title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
CodeIgniter - Basic Concepts | A controller is a simple class file. As the name suggests, it controls the whole application by URI.
First, go to application/controllers folder. You will find two files there, index.html and Welcome.php. These files come with the CodeIgniter.
Keep these files as they are. Create a new file under the same path named “Test.php”. Write the following code in that file −
<?php
class Test extends CI_Controller {
public function index() {
echo "Hello World!";
}
}
?>
The Test class extends an in-built class called CI_Controller. This class must be extended whenever you want to make your own Controller class.
The above controller can be called by URI as follows −
http://www.your-domain.com/index.php/test
Notice the word “test” in the above URI after index.php. This indicates the class name of controller. As we have given the name of the controller “Test”, we are writing “test” after the index.php. The class name must start with uppercase letter but we need to write lowercase letter when we call that controller by URI. The general syntax for calling the controller is as follows −
http://www.your-domain.com/index.php/controller/method-name
Let us modify the above class and create another method named “hello”.
<?php
class Test extends CI_Controller {
public function index() {
echo "This is default function.";
}
public function hello() {
echo "This is hello function.";
}
}
?>
We can execute the above controller in the following three ways −
http://www.your-domain.com/index.php/test
http://www.your-domain.com/index.php/test/index
http://www.your-domain.com/index.php/test/hello
After visiting the first URI in the browser, we get the output as shown in the picture given below. As you can see, we got the output of the method “index”, even though we did not pass the name of the method the URI. We have used only controller name in the URI. In such situations, the CodeIgniter calls the default method “index”.
Visiting the second URI in the browser, we get the same output as shown in the above picture. Here, we have passed method’s name after controller’s name in the URI. As the name of the method is “index”, we are getting the same output.
Visiting the third URI in the browser, we get the output as shown in picture given below. As you can see, we are getting the output of the method “hello” because we have passed “hello” as the method name, after the name of the controller “test” in the URI.
The name of the controller class must start with an uppercase letter.
The name of the controller class must start with an uppercase letter.
The controller must be called with lowercase letter.
The controller must be called with lowercase letter.
Do not use the same name of the method as your parent class, as it will override parent class’s functionality.
Do not use the same name of the method as your parent class, as it will override parent class’s functionality.
This can be a simple or complex webpage, which can be called by the controller. The webpage may contain header, footer, sidebar etc. View cannot be called directly. Let us create a simple view. Create a new file under application/views with name “test.php” and copy the below given code in that file.
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>CodeIgniter View Example</title>
</head>
<body>
CodeIgniter View Example
</body>
</html>
Change the code of application/controllers/test.php file as shown in the below.
The view can be loaded by the following syntax −
$this->load->view('name');
Where name is the view file, which is being rendered. If you have planned to store the view file in some directory then you can use the following syntax −
$this->load->view('directory-name/name');
It is not necessary to specify the extension as php, unless something other than .php is used.
The index() method is calling the view method and passing the “test” as argument to view() method because we have stored the html coding in “test.php” file under application/views/test.php.
<?php
class Test extends CI_Controller {
public function index() {
$this->load->view('test');
}
}
?>
Here is the output of the above code −
The following flowchart illustrates of how everything works −
Models classes are designed to work with information in the database. As an example, if you are using CodeIgniter to manage users in your application then you must have model class, which contains functions to insert, delete, update and retrieve your users’ data.
Model classes are stored in application/models directory. Following code shows how to create model class in CodeIgniter.
<?php
Class Model_name extends CI_Model {
Public function __construct() {
parent::__construct();
}
}
?>
Where Model_name is the name of the model class that you want to give. Each model class must inherit the CodeIgniter’s CI_Model class. The first letter of the model class must be in capital letter. Following is the code for users’ model class.
<?php
Class User_model extends CI_Model {
Public function __construct() {
parent::__construct();
}
}
?>
The above model class must be saved as User_model.php. The class name and file name must be same.
Model can be called in controller. Following code can be used to load any model.
$this->load->model('model_name');
Where model_name is the name of the model to be loaded. After loading the model you can simply call its method as shown below.
$this->model_name->method();
There may be situations where you want some model class throughout your application. In such situations, it is better if we autoload it.
/*
| ---------------------------------------------------------------
| Auto-Load Models
| ---------------------------------------------------------------
| Prototype:
|
| $autoload['model'] = array('first_model', 'second_model');
|
| You can also supply an alternative model name to be assigned
| in the controller:
|
| $autoload['model'] = array('first_model' => 'first');
*/
$autoload['model'] = array();
As shown in the above figure, pass the name of the model in the array that you want to autoload and it will be autoloaded, while system is in initialization state and is accessible throughout the application.
As the name suggests, it will help you build your system. It is divided into small functions to serve different functionality. A number of helpers are available in CodeIgniter, which are listed in the table below. We can build our own helpers too.
Helpers are typically stored in your system/helpers, or application/helpers directory. Custom helpers are stored in application/helpers directory and systems’ helpers are stored in system/helpers directory. CodeIgniter will look first in your application/helpers directory. If the directory does not exist or the specified helper is not located, CodeIgniter will instead, look in your global system/helpers/ directory. Each helper, whether it is custom or system helper, must be loaded before using it.
Array Helper
The Array Helper file contains functions that assist in working with arrays.
CAPTCHA Helper
The CAPTCHA Helper file contains functions that assist in creating CAPTCHA images.
Cookie Helper
The Cookie Helper file contains functions that assist in working with cookies.
Date Helper
The Date Helper file contains functions that help you work with dates.
Directory Helper
The Directory Helper file contains functions that assist in working with directories.
Download Helper
The Download Helper lets you download data to your desktop.
Email Helper
The Email Helper provides some assistive functions for working with Email. For a more robust email solution, see CodeIgniter’s Email Class.
File Helper
The File Helper file contains functions that assist in working with files.
Form Helper
The Form Helper file contains functions that assist in working with forms.
HTML Helper
The HTML Helper file contains functions that assist in working with HTML.
Inflector Helper
The Inflector Helper file contains functions that permits you to change words to plural, singular, camel case, etc.
Language Helper
The Language Helper file contains functions that assist in working with language files.
Number Helper
The Number Helper file contains functions that help you work with numeric data.
Path Helper
The Path Helper file contains functions that permits you to work with file paths on the server.
Security Helper
The Security Helper file contains security related functions.
Smiley Helper
The Smiley Helper file contains functions that let you manage smileys (emoticons).
String Helper
The String Helper file contains functions that assist in working with strings.
Text Helper
The Text Helper file contains functions that assist in working with text.
Typography Helper
The Typography Helper file contains functions that help your format text in semantically relevant ways.
URL Helper
The URL Helper file contains functions that assist in working with URLs.
XML Helper
The XML Helper file contains functions that assist in working with XML data.
A helper can be loaded as shown below −
$this->load->helper('name');
Where name is the name of the helper. For example, if you want to load the URL Helper, then it can be loaded as −
$this->load->helper('url');
CodeIgniter has user-friendly URI routing system, so that you can easily re-route URL. Typically, there is a one-to-one relationship between a URL string and its corresponding controller class/method. The segments in a URI normally follow this pattern −
your-domain.com/class/method/id/
The first segment represents the controller class that should be invoked.
The first segment represents the controller class that should be invoked.
The second segment represents the class function, or method, that should be called.
The second segment represents the class function, or method, that should be called.
The third, and any additional segments, represent the ID and any variables that will be passed to the controller.
The third, and any additional segments, represent the ID and any variables that will be passed to the controller.
In some situations, you may want to change this default routing mechanism. CodeIgniter provides facility through which you can set your own routing rules.
There is a particular file where you can handle all these. The file is located at application/config/routes.php. You will find an array called $route in which you can customize your routing rules. The key in the $route array will decide what to route and the value will decide where to route. There are three reserved routes in CodeIgniter.
$route['default_controller']
This route indicates which controller class should be loaded, if the URI contains no data, which will be the case when people load your root URL. You are encouraged to have a default route otherwise a 404 page will appear, by default. We can set home page of website here so it will be loaded by default.
$route['404_override']
This route indicates which controller class should be loaded if the requested controller is not found. It will override the default 404 error page. It won’t affect to the show_404() function, which will continue loading the default error_404.php file in application/views/errors/error_404.php.
$route['translate_uri_dashes']
As evident by the Boolean value, this is not exactly a route. This option enables you to automatically replace dashes (‘-‘) with underscores in the controller and method URI segments, thus saving you additional route entries if you need to do that. This is required because the dash is not a valid class or method-name character and will cause a fatal error, if you try to use it.
Routes can be customized by wildcards or by using regular expressions but keep in mind that these customized rules for routing must come after the reserved rules.
We can use two wildcard characters as explained below −
(:num) − It will match a segment containing only numbers.
(:num) − It will match a segment containing only numbers.
(:any) − It will match a segment containing any character.
(:any) − It will match a segment containing any character.
Example
$route['product/:num']='catalog/product_lookup';
In the above example, if the literal word “product” is found in the first segment of the URL, and a number is found in the second segment, the “catalog” class and the “product_lookup” method are used instead.
Like wildcards, we can also use regular expressions in $route array key part. If any URI matches with regular expression, then it will be routed to the value part set into $route array.
Example
$route['products/([a-z]+)/(\d+)']='$1/id_$2';
In the above example, a URI similar to products/shoes/123 would instead call the “shoes” controller class and the “id_123” method.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2420,
"s": 2319,
"text": "A controller is a simple class file. As the name suggests, it controls the whole application by URI."
},
{
"code": null,
"e": 2563,
"s": 2420,
"text": "First, go to application/controllers folder. You will find two files there, index.html and Welcome.php. These files come with the CodeIgniter."
},
{
"code": null,
"e": 2689,
"s": 2563,
"text": "Keep these files as they are. Create a new file under the same path named “Test.php”. Write the following code in that file −"
},
{
"code": null,
"e": 2819,
"s": 2689,
"text": "<?php \n class Test extends CI_Controller {\n \n public function index() { \n echo \"Hello World!\"; \n } \n } \n?>"
},
{
"code": null,
"e": 2963,
"s": 2819,
"text": "The Test class extends an in-built class called CI_Controller. This class must be extended whenever you want to make your own Controller class."
},
{
"code": null,
"e": 3018,
"s": 2963,
"text": "The above controller can be called by URI as follows −"
},
{
"code": null,
"e": 3061,
"s": 3018,
"text": "http://www.your-domain.com/index.php/test\n"
},
{
"code": null,
"e": 3444,
"s": 3061,
"text": "Notice the word “test” in the above URI after index.php. This indicates the class name of controller. As we have given the name of the controller “Test”, we are writing “test” after the index.php. The class name must start with uppercase letter but we need to write lowercase letter when we call that controller by URI. The general syntax for calling the controller is as follows −"
},
{
"code": null,
"e": 3505,
"s": 3444,
"text": "http://www.your-domain.com/index.php/controller/method-name\n"
},
{
"code": null,
"e": 3576,
"s": 3505,
"text": "Let us modify the above class and create another method named “hello”."
},
{
"code": null,
"e": 3807,
"s": 3576,
"text": "<?php \n class Test extends CI_Controller { \n\t\n public function index() { \n echo \"This is default function.\"; \n } \n \n public function hello() { \n echo \"This is hello function.\"; \n } \n } \n?>"
},
{
"code": null,
"e": 3873,
"s": 3807,
"text": "We can execute the above controller in the following three ways −"
},
{
"code": null,
"e": 3915,
"s": 3873,
"text": "http://www.your-domain.com/index.php/test"
},
{
"code": null,
"e": 3963,
"s": 3915,
"text": "http://www.your-domain.com/index.php/test/index"
},
{
"code": null,
"e": 4011,
"s": 3963,
"text": "http://www.your-domain.com/index.php/test/hello"
},
{
"code": null,
"e": 4344,
"s": 4011,
"text": "After visiting the first URI in the browser, we get the output as shown in the picture given below. As you can see, we got the output of the method “index”, even though we did not pass the name of the method the URI. We have used only controller name in the URI. In such situations, the CodeIgniter calls the default method “index”."
},
{
"code": null,
"e": 4579,
"s": 4344,
"text": "Visiting the second URI in the browser, we get the same output as shown in the above picture. Here, we have passed method’s name after controller’s name in the URI. As the name of the method is “index”, we are getting the same output."
},
{
"code": null,
"e": 4836,
"s": 4579,
"text": "Visiting the third URI in the browser, we get the output as shown in picture given below. As you can see, we are getting the output of the method “hello” because we have passed “hello” as the method name, after the name of the controller “test” in the URI."
},
{
"code": null,
"e": 4906,
"s": 4836,
"text": "The name of the controller class must start with an uppercase letter."
},
{
"code": null,
"e": 4976,
"s": 4906,
"text": "The name of the controller class must start with an uppercase letter."
},
{
"code": null,
"e": 5029,
"s": 4976,
"text": "The controller must be called with lowercase letter."
},
{
"code": null,
"e": 5082,
"s": 5029,
"text": "The controller must be called with lowercase letter."
},
{
"code": null,
"e": 5193,
"s": 5082,
"text": "Do not use the same name of the method as your parent class, as it will override parent class’s functionality."
},
{
"code": null,
"e": 5304,
"s": 5193,
"text": "Do not use the same name of the method as your parent class, as it will override parent class’s functionality."
},
{
"code": null,
"e": 5605,
"s": 5304,
"text": "This can be a simple or complex webpage, which can be called by the controller. The webpage may contain header, footer, sidebar etc. View cannot be called directly. Let us create a simple view. Create a new file under application/views with name “test.php” and copy the below given code in that file."
},
{
"code": null,
"e": 5810,
"s": 5605,
"text": "<!DOCTYPE html> \n<html lang = \"en\"> \n\n <head> \n <meta charset = \"utf-8\"> \n <title>CodeIgniter View Example</title> \n </head>\n\t\n <body> \n CodeIgniter View Example \n </body>\n\t\n</html>"
},
{
"code": null,
"e": 5890,
"s": 5810,
"text": "Change the code of application/controllers/test.php file as shown in the below."
},
{
"code": null,
"e": 5939,
"s": 5890,
"text": "The view can be loaded by the following syntax −"
},
{
"code": null,
"e": 5967,
"s": 5939,
"text": "$this->load->view('name');\n"
},
{
"code": null,
"e": 6122,
"s": 5967,
"text": "Where name is the view file, which is being rendered. If you have planned to store the view file in some directory then you can use the following syntax −"
},
{
"code": null,
"e": 6165,
"s": 6122,
"text": "$this->load->view('directory-name/name');\n"
},
{
"code": null,
"e": 6260,
"s": 6165,
"text": "It is not necessary to specify the extension as php, unless something other than .php is used."
},
{
"code": null,
"e": 6450,
"s": 6260,
"text": "The index() method is calling the view method and passing the “test” as argument to view() method because we have stored the html coding in “test.php” file under application/views/test.php."
},
{
"code": null,
"e": 6586,
"s": 6450,
"text": "<?php \n class Test extends CI_Controller { \n\t\n public function index() { \n $this->load->view('test'); \n } \n } \n?>"
},
{
"code": null,
"e": 6625,
"s": 6586,
"text": "Here is the output of the above code −"
},
{
"code": null,
"e": 6687,
"s": 6625,
"text": "The following flowchart illustrates of how everything works −"
},
{
"code": null,
"e": 6951,
"s": 6687,
"text": "Models classes are designed to work with information in the database. As an example, if you are using CodeIgniter to manage users in your application then you must have model class, which contains functions to insert, delete, update and retrieve your users’ data."
},
{
"code": null,
"e": 7072,
"s": 6951,
"text": "Model classes are stored in application/models directory. Following code shows how to create model class in CodeIgniter."
},
{
"code": null,
"e": 7212,
"s": 7072,
"text": "<?php \n Class Model_name extends CI_Model { \n\t\n Public function __construct() { \n parent::__construct(); \n } \n } \n?> "
},
{
"code": null,
"e": 7456,
"s": 7212,
"text": "Where Model_name is the name of the model class that you want to give. Each model class must inherit the CodeIgniter’s CI_Model class. The first letter of the model class must be in capital letter. Following is the code for users’ model class."
},
{
"code": null,
"e": 7597,
"s": 7456,
"text": "<?php \n Class User_model extends CI_Model {\n\t\n Public function __construct() { \n parent::__construct(); \n } \n\t\t\n } \n?>"
},
{
"code": null,
"e": 7695,
"s": 7597,
"text": "The above model class must be saved as User_model.php. The class name and file name must be same."
},
{
"code": null,
"e": 7776,
"s": 7695,
"text": "Model can be called in controller. Following code can be used to load any model."
},
{
"code": null,
"e": 7811,
"s": 7776,
"text": "$this->load->model('model_name');\n"
},
{
"code": null,
"e": 7938,
"s": 7811,
"text": "Where model_name is the name of the model to be loaded. After loading the model you can simply call its method as shown below."
},
{
"code": null,
"e": 7968,
"s": 7938,
"text": "$this->model_name->method();\n"
},
{
"code": null,
"e": 8105,
"s": 7968,
"text": "There may be situations where you want some model class throughout your application. In such situations, it is better if we autoload it."
},
{
"code": null,
"e": 8519,
"s": 8105,
"text": "/*\n| ---------------------------------------------------------------\n| Auto-Load Models\n| ---------------------------------------------------------------\n| Prototype:\n|\n| $autoload['model'] = array('first_model', 'second_model');\n|\n| You can also supply an alternative model name to be assigned\n| in the controller:\n| \n| $autoload['model'] = array('first_model' => 'first');\n*/\n$autoload['model'] = array();"
},
{
"code": null,
"e": 8728,
"s": 8519,
"text": "As shown in the above figure, pass the name of the model in the array that you want to autoload and it will be autoloaded, while system is in initialization state and is accessible throughout the application."
},
{
"code": null,
"e": 8976,
"s": 8728,
"text": "As the name suggests, it will help you build your system. It is divided into small functions to serve different functionality. A number of helpers are available in CodeIgniter, which are listed in the table below. We can build our own helpers too."
},
{
"code": null,
"e": 9479,
"s": 8976,
"text": "Helpers are typically stored in your system/helpers, or application/helpers directory. Custom helpers are stored in application/helpers directory and systems’ helpers are stored in system/helpers directory. CodeIgniter will look first in your application/helpers directory. If the directory does not exist or the specified helper is not located, CodeIgniter will instead, look in your global system/helpers/ directory. Each helper, whether it is custom or system helper, must be loaded before using it."
},
{
"code": null,
"e": 9492,
"s": 9479,
"text": "Array Helper"
},
{
"code": null,
"e": 9569,
"s": 9492,
"text": "The Array Helper file contains functions that assist in working with arrays."
},
{
"code": null,
"e": 9584,
"s": 9569,
"text": "CAPTCHA Helper"
},
{
"code": null,
"e": 9667,
"s": 9584,
"text": "The CAPTCHA Helper file contains functions that assist in creating CAPTCHA images."
},
{
"code": null,
"e": 9681,
"s": 9667,
"text": "Cookie Helper"
},
{
"code": null,
"e": 9760,
"s": 9681,
"text": "The Cookie Helper file contains functions that assist in working with cookies."
},
{
"code": null,
"e": 9772,
"s": 9760,
"text": "Date Helper"
},
{
"code": null,
"e": 9843,
"s": 9772,
"text": "The Date Helper file contains functions that help you work with dates."
},
{
"code": null,
"e": 9860,
"s": 9843,
"text": "Directory Helper"
},
{
"code": null,
"e": 9946,
"s": 9860,
"text": "The Directory Helper file contains functions that assist in working with directories."
},
{
"code": null,
"e": 9962,
"s": 9946,
"text": "Download Helper"
},
{
"code": null,
"e": 10022,
"s": 9962,
"text": "The Download Helper lets you download data to your desktop."
},
{
"code": null,
"e": 10035,
"s": 10022,
"text": "Email Helper"
},
{
"code": null,
"e": 10175,
"s": 10035,
"text": "The Email Helper provides some assistive functions for working with Email. For a more robust email solution, see CodeIgniter’s Email Class."
},
{
"code": null,
"e": 10187,
"s": 10175,
"text": "File Helper"
},
{
"code": null,
"e": 10262,
"s": 10187,
"text": "The File Helper file contains functions that assist in working with files."
},
{
"code": null,
"e": 10274,
"s": 10262,
"text": "Form Helper"
},
{
"code": null,
"e": 10349,
"s": 10274,
"text": "The Form Helper file contains functions that assist in working with forms."
},
{
"code": null,
"e": 10361,
"s": 10349,
"text": "HTML Helper"
},
{
"code": null,
"e": 10435,
"s": 10361,
"text": "The HTML Helper file contains functions that assist in working with HTML."
},
{
"code": null,
"e": 10452,
"s": 10435,
"text": "Inflector Helper"
},
{
"code": null,
"e": 10568,
"s": 10452,
"text": "The Inflector Helper file contains functions that permits you to change words to plural, singular, camel case, etc."
},
{
"code": null,
"e": 10584,
"s": 10568,
"text": "Language Helper"
},
{
"code": null,
"e": 10672,
"s": 10584,
"text": "The Language Helper file contains functions that assist in working with language files."
},
{
"code": null,
"e": 10686,
"s": 10672,
"text": "Number Helper"
},
{
"code": null,
"e": 10766,
"s": 10686,
"text": "The Number Helper file contains functions that help you work with numeric data."
},
{
"code": null,
"e": 10778,
"s": 10766,
"text": "Path Helper"
},
{
"code": null,
"e": 10874,
"s": 10778,
"text": "The Path Helper file contains functions that permits you to work with file paths on the server."
},
{
"code": null,
"e": 10890,
"s": 10874,
"text": "Security Helper"
},
{
"code": null,
"e": 10952,
"s": 10890,
"text": "The Security Helper file contains security related functions."
},
{
"code": null,
"e": 10966,
"s": 10952,
"text": "Smiley Helper"
},
{
"code": null,
"e": 11049,
"s": 10966,
"text": "The Smiley Helper file contains functions that let you manage smileys (emoticons)."
},
{
"code": null,
"e": 11063,
"s": 11049,
"text": "String Helper"
},
{
"code": null,
"e": 11142,
"s": 11063,
"text": "The String Helper file contains functions that assist in working with strings."
},
{
"code": null,
"e": 11154,
"s": 11142,
"text": "Text Helper"
},
{
"code": null,
"e": 11228,
"s": 11154,
"text": "The Text Helper file contains functions that assist in working with text."
},
{
"code": null,
"e": 11246,
"s": 11228,
"text": "Typography Helper"
},
{
"code": null,
"e": 11350,
"s": 11246,
"text": "The Typography Helper file contains functions that help your format text in semantically relevant ways."
},
{
"code": null,
"e": 11361,
"s": 11350,
"text": "URL Helper"
},
{
"code": null,
"e": 11434,
"s": 11361,
"text": "The URL Helper file contains functions that assist in working with URLs."
},
{
"code": null,
"e": 11445,
"s": 11434,
"text": "XML Helper"
},
{
"code": null,
"e": 11522,
"s": 11445,
"text": "The XML Helper file contains functions that assist in working with XML data."
},
{
"code": null,
"e": 11562,
"s": 11522,
"text": "A helper can be loaded as shown below −"
},
{
"code": null,
"e": 11592,
"s": 11562,
"text": "$this->load->helper('name');\n"
},
{
"code": null,
"e": 11706,
"s": 11592,
"text": "Where name is the name of the helper. For example, if you want to load the URL Helper, then it can be loaded as −"
},
{
"code": null,
"e": 11735,
"s": 11706,
"text": "$this->load->helper('url');\n"
},
{
"code": null,
"e": 11989,
"s": 11735,
"text": "CodeIgniter has user-friendly URI routing system, so that you can easily re-route URL. Typically, there is a one-to-one relationship between a URL string and its corresponding controller class/method. The segments in a URI normally follow this pattern −"
},
{
"code": null,
"e": 12023,
"s": 11989,
"text": "your-domain.com/class/method/id/\n"
},
{
"code": null,
"e": 12097,
"s": 12023,
"text": "The first segment represents the controller class that should be invoked."
},
{
"code": null,
"e": 12171,
"s": 12097,
"text": "The first segment represents the controller class that should be invoked."
},
{
"code": null,
"e": 12255,
"s": 12171,
"text": "The second segment represents the class function, or method, that should be called."
},
{
"code": null,
"e": 12339,
"s": 12255,
"text": "The second segment represents the class function, or method, that should be called."
},
{
"code": null,
"e": 12453,
"s": 12339,
"text": "The third, and any additional segments, represent the ID and any variables that will be passed to the controller."
},
{
"code": null,
"e": 12567,
"s": 12453,
"text": "The third, and any additional segments, represent the ID and any variables that will be passed to the controller."
},
{
"code": null,
"e": 12722,
"s": 12567,
"text": "In some situations, you may want to change this default routing mechanism. CodeIgniter provides facility through which you can set your own routing rules."
},
{
"code": null,
"e": 13063,
"s": 12722,
"text": "There is a particular file where you can handle all these. The file is located at application/config/routes.php. You will find an array called $route in which you can customize your routing rules. The key in the $route array will decide what to route and the value will decide where to route. There are three reserved routes in CodeIgniter."
},
{
"code": null,
"e": 13092,
"s": 13063,
"text": "$route['default_controller']"
},
{
"code": null,
"e": 13397,
"s": 13092,
"text": "This route indicates which controller class should be loaded, if the URI contains no data, which will be the case when people load your root URL. You are encouraged to have a default route otherwise a 404 page will appear, by default. We can set home page of website here so it will be loaded by default."
},
{
"code": null,
"e": 13420,
"s": 13397,
"text": "$route['404_override']"
},
{
"code": null,
"e": 13714,
"s": 13420,
"text": "This route indicates which controller class should be loaded if the requested controller is not found. It will override the default 404 error page. It won’t affect to the show_404() function, which will continue loading the default error_404.php file in application/views/errors/error_404.php."
},
{
"code": null,
"e": 13745,
"s": 13714,
"text": "$route['translate_uri_dashes']"
},
{
"code": null,
"e": 14126,
"s": 13745,
"text": "As evident by the Boolean value, this is not exactly a route. This option enables you to automatically replace dashes (‘-‘) with underscores in the controller and method URI segments, thus saving you additional route entries if you need to do that. This is required because the dash is not a valid class or method-name character and will cause a fatal error, if you try to use it."
},
{
"code": null,
"e": 14289,
"s": 14126,
"text": "Routes can be customized by wildcards or by using regular expressions but keep in mind that these customized rules for routing must come after the reserved rules."
},
{
"code": null,
"e": 14345,
"s": 14289,
"text": "We can use two wildcard characters as explained below −"
},
{
"code": null,
"e": 14403,
"s": 14345,
"text": "(:num) − It will match a segment containing only numbers."
},
{
"code": null,
"e": 14461,
"s": 14403,
"text": "(:num) − It will match a segment containing only numbers."
},
{
"code": null,
"e": 14520,
"s": 14461,
"text": "(:any) − It will match a segment containing any character."
},
{
"code": null,
"e": 14579,
"s": 14520,
"text": "(:any) − It will match a segment containing any character."
},
{
"code": null,
"e": 14587,
"s": 14579,
"text": "Example"
},
{
"code": null,
"e": 14637,
"s": 14587,
"text": "$route['product/:num']='catalog/product_lookup';\n"
},
{
"code": null,
"e": 14846,
"s": 14637,
"text": "In the above example, if the literal word “product” is found in the first segment of the URL, and a number is found in the second segment, the “catalog” class and the “product_lookup” method are used instead."
},
{
"code": null,
"e": 15032,
"s": 14846,
"text": "Like wildcards, we can also use regular expressions in $route array key part. If any URI matches with regular expression, then it will be routed to the value part set into $route array."
},
{
"code": null,
"e": 15040,
"s": 15032,
"text": "Example"
},
{
"code": null,
"e": 15087,
"s": 15040,
"text": "$route['products/([a-z]+)/(\\d+)']='$1/id_$2';\n"
},
{
"code": null,
"e": 15218,
"s": 15087,
"text": "In the above example, a URI similar to products/shoes/123 would instead call the “shoes” controller class and the “id_123” method."
},
{
"code": null,
"e": 15225,
"s": 15218,
"text": " Print"
},
{
"code": null,
"e": 15236,
"s": 15225,
"text": " Add Notes"
}
] |
BigInteger add() Method in Java with Examples - GeeksforGeeks | 04 Apr, 2019
The java.math.BigInteger.add(BigInteger val) is used to calculate the Arithmetic sum of two BigIntegers. This method is used to find arithmetic addition of large numbers of range much greater than the range of biggest data type double of java without compromising with the precision of the result. This method performs an operation upon the current BigInteger by which this method is called and BigInteger passed as the parameter.
Syntax:
public BigInteger add(BigInteger val)
Parameters: This method accepts a parameter val which is the value to be added to this BigInteger.
Return value: This method returns a BigInteger which holds sum (this + val).
Below programs is used to illustrate the add() method of BigInteger.
Example 1:
// Java program to demonstrate// add() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // BigInteger object to store result BigInteger sum; // For user input // Use Scanner or BufferedReader // Two objects of String created // Holds the values to calculate the sum String input1 = "5454564684456454684646454545"; String input2 = "4256456484464684864864864864"; // Convert the string input to BigInteger BigInteger a = new BigInteger(input1); BigInteger b = new BigInteger(input2); // Using add() method sum = a.add(b); // Display the result in BigInteger System.out.println("The sum of\n" + a + " \nand\n" + b + " " + "\nis\n" + sum + "\n"); }}
Output:
The sum of5454564684456454684646454545and4256456484464684864864864864is9711021168921139549511319409
As you can see from above example the data is full precised even after adding number of very large length.
Example 2:
// Java program to demonstrate// add() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // BigInteger object to store result BigInteger sum; // double variable // To store result as double double d; // For user input // Use Scanner or BufferedReader // Two objects of String // Holds the values to sum // The number's length is of 400 digits // Which is out of range of double String input1 = "012345678901234567" + "8901234567890123" + "4567890123456789" + "0123456789012345" + "6789012345678901" + "2345678901234567" + "8901234567890123" + "4567890123456789" + "0123456789012345" + "6789012345678901" + "2345678901234567" + "8901234567890123" + "4567890123456789" + "0123456789012345" + "6789012345678901" + "2345678901234567" + "8901234567890123" + "4554324324362432" + "7674637264783264" + "7832678463726478" + "3264736274673864" + "7364732463546354" + "6354632564532645" + "6325463546536453" + "6546325463546534" + "6325465345326456" + "4635463263453264" + "654632498739473"; String input2 = "0123456789012345" + "6789012345678901" + "2345678901234567" + "8901234567890123" + "4567890123456789" + "0123456789012345" + "6789012345678901" + "2345678901234567" + "8901234567890123" + "4567890123456789" + "0123456789012345" + "6789012345678901" + "2345678901234567" + "8901234567890123" + "4567890123456789" + "0123456789012345" + "6789012345678901" + "2345873271893718" + "2974897146378481" + "7489127847281478" + "2174871248721847" + "8748327463756475" + "6745781641263981" + "2839721897438974" + "3286574365764576" + "2376914689217817" + "4362473624721647" + "61247612748612746"; // convert the string input to BigInteger BigInteger a = new BigInteger(input1); BigInteger b = new BigInteger(input2); // Using add() method sum = a.add(b); // Display the result in BigInteger System.out.println("The sum of\n" + a + " \nand\n" + b + " " + "\nis\n" + sum); // Using double to hold the result d = Double.parseDouble(sum.toString()); // Display the result in double System.out.println("Using double, Sum is " + d); }}
Output:
The sum of1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234554324324362432767463726478326478326784637264783264736274673864736473246354635463546325645326456325463546536453654632546354653463254653453264564635463263453264654632498739473and1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234587327189371829748971463784817489127847281478217487124872184787483274637564756745781641263981283972189743897432865743657645762376914689217817436247362472164761247612748612746is2469135780246913578024691357802469135780246913578024691357802469135780246913578024691357802469135780246913578024691357802469135780246913578024691357802469135780246913578024691357802469135780246913578024691357802469135780246913578024691357802469135780246913578024691357802469141651513734262516435190263143967454631918743000751861146858652219747883919392209327966909307740297653290433886520376204000415840169342671082000882825735618025902245247352219Using double, Sum is Infinity
As from above output it is clear that using double for bigger integer numbers is not a good choice.Reference: https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/math/BigInteger.html#add(java.math.BigInteger)
Java-BigInteger
Java-Functions
Java-math-package
Java
Java-BigInteger
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Multidimensional Arrays in Java
Stream In Java
Stack Class in Java
Singleton Class in Java | [
{
"code": null,
"e": 24406,
"s": 24378,
"text": "\n04 Apr, 2019"
},
{
"code": null,
"e": 24837,
"s": 24406,
"text": "The java.math.BigInteger.add(BigInteger val) is used to calculate the Arithmetic sum of two BigIntegers. This method is used to find arithmetic addition of large numbers of range much greater than the range of biggest data type double of java without compromising with the precision of the result. This method performs an operation upon the current BigInteger by which this method is called and BigInteger passed as the parameter."
},
{
"code": null,
"e": 24845,
"s": 24837,
"text": "Syntax:"
},
{
"code": null,
"e": 24884,
"s": 24845,
"text": "public BigInteger add(BigInteger val)\n"
},
{
"code": null,
"e": 24983,
"s": 24884,
"text": "Parameters: This method accepts a parameter val which is the value to be added to this BigInteger."
},
{
"code": null,
"e": 25060,
"s": 24983,
"text": "Return value: This method returns a BigInteger which holds sum (this + val)."
},
{
"code": null,
"e": 25129,
"s": 25060,
"text": "Below programs is used to illustrate the add() method of BigInteger."
},
{
"code": null,
"e": 25140,
"s": 25129,
"text": "Example 1:"
},
{
"code": "// Java program to demonstrate// add() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // BigInteger object to store result BigInteger sum; // For user input // Use Scanner or BufferedReader // Two objects of String created // Holds the values to calculate the sum String input1 = \"5454564684456454684646454545\"; String input2 = \"4256456484464684864864864864\"; // Convert the string input to BigInteger BigInteger a = new BigInteger(input1); BigInteger b = new BigInteger(input2); // Using add() method sum = a.add(b); // Display the result in BigInteger System.out.println(\"The sum of\\n\" + a + \" \\nand\\n\" + b + \" \" + \"\\nis\\n\" + sum + \"\\n\"); }}",
"e": 26069,
"s": 25140,
"text": null
},
{
"code": null,
"e": 26077,
"s": 26069,
"text": "Output:"
},
{
"code": null,
"e": 26177,
"s": 26077,
"text": "The sum of5454564684456454684646454545and4256456484464684864864864864is9711021168921139549511319409"
},
{
"code": null,
"e": 26284,
"s": 26177,
"text": "As you can see from above example the data is full precised even after adding number of very large length."
},
{
"code": null,
"e": 26295,
"s": 26284,
"text": "Example 2:"
},
{
"code": "// Java program to demonstrate// add() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // BigInteger object to store result BigInteger sum; // double variable // To store result as double double d; // For user input // Use Scanner or BufferedReader // Two objects of String // Holds the values to sum // The number's length is of 400 digits // Which is out of range of double String input1 = \"012345678901234567\" + \"8901234567890123\" + \"4567890123456789\" + \"0123456789012345\" + \"6789012345678901\" + \"2345678901234567\" + \"8901234567890123\" + \"4567890123456789\" + \"0123456789012345\" + \"6789012345678901\" + \"2345678901234567\" + \"8901234567890123\" + \"4567890123456789\" + \"0123456789012345\" + \"6789012345678901\" + \"2345678901234567\" + \"8901234567890123\" + \"4554324324362432\" + \"7674637264783264\" + \"7832678463726478\" + \"3264736274673864\" + \"7364732463546354\" + \"6354632564532645\" + \"6325463546536453\" + \"6546325463546534\" + \"6325465345326456\" + \"4635463263453264\" + \"654632498739473\"; String input2 = \"0123456789012345\" + \"6789012345678901\" + \"2345678901234567\" + \"8901234567890123\" + \"4567890123456789\" + \"0123456789012345\" + \"6789012345678901\" + \"2345678901234567\" + \"8901234567890123\" + \"4567890123456789\" + \"0123456789012345\" + \"6789012345678901\" + \"2345678901234567\" + \"8901234567890123\" + \"4567890123456789\" + \"0123456789012345\" + \"6789012345678901\" + \"2345873271893718\" + \"2974897146378481\" + \"7489127847281478\" + \"2174871248721847\" + \"8748327463756475\" + \"6745781641263981\" + \"2839721897438974\" + \"3286574365764576\" + \"2376914689217817\" + \"4362473624721647\" + \"61247612748612746\"; // convert the string input to BigInteger BigInteger a = new BigInteger(input1); BigInteger b = new BigInteger(input2); // Using add() method sum = a.add(b); // Display the result in BigInteger System.out.println(\"The sum of\\n\" + a + \" \\nand\\n\" + b + \" \" + \"\\nis\\n\" + sum); // Using double to hold the result d = Double.parseDouble(sum.toString()); // Display the result in double System.out.println(\"Using double, Sum is \" + d); }}",
"e": 29914,
"s": 26295,
"text": null
},
{
"code": null,
"e": 29922,
"s": 29914,
"text": "Output:"
},
{
"code": null,
"e": 31311,
"s": 29922,
"text": "The sum of1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234554324324362432767463726478326478326784637264783264736274673864736473246354635463546325645326456325463546536453654632546354653463254653453264564635463263453264654632498739473and1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234587327189371829748971463784817489127847281478217487124872184787483274637564756745781641263981283972189743897432865743657645762376914689217817436247362472164761247612748612746is2469135780246913578024691357802469135780246913578024691357802469135780246913578024691357802469135780246913578024691357802469135780246913578024691357802469135780246913578024691357802469135780246913578024691357802469135780246913578024691357802469135780246913578024691357802469141651513734262516435190263143967454631918743000751861146858652219747883919392209327966909307740297653290433886520376204000415840169342671082000882825735618025902245247352219Using double, Sum is Infinity"
},
{
"code": null,
"e": 31534,
"s": 31311,
"text": "As from above output it is clear that using double for bigger integer numbers is not a good choice.Reference: https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/math/BigInteger.html#add(java.math.BigInteger)"
},
{
"code": null,
"e": 31550,
"s": 31534,
"text": "Java-BigInteger"
},
{
"code": null,
"e": 31565,
"s": 31550,
"text": "Java-Functions"
},
{
"code": null,
"e": 31583,
"s": 31565,
"text": "Java-math-package"
},
{
"code": null,
"e": 31588,
"s": 31583,
"text": "Java"
},
{
"code": null,
"e": 31604,
"s": 31588,
"text": "Java-BigInteger"
},
{
"code": null,
"e": 31609,
"s": 31604,
"text": "Java"
},
{
"code": null,
"e": 31707,
"s": 31609,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31739,
"s": 31707,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 31790,
"s": 31739,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 31820,
"s": 31790,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 31839,
"s": 31820,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 31870,
"s": 31839,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 31888,
"s": 31870,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 31920,
"s": 31888,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 31935,
"s": 31920,
"text": "Stream In Java"
},
{
"code": null,
"e": 31955,
"s": 31935,
"text": "Stack Class in Java"
}
] |
How to tell ReactJS to build project in Production mode ? - GeeksforGeeks | 30 Aug, 2021
In development mode, React includes many warnings to help in finding problems before they lead to bugs. Doing so, it increases the bundle size and makes the app run slower. The slowdown may be accepted while working on the app locally but we cannot afford this in deployment.
In development mode React, internally, uses several clever techniques to minimize the number of costly DOM operations required to update UI. Nevertheless, there are several ways we can speed up our React application – production builds being one of them.
What will production build do?
The production build creates minified bundles, lighter-weight source maps, and optimized assets. This improves the load time. React recommends using production mode while deploying the react app. We now know that production build helps in optimizing performance.
Let’s see now how to create react app in production mode.
Creating React Application using Create React App:
Step 1: Open terminal and run the following command to create project folder of the react application:npx create-react-app myapp
Step 1: Open terminal and run the following command to create project folder of the react application:
npx create-react-app myapp
Step 2: Move into the project folder:cd myapp
Step 2: Move into the project folder:
cd myapp
Project Structure: The initial project structure will look like the following.
project structure
Step 3: Now edit the App.js file in the project and replace pre-existing code with the following code.
App.js
import logo from './logo.svg';import './App.css'; function App() { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <p> This is my React App. </p> </header> </div> );} export default App;
Step to run the application: Go to the root of the project folder and run one of the following commands:
npm start
Output: The app will run on port 3000 and the output screen will look like this:
Output Screen
Step 4: Now create the production build of the app. React App makes it quite simple to build in production. If your project is build with create-react-app, go to the root directory of the project and run:
npm run build
creating production build
This will create a build directory with production build of the app. Your JavaScript and CSS files will be inside the build/static directory. A number of .js files are generated and placed inside the build/static/js directory. These are called chunks.
JS chunks created after production build
Step 5: Running the app in production mode. We will serve the build version with a static server: In production mode the react app will run on port 5000.
serve -s build
App running in production mode
Now let’ see how to know whether the build process was setup correctly
1. We will be using React Developer Tools for Chrome . When this extension is installed and running and we visit a site with react in production mode, the react icon will have dark background.
Production mode
2. If you visit a site with React in development mode, the icon will have a red background:
development mode
Picked
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set background images in ReactJS ?
ReactJS useNavigate() Hook
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
React-Router Hooks
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 24826,
"s": 24798,
"text": "\n30 Aug, 2021"
},
{
"code": null,
"e": 25102,
"s": 24826,
"text": "In development mode, React includes many warnings to help in finding problems before they lead to bugs. Doing so, it increases the bundle size and makes the app run slower. The slowdown may be accepted while working on the app locally but we cannot afford this in deployment."
},
{
"code": null,
"e": 25358,
"s": 25102,
"text": "In development mode React, internally, uses several clever techniques to minimize the number of costly DOM operations required to update UI. Nevertheless, there are several ways we can speed up our React application – production builds being one of them. "
},
{
"code": null,
"e": 25389,
"s": 25358,
"text": "What will production build do?"
},
{
"code": null,
"e": 25653,
"s": 25389,
"text": "The production build creates minified bundles, lighter-weight source maps, and optimized assets. This improves the load time. React recommends using production mode while deploying the react app. We now know that production build helps in optimizing performance. "
},
{
"code": null,
"e": 25713,
"s": 25655,
"text": "Let’s see now how to create react app in production mode."
},
{
"code": null,
"e": 25764,
"s": 25713,
"text": "Creating React Application using Create React App:"
},
{
"code": null,
"e": 25893,
"s": 25764,
"text": "Step 1: Open terminal and run the following command to create project folder of the react application:npx create-react-app myapp"
},
{
"code": null,
"e": 25996,
"s": 25893,
"text": "Step 1: Open terminal and run the following command to create project folder of the react application:"
},
{
"code": null,
"e": 26023,
"s": 25996,
"text": "npx create-react-app myapp"
},
{
"code": null,
"e": 26069,
"s": 26023,
"text": "Step 2: Move into the project folder:cd myapp"
},
{
"code": null,
"e": 26107,
"s": 26069,
"text": "Step 2: Move into the project folder:"
},
{
"code": null,
"e": 26116,
"s": 26107,
"text": "cd myapp"
},
{
"code": null,
"e": 26195,
"s": 26116,
"text": "Project Structure: The initial project structure will look like the following."
},
{
"code": null,
"e": 26213,
"s": 26195,
"text": "project structure"
},
{
"code": null,
"e": 26316,
"s": 26213,
"text": "Step 3: Now edit the App.js file in the project and replace pre-existing code with the following code."
},
{
"code": null,
"e": 26323,
"s": 26316,
"text": "App.js"
},
{
"code": "import logo from './logo.svg';import './App.css'; function App() { return ( <div className=\"App\"> <header className=\"App-header\"> <img src={logo} className=\"App-logo\" alt=\"logo\" /> <p> This is my React App. </p> </header> </div> );} export default App;",
"e": 26628,
"s": 26323,
"text": null
},
{
"code": null,
"e": 26735,
"s": 26630,
"text": "Step to run the application: Go to the root of the project folder and run one of the following commands:"
},
{
"code": null,
"e": 26745,
"s": 26735,
"text": "npm start"
},
{
"code": null,
"e": 26826,
"s": 26745,
"text": "Output: The app will run on port 3000 and the output screen will look like this:"
},
{
"code": null,
"e": 26840,
"s": 26826,
"text": "Output Screen"
},
{
"code": null,
"e": 27045,
"s": 26840,
"text": "Step 4: Now create the production build of the app. React App makes it quite simple to build in production. If your project is build with create-react-app, go to the root directory of the project and run:"
},
{
"code": null,
"e": 27059,
"s": 27045,
"text": "npm run build"
},
{
"code": null,
"e": 27085,
"s": 27059,
"text": "creating production build"
},
{
"code": null,
"e": 27337,
"s": 27085,
"text": "This will create a build directory with production build of the app. Your JavaScript and CSS files will be inside the build/static directory. A number of .js files are generated and placed inside the build/static/js directory. These are called chunks."
},
{
"code": null,
"e": 27378,
"s": 27337,
"text": "JS chunks created after production build"
},
{
"code": null,
"e": 27532,
"s": 27378,
"text": "Step 5: Running the app in production mode. We will serve the build version with a static server: In production mode the react app will run on port 5000."
},
{
"code": null,
"e": 27547,
"s": 27532,
"text": "serve -s build"
},
{
"code": null,
"e": 27578,
"s": 27547,
"text": "App running in production mode"
},
{
"code": null,
"e": 27649,
"s": 27578,
"text": "Now let’ see how to know whether the build process was setup correctly"
},
{
"code": null,
"e": 27843,
"s": 27649,
"text": "1. We will be using React Developer Tools for Chrome . When this extension is installed and running and we visit a site with react in production mode, the react icon will have dark background. "
},
{
"code": null,
"e": 27859,
"s": 27843,
"text": "Production mode"
},
{
"code": null,
"e": 27951,
"s": 27859,
"text": "2. If you visit a site with React in development mode, the icon will have a red background:"
},
{
"code": null,
"e": 27968,
"s": 27951,
"text": "development mode"
},
{
"code": null,
"e": 27975,
"s": 27968,
"text": "Picked"
},
{
"code": null,
"e": 27991,
"s": 27975,
"text": "React-Questions"
},
{
"code": null,
"e": 27999,
"s": 27991,
"text": "ReactJS"
},
{
"code": null,
"e": 28016,
"s": 27999,
"text": "Web Technologies"
},
{
"code": null,
"e": 28114,
"s": 28016,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28156,
"s": 28114,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 28183,
"s": 28156,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 28218,
"s": 28183,
"text": "How to create a table in ReactJS ?"
},
{
"code": null,
"e": 28276,
"s": 28218,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 28295,
"s": 28276,
"text": "React-Router Hooks"
},
{
"code": null,
"e": 28337,
"s": 28295,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28370,
"s": 28337,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28432,
"s": 28370,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28477,
"s": 28432,
"text": "Convert a string to an integer in JavaScript"
}
] |
CSS - Layers | CSS gives you opportunity to create layers of various divisions. The CSS layers refer to applying the z-index property to elements that overlap with each other.
The z-index property is used along with the position property to create an effect of layers. You can specify which element should come on top and which element should come at bottom.
A z-index property can help you to create more complex webpage layouts. Following is the example which shows how to create layers in CSS.
<html>
<head>
</head>
<body>
<div style = "background-color:red;
width:300px;
height:100px;
position:relative;
top:10px;
left:80px;
z-index:2">
</div>
<div style = "background-color:yellow;
width:300px;
height:100px;
position:relative;
top:-60px;
left:35px;
z-index:1;">
</div>
<div style = "background-color:green;
width:300px;
height:100px;
position:relative;
top:-220px;
left:120px;
z-index:3;">
</div>
</body>
</html>
It will produce the following result −
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": 2787,
"s": 2626,
"text": "CSS gives you opportunity to create layers of various divisions. The CSS layers refer to applying the z-index property to elements that overlap with each other."
},
{
"code": null,
"e": 2970,
"s": 2787,
"text": "The z-index property is used along with the position property to create an effect of layers. You can specify which element should come on top and which element should come at bottom."
},
{
"code": null,
"e": 3108,
"s": 2970,
"text": "A z-index property can help you to create more complex webpage layouts. Following is the example which shows how to create layers in CSS."
},
{
"code": null,
"e": 3774,
"s": 3108,
"text": "<html>\n <head>\n </head>\n\n <body>\n <div style = \"background-color:red; \n width:300px; \n height:100px; \n position:relative; \n top:10px; \n left:80px; \n z-index:2\">\n </div>\n \n <div style = \"background-color:yellow; \n width:300px; \n height:100px; \n position:relative; \n top:-60px; \n left:35px; \n z-index:1;\">\n </div>\n \n <div style = \"background-color:green; \n width:300px; \n height:100px; \n position:relative; \n top:-220px; \n left:120px; \n z-index:3;\">\n </div>\n </body>\n</html> "
},
{
"code": null,
"e": 3813,
"s": 3774,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 3848,
"s": 3813,
"text": "\n 33 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3862,
"s": 3848,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3897,
"s": 3862,
"text": "\n 26 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3914,
"s": 3897,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3949,
"s": 3914,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3980,
"s": 3949,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4015,
"s": 3980,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4046,
"s": 4015,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4081,
"s": 4046,
"text": "\n 51 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 4112,
"s": 4081,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4145,
"s": 4112,
"text": "\n 52 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4176,
"s": 4145,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4183,
"s": 4176,
"text": " Print"
},
{
"code": null,
"e": 4194,
"s": 4183,
"text": " Add Notes"
}
] |
PHP | MySQL UPDATE Query - GeeksforGeeks | 01 Aug, 2021
The MySQL UPDATE query is used to update existing records in a table in a MySQL database.
It can be used to update one or more field at the same time.
It can be used to specify any condition using the WHERE clause.Syntax :The basic syntax of the Update Query is –Implementation of Where Update Query :Let us consider the following table “Data” with four columns ‘ID’, ‘FirstName’, ‘LastName’ and ‘Age’.To update the “Age” of a person whose “ID” is 201 in the “Data” table, we can use the following code :Update Query using Procedural Method :<?php$link = mysqli_connect("localhost", "root", "", "Mydb"); if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error());} $sql = "UPDATE data SET Age='28' WHERE id=201";if(mysqli_query($link, $sql)){ echo "Record was updated successfully.";} else { echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);} mysqli_close($link);?>Output :Table After Updation –The output on Web Browser :Update Query using Object Oriented Method :<?php$mysqli = new mysqli("localhost", "root", "", "Mydb"); if($mysqli === false){ die("ERROR: Could not connect. " . $mysqli->connect_error);} $sql = "UPDATE data SET Age='28' WHERE id=201";if($mysqli->query($sql) === true){ echo "Records was updated successfully.";} else{ echo "ERROR: Could not able to execute $sql. " . $mysqli->error;}$mysqli->close();?>Output :Table After Updation –The output on Web Browser :Update Query using PDO Method :<?phptry{ $pdo = new PDO("mysql:host=localhost; dbname=Mydb", "root", ""); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);} catch(PDOException $e){ die("ERROR: Could not connect. " . $e->getMessage());} try{ $sql = "UPDATE data SET Age='28' WHERE id=201"; $pdo->exec($sql); echo "Records was updated successfully.";} catch(PDOException $e){ die("ERROR: Could not able to execute $sql. " . $e->getMessage());}unset($pdo);?>Output :Table After Updation –The output on Web Browser :PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.My Personal Notes
arrow_drop_upSave
Syntax :The basic syntax of the Update Query is –
Let us consider the following table “Data” with four columns ‘ID’, ‘FirstName’, ‘LastName’ and ‘Age’.
To update the “Age” of a person whose “ID” is 201 in the “Data” table, we can use the following code :
Update Query using Procedural Method :
<?php$link = mysqli_connect("localhost", "root", "", "Mydb"); if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error());} $sql = "UPDATE data SET Age='28' WHERE id=201";if(mysqli_query($link, $sql)){ echo "Record was updated successfully.";} else { echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);} mysqli_close($link);?>
Output :Table After Updation –
The output on Web Browser :
Update Query using Object Oriented Method :
<?php$mysqli = new mysqli("localhost", "root", "", "Mydb"); if($mysqli === false){ die("ERROR: Could not connect. " . $mysqli->connect_error);} $sql = "UPDATE data SET Age='28' WHERE id=201";if($mysqli->query($sql) === true){ echo "Records was updated successfully.";} else{ echo "ERROR: Could not able to execute $sql. " . $mysqli->error;}$mysqli->close();?>
Output :Table After Updation –
The output on Web Browser :
Update Query using PDO Method :
<?phptry{ $pdo = new PDO("mysql:host=localhost; dbname=Mydb", "root", ""); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);} catch(PDOException $e){ die("ERROR: Could not connect. " . $e->getMessage());} try{ $sql = "UPDATE data SET Age='28' WHERE id=201"; $pdo->exec($sql); echo "Records was updated successfully.";} catch(PDOException $e){ die("ERROR: Could not able to execute $sql. " . $e->getMessage());}unset($pdo);?>
Output :Table After Updation –
The output on Web Browser :
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
mysql
PHP
SQL
Web Technologies
SQL
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?
Comparing two dates in PHP
SQL | DDL, DQL, DML, DCL and TCL Commands
SQL | WITH clause
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
SQL Trigger | Student Database | [
{
"code": null,
"e": 24345,
"s": 24317,
"text": "\n01 Aug, 2021"
},
{
"code": null,
"e": 24435,
"s": 24345,
"text": "The MySQL UPDATE query is used to update existing records in a table in a MySQL database."
},
{
"code": null,
"e": 24496,
"s": 24435,
"text": "It can be used to update one or more field at the same time."
},
{
"code": null,
"e": 26729,
"s": 24496,
"text": "It can be used to specify any condition using the WHERE clause.Syntax :The basic syntax of the Update Query is –Implementation of Where Update Query :Let us consider the following table “Data” with four columns ‘ID’, ‘FirstName’, ‘LastName’ and ‘Age’.To update the “Age” of a person whose “ID” is 201 in the “Data” table, we can use the following code :Update Query using Procedural Method :<?php$link = mysqli_connect(\"localhost\", \"root\", \"\", \"Mydb\"); if($link === false){ die(\"ERROR: Could not connect. \" . mysqli_connect_error());} $sql = \"UPDATE data SET Age='28' WHERE id=201\";if(mysqli_query($link, $sql)){ echo \"Record was updated successfully.\";} else { echo \"ERROR: Could not able to execute $sql. \" . mysqli_error($link);} mysqli_close($link);?>Output :Table After Updation –The output on Web Browser :Update Query using Object Oriented Method :<?php$mysqli = new mysqli(\"localhost\", \"root\", \"\", \"Mydb\"); if($mysqli === false){ die(\"ERROR: Could not connect. \" . $mysqli->connect_error);} $sql = \"UPDATE data SET Age='28' WHERE id=201\";if($mysqli->query($sql) === true){ echo \"Records was updated successfully.\";} else{ echo \"ERROR: Could not able to execute $sql. \" . $mysqli->error;}$mysqli->close();?>Output :Table After Updation –The output on Web Browser :Update Query using PDO Method :<?phptry{ $pdo = new PDO(\"mysql:host=localhost; dbname=Mydb\", \"root\", \"\"); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);} catch(PDOException $e){ die(\"ERROR: Could not connect. \" . $e->getMessage());} try{ $sql = \"UPDATE data SET Age='28' WHERE id=201\"; $pdo->exec($sql); echo \"Records was updated successfully.\";} catch(PDOException $e){ die(\"ERROR: Could not able to execute $sql. \" . $e->getMessage());}unset($pdo);?>Output :Table After Updation –The output on Web Browser :PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 26779,
"s": 26729,
"text": "Syntax :The basic syntax of the Update Query is –"
},
{
"code": null,
"e": 26881,
"s": 26779,
"text": "Let us consider the following table “Data” with four columns ‘ID’, ‘FirstName’, ‘LastName’ and ‘Age’."
},
{
"code": null,
"e": 26984,
"s": 26881,
"text": "To update the “Age” of a person whose “ID” is 201 in the “Data” table, we can use the following code :"
},
{
"code": null,
"e": 27023,
"s": 26984,
"text": "Update Query using Procedural Method :"
},
{
"code": "<?php$link = mysqli_connect(\"localhost\", \"root\", \"\", \"Mydb\"); if($link === false){ die(\"ERROR: Could not connect. \" . mysqli_connect_error());} $sql = \"UPDATE data SET Age='28' WHERE id=201\";if(mysqli_query($link, $sql)){ echo \"Record was updated successfully.\";} else { echo \"ERROR: Could not able to execute $sql. \" . mysqli_error($link);} mysqli_close($link);?>",
"e": 27443,
"s": 27023,
"text": null
},
{
"code": null,
"e": 27474,
"s": 27443,
"text": "Output :Table After Updation –"
},
{
"code": null,
"e": 27502,
"s": 27474,
"text": "The output on Web Browser :"
},
{
"code": null,
"e": 27546,
"s": 27502,
"text": "Update Query using Object Oriented Method :"
},
{
"code": "<?php$mysqli = new mysqli(\"localhost\", \"root\", \"\", \"Mydb\"); if($mysqli === false){ die(\"ERROR: Could not connect. \" . $mysqli->connect_error);} $sql = \"UPDATE data SET Age='28' WHERE id=201\";if($mysqli->query($sql) === true){ echo \"Records was updated successfully.\";} else{ echo \"ERROR: Could not able to execute $sql. \" . $mysqli->error;}$mysqli->close();?>",
"e": 27968,
"s": 27546,
"text": null
},
{
"code": null,
"e": 27999,
"s": 27968,
"text": "Output :Table After Updation –"
},
{
"code": null,
"e": 28027,
"s": 27999,
"text": "The output on Web Browser :"
},
{
"code": null,
"e": 28059,
"s": 28027,
"text": "Update Query using PDO Method :"
},
{
"code": "<?phptry{ $pdo = new PDO(\"mysql:host=localhost; dbname=Mydb\", \"root\", \"\"); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);} catch(PDOException $e){ die(\"ERROR: Could not connect. \" . $e->getMessage());} try{ $sql = \"UPDATE data SET Age='28' WHERE id=201\"; $pdo->exec($sql); echo \"Records was updated successfully.\";} catch(PDOException $e){ die(\"ERROR: Could not able to execute $sql. \" . $e->getMessage());}unset($pdo);?>",
"e": 28613,
"s": 28059,
"text": null
},
{
"code": null,
"e": 28644,
"s": 28613,
"text": "Output :Table After Updation –"
},
{
"code": null,
"e": 28672,
"s": 28644,
"text": "The output on Web Browser :"
},
{
"code": null,
"e": 28841,
"s": 28672,
"text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples."
},
{
"code": null,
"e": 28847,
"s": 28841,
"text": "mysql"
},
{
"code": null,
"e": 28851,
"s": 28847,
"text": "PHP"
},
{
"code": null,
"e": 28855,
"s": 28851,
"text": "SQL"
},
{
"code": null,
"e": 28872,
"s": 28855,
"text": "Web Technologies"
},
{
"code": null,
"e": 28876,
"s": 28872,
"text": "SQL"
},
{
"code": null,
"e": 28880,
"s": 28876,
"text": "PHP"
},
{
"code": null,
"e": 28978,
"s": 28880,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29028,
"s": 28978,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 29068,
"s": 29028,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 29129,
"s": 29068,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 29179,
"s": 29129,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 29206,
"s": 29179,
"text": "Comparing two dates in PHP"
},
{
"code": null,
"e": 29248,
"s": 29206,
"text": "SQL | DDL, DQL, DML, DCL and TCL Commands"
},
{
"code": null,
"e": 29266,
"s": 29248,
"text": "SQL | WITH clause"
},
{
"code": null,
"e": 29310,
"s": 29266,
"text": "How to find Nth highest salary from a table"
},
{
"code": null,
"e": 29331,
"s": 29310,
"text": "SQL | ALTER (RENAME)"
}
] |
Count of subsequences in an array with sum less than or equal to X - GeeksforGeeks | 09 Nov, 2021
Given an integer array arr[] of size N and an integer X, the task is to count the number of subsequences in that array such that its sum is less than or equal to X. Note: 1 <= N <= 1000 and 1 <= X <= 1000, where N is the size of the array.
Examples:
Input : arr[] = {84, 87, 73}, X = 100 Output : 3 Explanation: The three subsequences with sum less than or equal to 100 are {84}, {87} and {73}.
Input : arr[] = {25, 13, 40}, X = 50 Output : 4 Explanation: The four subsequences with sum less than or equal to 50 are {25}, {13}, {40} and {25, 13}.
Naive Approach: Generate all the subsequences of the array and check if the sum is less than or equal to X. Time complexity:O(2N)
Efficient Approach: Generate the count of subsequences using Dynamic Programming. In order to solve the problem, follow the steps below:
For any index ind, if arr[ind] ≤ X then, the count of subsequences including as well as excluding the element at the current index:
countSubsequence(ind, X) = countSubsequence(ind + 1, X) (excluding) + countSubsequence(ind + 1, X – arr[ind]) (including)
Else, count subsequences excluding the current index:
countSubsequence(ind, X) = countSubsequence(ind + 1, X) (excluding)
Finally, subtract 1 from the final count returned by the function as it also counts an empty subsequence.
Below is the implementation of the above approach:
C++
Java
C#
Javascript
// C++ Program to count number// of subsequences in an array// with sum less than or equal to X#include <bits/stdc++.h>using namespace std; // Utility function to return the count// of subsequence in an array with sum// less than or equal to Xint countSubsequenceUtil( int ind, int sum, int* A, int N, vector<vector<int> >& dp){ // Base condition if (ind == N) return 1; // Return if the sub-problem // is already calculated if (dp[ind][sum] != -1) return dp[ind][sum]; // Check if the current element is // less than or equal to sum if (A[ind] <= sum) { // Count subsequences excluding // the current element dp[ind][sum] = countSubsequenceUtil( ind + 1, sum, A, N, dp) + // Count subsequences including // the current element countSubsequenceUtil( ind + 1, sum - A[ind], A, N, dp); } else { // Exclude current element dp[ind][sum] = countSubsequenceUtil( ind + 1, sum, A, N, dp); } // Return the result return dp[ind][sum];} // Function to return the count of subsequence// in an array with sum less than or equal to Xint countSubsequence(int* A, int N, int X){ // Initialize a DP array vector<vector<int> > dp( N, vector<int>(X + 1, -1)); // Return the result return countSubsequenceUtil(0, X, A, N, dp) - 1;} // Driver Codeint main(){ int arr[] = { 25, 13, 40 }, X = 50; int N = sizeof(arr) / sizeof(arr[0]); cout << countSubsequence(arr, N, X); return 0;}
// Java program to count number// of subsequences in an array// with sum less than or equal to Xclass GFG{ // Utility function to return the count// of subsequence in an array with sum// less than or equal to Xstatic int countSubsequenceUtil(int ind, int sum, int []A, int N, int [][]dp){ // Base condition if (ind == N) return 1; // Return if the sub-problem // is already calculated if (dp[ind][sum] != -1) return dp[ind][sum]; // Check if the current element is // less than or equal to sum if (A[ind] <= sum) { // Count subsequences excluding // the current element dp[ind][sum] = countSubsequenceUtil( ind + 1, sum, A, N, dp) + // Count subsequences // including the current // element countSubsequenceUtil( ind + 1, sum - A[ind], A, N, dp); } else { // Exclude current element dp[ind][sum] = countSubsequenceUtil( ind + 1, sum, A, N, dp); } // Return the result return dp[ind][sum];} // Function to return the count of subsequence// in an array with sum less than or equal to Xstatic int countSubsequence(int[] A, int N, int X){ // Initialize a DP array int [][]dp = new int[N][X + 1]; for(int i = 0; i < N; i++) { for(int j = 0; j < X + 1; j++) { dp[i][j] = -1; } } // Return the result return countSubsequenceUtil(0, X, A, N, dp) - 1;} // Driver Codepublic static void main(String[] args){ int arr[] = { 25, 13, 40 }, X = 50; int N = arr.length; System.out.print(countSubsequence(arr, N, X));}} // This code is contributed by Rajput-Ji
// C# program to count number// of subsequences in an array// with sum less than or equal to Xusing System; class GFG{ // Utility function to return the count// of subsequence in an array with sum// less than or equal to Xstatic int countSubsequenceUtil(int ind, int sum, int []A, int N, int [,]dp){ // Base condition if (ind == N) return 1; // Return if the sub-problem // is already calculated if (dp[ind, sum] != -1) return dp[ind, sum]; // Check if the current element is // less than or equal to sum if (A[ind] <= sum) { // Count subsequences excluding // the current element dp[ind, sum] = countSubsequenceUtil( ind + 1, sum, A, N, dp) + // Count subsequences // including the current // element countSubsequenceUtil( ind + 1, sum - A[ind], A, N, dp); } else { // Exclude current element dp[ind, sum] = countSubsequenceUtil( ind + 1, sum, A, N, dp); } // Return the result return dp[ind, sum];} // Function to return the count of subsequence// in an array with sum less than or equal to Xstatic int countSubsequence(int[] A, int N, int X){ // Initialize a DP array int [,]dp = new int[N, X + 1]; for(int i = 0; i < N; i++) { for(int j = 0; j < X + 1; j++) { dp[i, j] = -1; } } // Return the result return countSubsequenceUtil(0, X, A, N, dp) - 1;} // Driver Codepublic static void Main(String[] args){ int []arr = { 25, 13, 40 }; int X = 50; int N = arr.Length; Console.Write(countSubsequence(arr, N, X));}} // This code is contributed by 29AjayKumar
<script> // JavaScript program to count number// of subsequences in an array// with sum less than or equal to X // Utility function to return the count// of subsequence in an array with sum// less than or equal to Xfunction countSubsequenceUtil(ind, sum, A, N, dp){ // Base condition if (ind == N) return 1; // Return if the sub-problem // is already calculated if (dp[ind][sum] != -1) return dp[ind][sum]; // Check if the current element is // less than or equal to sum if (A[ind] <= sum) { // Count subsequences excluding // the current element dp[ind][sum] = countSubsequenceUtil( ind + 1, sum, A, N, dp) + // Count subsequences // including the current // element countSubsequenceUtil( ind + 1, sum - A[ind], A, N, dp); } else { // Exclude current element dp[ind][sum] = countSubsequenceUtil( ind + 1, sum, A, N, dp); } // Return the result return dp[ind][sum];} // Function to return the count of subsequence// in an array with sum less than or equal to Xfunction countSubsequence(A, N, X){ // Initialize a DP array let dp = new Array(N); for(var i = 0; i < dp.length; i++) { dp[i] = new Array(2); } for(let i = 0; i < N; i++) { for(let j = 0; j < X + 1; j++) { dp[i][j] = -1; } } // Return the result return countSubsequenceUtil(0, X, A, N, dp) - 1;} // Driver Codelet arr = [ 25, 13, 40 ], X = 50;let N = arr.length; document.write(countSubsequence(arr, N, X)); // This code is contributed by susmitakundugoaldanga </script>
4
Time Complexity: O(N*X)
Auxiliary Space: O(N*X)
Rajput-Ji
29AjayKumar
susmitakundugoaldanga
rohitkumarsinghcna
subsequence
Arrays
Competitive Programming
Dynamic Programming
Arrays
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Maximum and minimum of an array using minimum number of comparisons
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Competitive Programming - A Complete Guide
Modulo 10^9+7 (1000000007)
Top 10 Algorithms and Data Structures for Competitive Programming | [
{
"code": null,
"e": 25360,
"s": 25332,
"text": "\n09 Nov, 2021"
},
{
"code": null,
"e": 25600,
"s": 25360,
"text": "Given an integer array arr[] of size N and an integer X, the task is to count the number of subsequences in that array such that its sum is less than or equal to X. Note: 1 <= N <= 1000 and 1 <= X <= 1000, where N is the size of the array."
},
{
"code": null,
"e": 25612,
"s": 25600,
"text": "Examples: "
},
{
"code": null,
"e": 25757,
"s": 25612,
"text": "Input : arr[] = {84, 87, 73}, X = 100 Output : 3 Explanation: The three subsequences with sum less than or equal to 100 are {84}, {87} and {73}."
},
{
"code": null,
"e": 25911,
"s": 25757,
"text": "Input : arr[] = {25, 13, 40}, X = 50 Output : 4 Explanation: The four subsequences with sum less than or equal to 50 are {25}, {13}, {40} and {25, 13}. "
},
{
"code": null,
"e": 26041,
"s": 25911,
"text": "Naive Approach: Generate all the subsequences of the array and check if the sum is less than or equal to X. Time complexity:O(2N)"
},
{
"code": null,
"e": 26179,
"s": 26041,
"text": "Efficient Approach: Generate the count of subsequences using Dynamic Programming. In order to solve the problem, follow the steps below: "
},
{
"code": null,
"e": 26311,
"s": 26179,
"text": "For any index ind, if arr[ind] ≤ X then, the count of subsequences including as well as excluding the element at the current index:"
},
{
"code": null,
"e": 26433,
"s": 26311,
"text": "countSubsequence(ind, X) = countSubsequence(ind + 1, X) (excluding) + countSubsequence(ind + 1, X – arr[ind]) (including)"
},
{
"code": null,
"e": 26487,
"s": 26433,
"text": "Else, count subsequences excluding the current index:"
},
{
"code": null,
"e": 26555,
"s": 26487,
"text": "countSubsequence(ind, X) = countSubsequence(ind + 1, X) (excluding)"
},
{
"code": null,
"e": 26661,
"s": 26555,
"text": "Finally, subtract 1 from the final count returned by the function as it also counts an empty subsequence."
},
{
"code": null,
"e": 26714,
"s": 26661,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26718,
"s": 26714,
"text": "C++"
},
{
"code": null,
"e": 26723,
"s": 26718,
"text": "Java"
},
{
"code": null,
"e": 26726,
"s": 26723,
"text": "C#"
},
{
"code": null,
"e": 26737,
"s": 26726,
"text": "Javascript"
},
{
"code": "// C++ Program to count number// of subsequences in an array// with sum less than or equal to X#include <bits/stdc++.h>using namespace std; // Utility function to return the count// of subsequence in an array with sum// less than or equal to Xint countSubsequenceUtil( int ind, int sum, int* A, int N, vector<vector<int> >& dp){ // Base condition if (ind == N) return 1; // Return if the sub-problem // is already calculated if (dp[ind][sum] != -1) return dp[ind][sum]; // Check if the current element is // less than or equal to sum if (A[ind] <= sum) { // Count subsequences excluding // the current element dp[ind][sum] = countSubsequenceUtil( ind + 1, sum, A, N, dp) + // Count subsequences including // the current element countSubsequenceUtil( ind + 1, sum - A[ind], A, N, dp); } else { // Exclude current element dp[ind][sum] = countSubsequenceUtil( ind + 1, sum, A, N, dp); } // Return the result return dp[ind][sum];} // Function to return the count of subsequence// in an array with sum less than or equal to Xint countSubsequence(int* A, int N, int X){ // Initialize a DP array vector<vector<int> > dp( N, vector<int>(X + 1, -1)); // Return the result return countSubsequenceUtil(0, X, A, N, dp) - 1;} // Driver Codeint main(){ int arr[] = { 25, 13, 40 }, X = 50; int N = sizeof(arr) / sizeof(arr[0]); cout << countSubsequence(arr, N, X); return 0;}",
"e": 28487,
"s": 26737,
"text": null
},
{
"code": "// Java program to count number// of subsequences in an array// with sum less than or equal to Xclass GFG{ // Utility function to return the count// of subsequence in an array with sum// less than or equal to Xstatic int countSubsequenceUtil(int ind, int sum, int []A, int N, int [][]dp){ // Base condition if (ind == N) return 1; // Return if the sub-problem // is already calculated if (dp[ind][sum] != -1) return dp[ind][sum]; // Check if the current element is // less than or equal to sum if (A[ind] <= sum) { // Count subsequences excluding // the current element dp[ind][sum] = countSubsequenceUtil( ind + 1, sum, A, N, dp) + // Count subsequences // including the current // element countSubsequenceUtil( ind + 1, sum - A[ind], A, N, dp); } else { // Exclude current element dp[ind][sum] = countSubsequenceUtil( ind + 1, sum, A, N, dp); } // Return the result return dp[ind][sum];} // Function to return the count of subsequence// in an array with sum less than or equal to Xstatic int countSubsequence(int[] A, int N, int X){ // Initialize a DP array int [][]dp = new int[N][X + 1]; for(int i = 0; i < N; i++) { for(int j = 0; j < X + 1; j++) { dp[i][j] = -1; } } // Return the result return countSubsequenceUtil(0, X, A, N, dp) - 1;} // Driver Codepublic static void main(String[] args){ int arr[] = { 25, 13, 40 }, X = 50; int N = arr.length; System.out.print(countSubsequence(arr, N, X));}} // This code is contributed by Rajput-Ji",
"e": 30511,
"s": 28487,
"text": null
},
{
"code": "// C# program to count number// of subsequences in an array// with sum less than or equal to Xusing System; class GFG{ // Utility function to return the count// of subsequence in an array with sum// less than or equal to Xstatic int countSubsequenceUtil(int ind, int sum, int []A, int N, int [,]dp){ // Base condition if (ind == N) return 1; // Return if the sub-problem // is already calculated if (dp[ind, sum] != -1) return dp[ind, sum]; // Check if the current element is // less than or equal to sum if (A[ind] <= sum) { // Count subsequences excluding // the current element dp[ind, sum] = countSubsequenceUtil( ind + 1, sum, A, N, dp) + // Count subsequences // including the current // element countSubsequenceUtil( ind + 1, sum - A[ind], A, N, dp); } else { // Exclude current element dp[ind, sum] = countSubsequenceUtil( ind + 1, sum, A, N, dp); } // Return the result return dp[ind, sum];} // Function to return the count of subsequence// in an array with sum less than or equal to Xstatic int countSubsequence(int[] A, int N, int X){ // Initialize a DP array int [,]dp = new int[N, X + 1]; for(int i = 0; i < N; i++) { for(int j = 0; j < X + 1; j++) { dp[i, j] = -1; } } // Return the result return countSubsequenceUtil(0, X, A, N, dp) - 1;} // Driver Codepublic static void Main(String[] args){ int []arr = { 25, 13, 40 }; int X = 50; int N = arr.Length; Console.Write(countSubsequence(arr, N, X));}} // This code is contributed by 29AjayKumar",
"e": 32555,
"s": 30511,
"text": null
},
{
"code": "<script> // JavaScript program to count number// of subsequences in an array// with sum less than or equal to X // Utility function to return the count// of subsequence in an array with sum// less than or equal to Xfunction countSubsequenceUtil(ind, sum, A, N, dp){ // Base condition if (ind == N) return 1; // Return if the sub-problem // is already calculated if (dp[ind][sum] != -1) return dp[ind][sum]; // Check if the current element is // less than or equal to sum if (A[ind] <= sum) { // Count subsequences excluding // the current element dp[ind][sum] = countSubsequenceUtil( ind + 1, sum, A, N, dp) + // Count subsequences // including the current // element countSubsequenceUtil( ind + 1, sum - A[ind], A, N, dp); } else { // Exclude current element dp[ind][sum] = countSubsequenceUtil( ind + 1, sum, A, N, dp); } // Return the result return dp[ind][sum];} // Function to return the count of subsequence// in an array with sum less than or equal to Xfunction countSubsequence(A, N, X){ // Initialize a DP array let dp = new Array(N); for(var i = 0; i < dp.length; i++) { dp[i] = new Array(2); } for(let i = 0; i < N; i++) { for(let j = 0; j < X + 1; j++) { dp[i][j] = -1; } } // Return the result return countSubsequenceUtil(0, X, A, N, dp) - 1;} // Driver Codelet arr = [ 25, 13, 40 ], X = 50;let N = arr.length; document.write(countSubsequence(arr, N, X)); // This code is contributed by susmitakundugoaldanga </script>",
"e": 34514,
"s": 32555,
"text": null
},
{
"code": null,
"e": 34516,
"s": 34514,
"text": "4"
},
{
"code": null,
"e": 34542,
"s": 34518,
"text": "Time Complexity: O(N*X)"
},
{
"code": null,
"e": 34567,
"s": 34542,
"text": "Auxiliary Space: O(N*X) "
},
{
"code": null,
"e": 34577,
"s": 34567,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 34589,
"s": 34577,
"text": "29AjayKumar"
},
{
"code": null,
"e": 34611,
"s": 34589,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 34630,
"s": 34611,
"text": "rohitkumarsinghcna"
},
{
"code": null,
"e": 34642,
"s": 34630,
"text": "subsequence"
},
{
"code": null,
"e": 34649,
"s": 34642,
"text": "Arrays"
},
{
"code": null,
"e": 34673,
"s": 34649,
"text": "Competitive Programming"
},
{
"code": null,
"e": 34693,
"s": 34673,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 34700,
"s": 34693,
"text": "Arrays"
},
{
"code": null,
"e": 34720,
"s": 34700,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 34818,
"s": 34720,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34827,
"s": 34818,
"text": "Comments"
},
{
"code": null,
"e": 34840,
"s": 34827,
"text": "Old Comments"
},
{
"code": null,
"e": 34884,
"s": 34840,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 34907,
"s": 34884,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 34939,
"s": 34907,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 34953,
"s": 34939,
"text": "Linear Search"
},
{
"code": null,
"e": 35021,
"s": 34953,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 35064,
"s": 35021,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 35105,
"s": 35064,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 35148,
"s": 35105,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 35175,
"s": 35148,
"text": "Modulo 10^9+7 (1000000007)"
}
] |
The k-prototype as Clustering Algorithm for Mixed Data Type (Categorical and Numerical) | by Audhi Aprilliant | Towards Data Science | One of the conventional clustering methods commonly used in clustering techniques and efficiently used for large data is the K-Means algorithm. However, its method is not good and suitable for data that contains categorical variables. This problem happens when the cost function in K-Means is calculated using the Euclidian distance that is only suitable for numerical data. While K-Mode is only suitable for categorical data only, not mixed data types.
Facing these problems, Huang proposed an algorithm called K-Prototype which is created in order to handle clustering algorithms with the mixed data types (numerical and categorical variables). K-Prototype is a clustering method based on partitioning. Its algorithm is an improvement of the K-Means and K-Mode clustering algorithm to handle clustering with the mixed data types.
Read the full of K-Prototype clustering algorithm HERE.
It’s important to know well about the scale measurement from the data.
Note: K-Prototype has an advantage because it’s not too complex and is able to handle large data and is better than hierarchical based algorithms
In this part, we will demonstrate the implementation of K-Prototype using Python. Before that, it’s important to install the kmodes module first using the terminal or Anaconda prompt.
There are a few modules used for demonstration. They are pandas for data manipulation, numpy for linear algebra calculation, plotnine as data visualization, and kmodes for K-Prototype clustering algorithm.
# Import module for data manipulationimport pandas as pd# Import module for linear algebraimport numpy as np# Import module for data visualizationfrom plotnine import *import plotnine# Import module for k-protoype clusterfrom kmodes.kprototypes import KPrototypes# Ignore warningsimport warningswarnings.filterwarnings('ignore', category = FutureWarning)# Format scientific notation from Pandaspd.set_option('display.float_format', lambda x: '%.3f' % x)
The data can be downloaded here or you can easily generate this data by visiting this website. It’s totally free of charge. Enjoy!
# Load the datadf = pd.read_csv('data/10000 Sales Records.csv')# The dimension of dataprint('Dimension data: {} rows and {} columns'.format(len(df), len(df.columns)))# Print the first 5 rowsdf.head()
The data is actually the Country Sales Data. The data has 10,000 rows and 14 columns with mixed data types (numerical and categorical). It records the transaction of sales by country around the world.
To make sure the data type of each column is mapped properly, we must inspect their type manually using df.info() command. If we found there is false mapping, we should correct it to the right data type.
# Inspect the data typedf.info()
Luckily, all the columns have the right data type. Please ignore the Order ID because we will not use it and will be removed later.
There are seven categorical variables in the dataset. The Country that has the 185 unique values, Order Date with 2691 unique values, and Ship Date with 2719 unique values will be removed from cluster analysis because they have a lot of unique values. The rest of the columns will be kept. They are Region with 7 unique values, Item Type with 12 unique values, Sales Channel that has the 2 unique values and Order Priority with 4 unique values.
# Inspect the categorical variablesdf.select_dtypes('object').nunique()
The rest of the columns are numerical variables. They are Order ID, Units Sold, Unit Price, Units Cost, Total Revenue, Total Cost, and Total Profit.
# Inspect the numerical variablesdf.describe()
The last task before going to data exploration and analysis is to make sure the data doesn’t contain missing values.
# Check missing valuedf.isna().sum()
Before going to cluster analysis, we should do data exploration for descriptive analysis. It aims to find out an interesting point that can be useful for report generating and capture the phenomenon in the data.
We have the hypothesis that the number of purchases in each region has a strong linear correlation to the total profit. To conclude this, we have two options, descriptive analysis, and inference analysis. For this section, we will choose the first option. Let’s see!
# The distribution of sales each regiondf_region = pd.DataFrame(df['Region'].value_counts()).reset_index()df_region['Percentage'] = df_region['Region'] / df['Region'].value_counts().sum()df_region.rename(columns = {'index':'Region', 'Region':'Total'}, inplace = True)df_region = df_region.sort_values('Total', ascending = True).reset_index(drop = True)# The dataframedf_region = df.groupby('Region').agg({ 'Region': 'count', 'Units Sold': 'mean', 'Total Revenue': 'mean', 'Total Cost': 'mean', 'Total Profit': 'mean' }).rename(columns = {'Region': 'Total'}).reset_index().sort_values('Total', ascending = True)
From the above result, we can conclude that North America is the region with the lowest number of sales but they outperform all regions in certain columns such as Units Sold, Total Revenue, Total Cost, and Total Profit. Unlike other regions, North America makes many purchases at the same time. While Europe that has the highest number of purchases doesn’t contribute to the total profit significantly. It means that the number of purchases is not having a strong linear correlation to the total profit.
# Data vizplotnine.options.figure_size = (8, 4.8)( ggplot(data = df_region)+ geom_bar(aes(x = 'Region', y = 'Total'), fill = np.where(df_region['Region'] == 'Asia', '#981220', '#80797c'), stat = 'identity')+ geom_text(aes(x = 'Region', y = 'Total', label = 'Total'), size = 10, nudge_y = 120)+ labs(title = 'Region that has the highest purchases')+ xlab('Region')+ ylab('Frequency')+ scale_x_discrete(limits = df_region['Region'].tolist())+ theme_minimal()+ coord_flip())
For the data exploration, we will create a cross-tabulation between Region and Item Type to look out for any patterns.
# Order the index of cross tabulationorder_region = df_region['Region'].to_list()order_region.append('All')# distribution of item typedf_item = pd.crosstab(df['Region'], df['Item Type'], margins = True).reindex(order_region, axis = 0).reset_index()# Remove index namedf_item.columns.name = Nonedf_item
Data pre-processing aims to remove the unused columns which are Country, Order Date, Order ID, and Ship Date. They are irrelevant regarding the K-Prototype clustering algorithm. There are two reasons why we need to remove these columns as follows:
Country — it has a lot of unique values that add to the computational load. The information is too much to process and becomes meaningless
Order Date and Ship Date — the clustering algorithm needs the assumption that the rows in the data represent the unique observation observed in a certain time period
Order ID — it has meaningless information to the cluster analysis
# Data pre-processingdf.drop(['Country', 'Order Date', 'Order ID', 'Ship Date'], axis = 1, inplace = True)# Show the data after pre-processingprint('Dimension data: {} rows and {} columns'.format(len(df), len(df.columns)))df.head()
The K-Prototype clustering algorithm in kmodes module needs categorical variables or columns position in the data. This task aims to save those in a given variables catColumnsPos. It will be added for the next task in cluster analysis. The categorical column position is in the first four columns in the data.
# Get the position of categorical columnscatColumnsPos = [df.columns.get_loc(col) for col in list(df.select_dtypes('object').columns)]print('Categorical columns : {}'.format(list(df.select_dtypes('object').columns)))print('Categorical columns position : {}'.format(catColumnsPos))
Important! In a real case, the numerical columns will have different scales so you must normalize them using appropriate techniques, such as min-max normalization, Z-Score Normalization, etc
Next, convert the data from the data frame to the matrix. It helps the kmodes module running the K-Prototype clustering algorithm. Save the data matrix to the variable dfMatrix.
# Convert dataframe to matrixdfMatrix = df.to_numpy()dfMatrix
We are using the Elbow method to determine the optimal number of clusters for K-Prototype clusters. Instead of calculating the within the sum of squares errors (WSSE) with Euclidian distance, K-Prototype provides the cost function that combines the calculation for numerical and categorical variables. We can look into the Elbow to determine the optimal number of clusters.
# Choose optimal K using Elbow methodcost = []for cluster in range(1, 10): try: kprototype = KPrototypes(n_jobs = -1, n_clusters = cluster, init = 'Huang', random_state = 0) kprototype.fit_predict(dfMatrix, categorical = catColumnsPos) cost.append(kprototype.cost_) print('Cluster initiation: {}'.format(cluster)) except: break# Converting the results into a dataframe and plotting themdf_cost = pd.DataFrame({'Cluster':range(1, 6), 'Cost':cost})# Data vizplotnine.options.figure_size = (8, 4.8)( ggplot(data = df_cost)+ geom_line(aes(x = 'Cluster', y = 'Cost'))+ geom_point(aes(x = 'Cluster', y = 'Cost'))+ geom_label(aes(x = 'Cluster', y = 'Cost', label = 'Cluster'), size = 10, nudge_y = 1000) + labs(title = 'Optimal number of cluster with Elbow Method')+ xlab('Number of Clusters k')+ ylab('Cost')+ theme_minimal())
Important! Read more HERE
According to the scree plot of cost function above, we consider choosing the number of cluster k = 3. It will be the optimal number of clusters for K-Prototype cluster analysis. Read more about the Elbow method HERE.
# Fit the clusterkprototype = KPrototypes(n_jobs = -1, n_clusters = 3, init = 'Huang', random_state = 0)kprototype.fit_predict(dfMatrix, categorical = catColumnsPos)
The algorithm has 7 iterations to converge and it has a cost of 4,960,713,581,025,175.0 (it’s quite big right?!). We can print the centroids of cluster using kprototype.cluster_centroids_. For the numerical variables, it will be using the average while the categorical using the mode.
# Cluster centoridkprototype.cluster_centroids_# Check the iteration of the clusters createdkprototype.n_iter_# Check the cost of the clusters createdkprototype.cost_
The interpretation of clusters is needed. The interpretation is using the centroids in each cluster. To do so, we need to append the cluster labels to the raw data. Order the cluster labels will be helpful to arrange the interpretation based on cluster labels.
# Add the cluster to the dataframedf['Cluster Labels'] = kprototype.labels_df['Segment'] = df['Cluster Labels'].map({0:'First', 1:'Second', 2:'Third'})# Order the clusterdf['Segment'] = df['Segment'].astype('category')df['Segment'] = df['Segment'].cat.reorder_categories(['First','Second','Third'])
To interpret the cluster, for the numerical variables, it will be using the average while the categorical using the mode. But there are other methods that can be implemented such as using median, percentile, or value composition for categorical variables.
# Cluster interpretationdf.rename(columns = {'Cluster Labels':'Total'}, inplace = True)df.groupby('Segment').agg( { 'Total':'count', 'Region': lambda x: x.value_counts().index[0], 'Item Type': lambda x: x.value_counts().index[0], 'Sales Channel': lambda x: x.value_counts().index[0], 'Order Priority': lambda x: x.value_counts().index[0], 'Units Sold': 'mean', 'Unit Price': 'mean', 'Total Revenue': 'mean', 'Total Cost': 'mean', 'Total Profit': 'mean' }).reset_index()
The complete example is listed below.
The K-Prototype is the clustering algorithm which is the combination of K-Means and K-Mode developed by Huang. For the implementation of its algorithm, the researcher needs to filter the columns carefully especially for the categorical variables. The categorical variables must be relevant to the analysis which is not meaningless information. Besides that, the quality of the input (data) affects the clustering result (cluster initialization) and how the algorithm processes the data to get the converged result. As the researcher, for the final task, interpretation, we need to consider the metrics to use for both numerical and categorical variables.
[1] Z. Huang. Extensions to the k-Means Algorithm for ClusteringLarge Data Sets with Categorical Values (1998). Data Mining and Knowledge Discovery. 2(3): 283–304. | [
{
"code": null,
"e": 626,
"s": 172,
"text": "One of the conventional clustering methods commonly used in clustering techniques and efficiently used for large data is the K-Means algorithm. However, its method is not good and suitable for data that contains categorical variables. This problem happens when the cost function in K-Means is calculated using the Euclidian distance that is only suitable for numerical data. While K-Mode is only suitable for categorical data only, not mixed data types."
},
{
"code": null,
"e": 1004,
"s": 626,
"text": "Facing these problems, Huang proposed an algorithm called K-Prototype which is created in order to handle clustering algorithms with the mixed data types (numerical and categorical variables). K-Prototype is a clustering method based on partitioning. Its algorithm is an improvement of the K-Means and K-Mode clustering algorithm to handle clustering with the mixed data types."
},
{
"code": null,
"e": 1060,
"s": 1004,
"text": "Read the full of K-Prototype clustering algorithm HERE."
},
{
"code": null,
"e": 1131,
"s": 1060,
"text": "It’s important to know well about the scale measurement from the data."
},
{
"code": null,
"e": 1277,
"s": 1131,
"text": "Note: K-Prototype has an advantage because it’s not too complex and is able to handle large data and is better than hierarchical based algorithms"
},
{
"code": null,
"e": 1461,
"s": 1277,
"text": "In this part, we will demonstrate the implementation of K-Prototype using Python. Before that, it’s important to install the kmodes module first using the terminal or Anaconda prompt."
},
{
"code": null,
"e": 1667,
"s": 1461,
"text": "There are a few modules used for demonstration. They are pandas for data manipulation, numpy for linear algebra calculation, plotnine as data visualization, and kmodes for K-Prototype clustering algorithm."
},
{
"code": null,
"e": 2121,
"s": 1667,
"text": "# Import module for data manipulationimport pandas as pd# Import module for linear algebraimport numpy as np# Import module for data visualizationfrom plotnine import *import plotnine# Import module for k-protoype clusterfrom kmodes.kprototypes import KPrototypes# Ignore warningsimport warningswarnings.filterwarnings('ignore', category = FutureWarning)# Format scientific notation from Pandaspd.set_option('display.float_format', lambda x: '%.3f' % x)"
},
{
"code": null,
"e": 2252,
"s": 2121,
"text": "The data can be downloaded here or you can easily generate this data by visiting this website. It’s totally free of charge. Enjoy!"
},
{
"code": null,
"e": 2452,
"s": 2252,
"text": "# Load the datadf = pd.read_csv('data/10000 Sales Records.csv')# The dimension of dataprint('Dimension data: {} rows and {} columns'.format(len(df), len(df.columns)))# Print the first 5 rowsdf.head()"
},
{
"code": null,
"e": 2653,
"s": 2452,
"text": "The data is actually the Country Sales Data. The data has 10,000 rows and 14 columns with mixed data types (numerical and categorical). It records the transaction of sales by country around the world."
},
{
"code": null,
"e": 2857,
"s": 2653,
"text": "To make sure the data type of each column is mapped properly, we must inspect their type manually using df.info() command. If we found there is false mapping, we should correct it to the right data type."
},
{
"code": null,
"e": 2890,
"s": 2857,
"text": "# Inspect the data typedf.info()"
},
{
"code": null,
"e": 3022,
"s": 2890,
"text": "Luckily, all the columns have the right data type. Please ignore the Order ID because we will not use it and will be removed later."
},
{
"code": null,
"e": 3467,
"s": 3022,
"text": "There are seven categorical variables in the dataset. The Country that has the 185 unique values, Order Date with 2691 unique values, and Ship Date with 2719 unique values will be removed from cluster analysis because they have a lot of unique values. The rest of the columns will be kept. They are Region with 7 unique values, Item Type with 12 unique values, Sales Channel that has the 2 unique values and Order Priority with 4 unique values."
},
{
"code": null,
"e": 3539,
"s": 3467,
"text": "# Inspect the categorical variablesdf.select_dtypes('object').nunique()"
},
{
"code": null,
"e": 3688,
"s": 3539,
"text": "The rest of the columns are numerical variables. They are Order ID, Units Sold, Unit Price, Units Cost, Total Revenue, Total Cost, and Total Profit."
},
{
"code": null,
"e": 3735,
"s": 3688,
"text": "# Inspect the numerical variablesdf.describe()"
},
{
"code": null,
"e": 3852,
"s": 3735,
"text": "The last task before going to data exploration and analysis is to make sure the data doesn’t contain missing values."
},
{
"code": null,
"e": 3889,
"s": 3852,
"text": "# Check missing valuedf.isna().sum()"
},
{
"code": null,
"e": 4101,
"s": 3889,
"text": "Before going to cluster analysis, we should do data exploration for descriptive analysis. It aims to find out an interesting point that can be useful for report generating and capture the phenomenon in the data."
},
{
"code": null,
"e": 4368,
"s": 4101,
"text": "We have the hypothesis that the number of purchases in each region has a strong linear correlation to the total profit. To conclude this, we have two options, descriptive analysis, and inference analysis. For this section, we will choose the first option. Let’s see!"
},
{
"code": null,
"e": 4997,
"s": 4368,
"text": "# The distribution of sales each regiondf_region = pd.DataFrame(df['Region'].value_counts()).reset_index()df_region['Percentage'] = df_region['Region'] / df['Region'].value_counts().sum()df_region.rename(columns = {'index':'Region', 'Region':'Total'}, inplace = True)df_region = df_region.sort_values('Total', ascending = True).reset_index(drop = True)# The dataframedf_region = df.groupby('Region').agg({ 'Region': 'count', 'Units Sold': 'mean', 'Total Revenue': 'mean', 'Total Cost': 'mean', 'Total Profit': 'mean' }).rename(columns = {'Region': 'Total'}).reset_index().sort_values('Total', ascending = True)"
},
{
"code": null,
"e": 5501,
"s": 4997,
"text": "From the above result, we can conclude that North America is the region with the lowest number of sales but they outperform all regions in certain columns such as Units Sold, Total Revenue, Total Cost, and Total Profit. Unlike other regions, North America makes many purchases at the same time. While Europe that has the highest number of purchases doesn’t contribute to the total profit significantly. It means that the number of purchases is not having a strong linear correlation to the total profit."
},
{
"code": null,
"e": 6104,
"s": 5501,
"text": "# Data vizplotnine.options.figure_size = (8, 4.8)( ggplot(data = df_region)+ geom_bar(aes(x = 'Region', y = 'Total'), fill = np.where(df_region['Region'] == 'Asia', '#981220', '#80797c'), stat = 'identity')+ geom_text(aes(x = 'Region', y = 'Total', label = 'Total'), size = 10, nudge_y = 120)+ labs(title = 'Region that has the highest purchases')+ xlab('Region')+ ylab('Frequency')+ scale_x_discrete(limits = df_region['Region'].tolist())+ theme_minimal()+ coord_flip())"
},
{
"code": null,
"e": 6223,
"s": 6104,
"text": "For the data exploration, we will create a cross-tabulation between Region and Item Type to look out for any patterns."
},
{
"code": null,
"e": 6525,
"s": 6223,
"text": "# Order the index of cross tabulationorder_region = df_region['Region'].to_list()order_region.append('All')# distribution of item typedf_item = pd.crosstab(df['Region'], df['Item Type'], margins = True).reindex(order_region, axis = 0).reset_index()# Remove index namedf_item.columns.name = Nonedf_item"
},
{
"code": null,
"e": 6773,
"s": 6525,
"text": "Data pre-processing aims to remove the unused columns which are Country, Order Date, Order ID, and Ship Date. They are irrelevant regarding the K-Prototype clustering algorithm. There are two reasons why we need to remove these columns as follows:"
},
{
"code": null,
"e": 6912,
"s": 6773,
"text": "Country — it has a lot of unique values that add to the computational load. The information is too much to process and becomes meaningless"
},
{
"code": null,
"e": 7078,
"s": 6912,
"text": "Order Date and Ship Date — the clustering algorithm needs the assumption that the rows in the data represent the unique observation observed in a certain time period"
},
{
"code": null,
"e": 7144,
"s": 7078,
"text": "Order ID — it has meaningless information to the cluster analysis"
},
{
"code": null,
"e": 7376,
"s": 7144,
"text": "# Data pre-processingdf.drop(['Country', 'Order Date', 'Order ID', 'Ship Date'], axis = 1, inplace = True)# Show the data after pre-processingprint('Dimension data: {} rows and {} columns'.format(len(df), len(df.columns)))df.head()"
},
{
"code": null,
"e": 7686,
"s": 7376,
"text": "The K-Prototype clustering algorithm in kmodes module needs categorical variables or columns position in the data. This task aims to save those in a given variables catColumnsPos. It will be added for the next task in cluster analysis. The categorical column position is in the first four columns in the data."
},
{
"code": null,
"e": 7978,
"s": 7686,
"text": "# Get the position of categorical columnscatColumnsPos = [df.columns.get_loc(col) for col in list(df.select_dtypes('object').columns)]print('Categorical columns : {}'.format(list(df.select_dtypes('object').columns)))print('Categorical columns position : {}'.format(catColumnsPos))"
},
{
"code": null,
"e": 8169,
"s": 7978,
"text": "Important! In a real case, the numerical columns will have different scales so you must normalize them using appropriate techniques, such as min-max normalization, Z-Score Normalization, etc"
},
{
"code": null,
"e": 8347,
"s": 8169,
"text": "Next, convert the data from the data frame to the matrix. It helps the kmodes module running the K-Prototype clustering algorithm. Save the data matrix to the variable dfMatrix."
},
{
"code": null,
"e": 8409,
"s": 8347,
"text": "# Convert dataframe to matrixdfMatrix = df.to_numpy()dfMatrix"
},
{
"code": null,
"e": 8783,
"s": 8409,
"text": "We are using the Elbow method to determine the optimal number of clusters for K-Prototype clusters. Instead of calculating the within the sum of squares errors (WSSE) with Euclidian distance, K-Prototype provides the cost function that combines the calculation for numerical and categorical variables. We can look into the Elbow to determine the optimal number of clusters."
},
{
"code": null,
"e": 9768,
"s": 8783,
"text": "# Choose optimal K using Elbow methodcost = []for cluster in range(1, 10): try: kprototype = KPrototypes(n_jobs = -1, n_clusters = cluster, init = 'Huang', random_state = 0) kprototype.fit_predict(dfMatrix, categorical = catColumnsPos) cost.append(kprototype.cost_) print('Cluster initiation: {}'.format(cluster)) except: break# Converting the results into a dataframe and plotting themdf_cost = pd.DataFrame({'Cluster':range(1, 6), 'Cost':cost})# Data vizplotnine.options.figure_size = (8, 4.8)( ggplot(data = df_cost)+ geom_line(aes(x = 'Cluster', y = 'Cost'))+ geom_point(aes(x = 'Cluster', y = 'Cost'))+ geom_label(aes(x = 'Cluster', y = 'Cost', label = 'Cluster'), size = 10, nudge_y = 1000) + labs(title = 'Optimal number of cluster with Elbow Method')+ xlab('Number of Clusters k')+ ylab('Cost')+ theme_minimal())"
},
{
"code": null,
"e": 9794,
"s": 9768,
"text": "Important! Read more HERE"
},
{
"code": null,
"e": 10011,
"s": 9794,
"text": "According to the scree plot of cost function above, we consider choosing the number of cluster k = 3. It will be the optimal number of clusters for K-Prototype cluster analysis. Read more about the Elbow method HERE."
},
{
"code": null,
"e": 10177,
"s": 10011,
"text": "# Fit the clusterkprototype = KPrototypes(n_jobs = -1, n_clusters = 3, init = 'Huang', random_state = 0)kprototype.fit_predict(dfMatrix, categorical = catColumnsPos)"
},
{
"code": null,
"e": 10462,
"s": 10177,
"text": "The algorithm has 7 iterations to converge and it has a cost of 4,960,713,581,025,175.0 (it’s quite big right?!). We can print the centroids of cluster using kprototype.cluster_centroids_. For the numerical variables, it will be using the average while the categorical using the mode."
},
{
"code": null,
"e": 10629,
"s": 10462,
"text": "# Cluster centoridkprototype.cluster_centroids_# Check the iteration of the clusters createdkprototype.n_iter_# Check the cost of the clusters createdkprototype.cost_"
},
{
"code": null,
"e": 10890,
"s": 10629,
"text": "The interpretation of clusters is needed. The interpretation is using the centroids in each cluster. To do so, we need to append the cluster labels to the raw data. Order the cluster labels will be helpful to arrange the interpretation based on cluster labels."
},
{
"code": null,
"e": 11189,
"s": 10890,
"text": "# Add the cluster to the dataframedf['Cluster Labels'] = kprototype.labels_df['Segment'] = df['Cluster Labels'].map({0:'First', 1:'Second', 2:'Third'})# Order the clusterdf['Segment'] = df['Segment'].astype('category')df['Segment'] = df['Segment'].cat.reorder_categories(['First','Second','Third'])"
},
{
"code": null,
"e": 11445,
"s": 11189,
"text": "To interpret the cluster, for the numerical variables, it will be using the average while the categorical using the mode. But there are other methods that can be implemented such as using median, percentile, or value composition for categorical variables."
},
{
"code": null,
"e": 11991,
"s": 11445,
"text": "# Cluster interpretationdf.rename(columns = {'Cluster Labels':'Total'}, inplace = True)df.groupby('Segment').agg( { 'Total':'count', 'Region': lambda x: x.value_counts().index[0], 'Item Type': lambda x: x.value_counts().index[0], 'Sales Channel': lambda x: x.value_counts().index[0], 'Order Priority': lambda x: x.value_counts().index[0], 'Units Sold': 'mean', 'Unit Price': 'mean', 'Total Revenue': 'mean', 'Total Cost': 'mean', 'Total Profit': 'mean' }).reset_index()"
},
{
"code": null,
"e": 12029,
"s": 11991,
"text": "The complete example is listed below."
},
{
"code": null,
"e": 12684,
"s": 12029,
"text": "The K-Prototype is the clustering algorithm which is the combination of K-Means and K-Mode developed by Huang. For the implementation of its algorithm, the researcher needs to filter the columns carefully especially for the categorical variables. The categorical variables must be relevant to the analysis which is not meaningless information. Besides that, the quality of the input (data) affects the clustering result (cluster initialization) and how the algorithm processes the data to get the converged result. As the researcher, for the final task, interpretation, we need to consider the metrics to use for both numerical and categorical variables."
}
] |
How to Properly Use the GPU within a Docker Container | by Jacob Solawetz | Towards Data Science | Configuring the GPU on your machine can be immensely difficult. The configuration steps change based on your machine’s operating system and the kind of NVIDIA GPU that your machine has. To add another layer of difficulty, when Docker starts a container — it starts from almost scratch. Certain things like the CPU drivers are pre-configured for you, but the GPU is not configured when you run a docker container. Luckily, you have found the solution explained here. It is called the NVIDIA Container Toolkit!
When you attempt to run your container that needs the GPU in Docker, you might receive any of the following errors.
Error: Docker does not find Nvidia drivers
docker: Error response from daemon: Container command 'nvidia-smi' not found or does not exist..
Error: tensorflow cannot access GPU in Docker
I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:150] kernel reported version is: 352.93I tensorflow/core/common_runtime/gpu/gpu_init.cc:81] No GPU devices available on machine.
Error: pytorch cannot access GPU in Docker
RuntimeError: cuda runtime error (100) : no CUDA-capable device is detected at /pytorch/aten/src/THC/THCGeneral.cpp:50
Error: keras cannot access GPU in Docker
The TensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations.
You may receive many other errors indicating that your Docker container cannot access the machine’s GPU. In any case, if you have any errors that look like the above, you have found the right place here.
You must first install NVIDIA GPU drivers on your base machine before you can utilize the GPU in Docker. As previously mentioned, this can be difficult given the plethora of distribution of operating systems, NVIDIA GPUs, and NVIDIA GPU drivers. The exact commands you will run will vary based on these parameters. Here are some resources that you might find useful to configure the GPU on your base machine.
NVIDIA’s official toolkit documentation
Installing NVIDIA drivers on Ubuntu guide
Installing NVIDIA drivers from the command line
Once you have worked through those steps, you will know you are successful by running the nvidia-smi command and viewing an output like the following.
Now that we can assure we have successfully assure that the NVIDIA GPU drivers are installed on the base machine, we can move one layer deeper to the Docker container.
In order to get Docker to recognize the GPU, we need to make it aware of the GPU drivers. We do this in the image creation process. Docker image creation is a series of commands that configure the environment that our Docker container will be running in.
The Brute Force Approach — The brute force approach is to include the same commands that you used to configure the GPU on your base machine. When docker builds the image, these commands will run and install the GPU drivers on your image and all should be well. The brute force approach will look something like this in your Dockerfile (Code credit to stack overflow):
FROM ubuntu:14.04MAINTAINER Regan <http://stackoverflow.com/questions/25185405/using-gpu-from-a-docker-container>RUN apt-get update && apt-get install -y build-essentialRUN apt-get --purge remove -y nvidia*ADD ./Downloads/nvidia_installers /tmp/nvidia > Get the install files you used to install CUDA and the NVIDIA drivers on your hostRUN /tmp/nvidia/NVIDIA-Linux-x86_64-331.62.run -s -N --no-kernel-module > Install the driver.RUN rm -rf /tmp/selfgz7 > For some reason the driver installer left temp files when used during a docker build (i don't have any explanation why) and the CUDA installer will fail if there still there so we delete them.RUN /tmp/nvidia/cuda-linux64-rel-6.0.37-18176142.run -noprompt > CUDA driver installer.RUN /tmp/nvidia/cuda-samples-linux-6.0.37-18176142.run -noprompt -cudaprefix=/usr/local/cuda-6.0 > CUDA samples comment if you don't want them.RUN export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda/lib64 > Add CUDA library into your PATHRUN touch /etc/ld.so.conf.d/cuda.conf > Update the ld.so.conf.d directoryRUN rm -rf /temp/* > Delete installer files.
The Downsides of the Brute Force Approach — First of all, every time you rebuild the docker image you will have to reinstall the image, slowing down development. Second, if you decide to lift the docker image off of the current machine and onto a new one that has a different GPU, operating system, or you would like new drivers — you will have to re-code this step every time for each machine. This kind of defeats the purpose of build a Docker image. Third, you might not remember the commands to install the drivers on your local machine, and there you are back at configuring the GPU again inside of Docker.
The Best Approach — The best approach is to use the NVIDIA Container Toolkit. The NVIDIA Container Toolkit is a docker image that provides support to automatically recognize GPU drivers on your base machine and pass those same drivers to your Docker container when it runs. So if you are able to run nvidia-smi, on your base machine you will also be able to run it in your Docker container (and all of your programs will be able to reference the GPU). In order to use the NVIDIA Container Toolkit, you simply pull the NVIDIA Container Toolkit image at the top of your Dockerfile like so — nano Dockerfile:
FROM nvidia/cuda:10.2-baseCMD nvidia-smi
This is all the code you need to expose GPU drivers to Docker. In that Dockerfile we have imported the NVIDIA Container Toolkit image for 10.2 drivers and then we have specified a command to run when we run the container to check for the drivers. Now we build the image like so with docker build . -t nvidia-test:
Now we run the container from the image by using the command docker run — gpus all nvidia-test. Keep in mind, we need the — gpus all or else the GPU will not be exposed to the running container.
From this base state, you can develop your app accordingly. In my case, I use the NVIDIA Container Toolkit to power experimental deep learning frameworks. The layout of a fully built Dockerfile might look something like the following (where /app/ contains all of the python files):
FROM nvidia/cuda:10.2-baseCMD nvidia-smi#set up environmentRUN apt-get update && apt-get install --no-install-recommends --no-install-suggests -y curlRUN apt-get install unzipRUN apt-get -y install python3RUN apt-get -y install python3-pipCOPY app/requirements_verbose.txt /app/requirements_verbose.txtRUN pip3 install -r /app/requirements_verbose.txt#copies the applicaiton from local path to container pathCOPY app/ /app/WORKDIR /appENV NUM_EPOCHS=10ENV MODEL_TYPE='EfficientDet'ENV DATASET_LINK='HIDDEN'ENV TRAIN_TIME_SEC=100CMD ["python3", "train_and_eval.py"]
The above Docker container trains and evaluates a deep learning model based on specifications using the base machines GPU. Pretty cool!
Let’s say you have been relying on a different base image in your Dockerfile. Then, you can install NVIDIA container runtime.
apt-get install nvidia-container-runtimedocker run -it --rm --gpus all ubuntu nvidia-smi
Now you can run other base images with nvidia container runtime (here we run ubuntu base).
Now that you have you written your image to pass through the base machine’s GPU drivers, you will be able to lift the image off the current machine and deploy it to containers running on any instance that you desire.
The nvidia/cuda:10.2-base will only get you nvidia-smi. If you need cuDNN or nvcc --version you can pull from other NVIDIA Docker base images, namely: nvidia/cuda:10.2-devel-ubuntu18.0. (gets you nvcc cuda toolkit) andnvidia/cuda:10.2-cudnn7-devel-ubuntu18.04. (gets you cuDNN).
Congratulations! Now you know how to expose GPU Drivers to your running Docker container using the NVIDIA Container Toolkit.
Want to use your new Docker capabilities to do something awesome? You might enjoy our other posts on training a state of the art object detection model, training a state of the art image classification model, or simply by looking into some free computer vision data! | [
{
"code": null,
"e": 681,
"s": 172,
"text": "Configuring the GPU on your machine can be immensely difficult. The configuration steps change based on your machine’s operating system and the kind of NVIDIA GPU that your machine has. To add another layer of difficulty, when Docker starts a container — it starts from almost scratch. Certain things like the CPU drivers are pre-configured for you, but the GPU is not configured when you run a docker container. Luckily, you have found the solution explained here. It is called the NVIDIA Container Toolkit!"
},
{
"code": null,
"e": 797,
"s": 681,
"text": "When you attempt to run your container that needs the GPU in Docker, you might receive any of the following errors."
},
{
"code": null,
"e": 840,
"s": 797,
"text": "Error: Docker does not find Nvidia drivers"
},
{
"code": null,
"e": 937,
"s": 840,
"text": "docker: Error response from daemon: Container command 'nvidia-smi' not found or does not exist.."
},
{
"code": null,
"e": 983,
"s": 937,
"text": "Error: tensorflow cannot access GPU in Docker"
},
{
"code": null,
"e": 1166,
"s": 983,
"text": "I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:150] kernel reported version is: 352.93I tensorflow/core/common_runtime/gpu/gpu_init.cc:81] No GPU devices available on machine."
},
{
"code": null,
"e": 1209,
"s": 1166,
"text": "Error: pytorch cannot access GPU in Docker"
},
{
"code": null,
"e": 1328,
"s": 1209,
"text": "RuntimeError: cuda runtime error (100) : no CUDA-capable device is detected at /pytorch/aten/src/THC/THCGeneral.cpp:50"
},
{
"code": null,
"e": 1369,
"s": 1328,
"text": "Error: keras cannot access GPU in Docker"
},
{
"code": null,
"e": 1510,
"s": 1369,
"text": "The TensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations."
},
{
"code": null,
"e": 1714,
"s": 1510,
"text": "You may receive many other errors indicating that your Docker container cannot access the machine’s GPU. In any case, if you have any errors that look like the above, you have found the right place here."
},
{
"code": null,
"e": 2123,
"s": 1714,
"text": "You must first install NVIDIA GPU drivers on your base machine before you can utilize the GPU in Docker. As previously mentioned, this can be difficult given the plethora of distribution of operating systems, NVIDIA GPUs, and NVIDIA GPU drivers. The exact commands you will run will vary based on these parameters. Here are some resources that you might find useful to configure the GPU on your base machine."
},
{
"code": null,
"e": 2163,
"s": 2123,
"text": "NVIDIA’s official toolkit documentation"
},
{
"code": null,
"e": 2205,
"s": 2163,
"text": "Installing NVIDIA drivers on Ubuntu guide"
},
{
"code": null,
"e": 2253,
"s": 2205,
"text": "Installing NVIDIA drivers from the command line"
},
{
"code": null,
"e": 2404,
"s": 2253,
"text": "Once you have worked through those steps, you will know you are successful by running the nvidia-smi command and viewing an output like the following."
},
{
"code": null,
"e": 2572,
"s": 2404,
"text": "Now that we can assure we have successfully assure that the NVIDIA GPU drivers are installed on the base machine, we can move one layer deeper to the Docker container."
},
{
"code": null,
"e": 2827,
"s": 2572,
"text": "In order to get Docker to recognize the GPU, we need to make it aware of the GPU drivers. We do this in the image creation process. Docker image creation is a series of commands that configure the environment that our Docker container will be running in."
},
{
"code": null,
"e": 3195,
"s": 2827,
"text": "The Brute Force Approach — The brute force approach is to include the same commands that you used to configure the GPU on your base machine. When docker builds the image, these commands will run and install the GPU drivers on your image and all should be well. The brute force approach will look something like this in your Dockerfile (Code credit to stack overflow):"
},
{
"code": null,
"e": 4427,
"s": 3195,
"text": "FROM ubuntu:14.04MAINTAINER Regan <http://stackoverflow.com/questions/25185405/using-gpu-from-a-docker-container>RUN apt-get update && apt-get install -y build-essentialRUN apt-get --purge remove -y nvidia*ADD ./Downloads/nvidia_installers /tmp/nvidia > Get the install files you used to install CUDA and the NVIDIA drivers on your hostRUN /tmp/nvidia/NVIDIA-Linux-x86_64-331.62.run -s -N --no-kernel-module > Install the driver.RUN rm -rf /tmp/selfgz7 > For some reason the driver installer left temp files when used during a docker build (i don't have any explanation why) and the CUDA installer will fail if there still there so we delete them.RUN /tmp/nvidia/cuda-linux64-rel-6.0.37-18176142.run -noprompt > CUDA driver installer.RUN /tmp/nvidia/cuda-samples-linux-6.0.37-18176142.run -noprompt -cudaprefix=/usr/local/cuda-6.0 > CUDA samples comment if you don't want them.RUN export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda/lib64 > Add CUDA library into your PATHRUN touch /etc/ld.so.conf.d/cuda.conf > Update the ld.so.conf.d directoryRUN rm -rf /temp/* > Delete installer files."
},
{
"code": null,
"e": 5039,
"s": 4427,
"text": "The Downsides of the Brute Force Approach — First of all, every time you rebuild the docker image you will have to reinstall the image, slowing down development. Second, if you decide to lift the docker image off of the current machine and onto a new one that has a different GPU, operating system, or you would like new drivers — you will have to re-code this step every time for each machine. This kind of defeats the purpose of build a Docker image. Third, you might not remember the commands to install the drivers on your local machine, and there you are back at configuring the GPU again inside of Docker."
},
{
"code": null,
"e": 5645,
"s": 5039,
"text": "The Best Approach — The best approach is to use the NVIDIA Container Toolkit. The NVIDIA Container Toolkit is a docker image that provides support to automatically recognize GPU drivers on your base machine and pass those same drivers to your Docker container when it runs. So if you are able to run nvidia-smi, on your base machine you will also be able to run it in your Docker container (and all of your programs will be able to reference the GPU). In order to use the NVIDIA Container Toolkit, you simply pull the NVIDIA Container Toolkit image at the top of your Dockerfile like so — nano Dockerfile:"
},
{
"code": null,
"e": 5686,
"s": 5645,
"text": "FROM nvidia/cuda:10.2-baseCMD nvidia-smi"
},
{
"code": null,
"e": 6000,
"s": 5686,
"text": "This is all the code you need to expose GPU drivers to Docker. In that Dockerfile we have imported the NVIDIA Container Toolkit image for 10.2 drivers and then we have specified a command to run when we run the container to check for the drivers. Now we build the image like so with docker build . -t nvidia-test:"
},
{
"code": null,
"e": 6195,
"s": 6000,
"text": "Now we run the container from the image by using the command docker run — gpus all nvidia-test. Keep in mind, we need the — gpus all or else the GPU will not be exposed to the running container."
},
{
"code": null,
"e": 6477,
"s": 6195,
"text": "From this base state, you can develop your app accordingly. In my case, I use the NVIDIA Container Toolkit to power experimental deep learning frameworks. The layout of a fully built Dockerfile might look something like the following (where /app/ contains all of the python files):"
},
{
"code": null,
"e": 7042,
"s": 6477,
"text": "FROM nvidia/cuda:10.2-baseCMD nvidia-smi#set up environmentRUN apt-get update && apt-get install --no-install-recommends --no-install-suggests -y curlRUN apt-get install unzipRUN apt-get -y install python3RUN apt-get -y install python3-pipCOPY app/requirements_verbose.txt /app/requirements_verbose.txtRUN pip3 install -r /app/requirements_verbose.txt#copies the applicaiton from local path to container pathCOPY app/ /app/WORKDIR /appENV NUM_EPOCHS=10ENV MODEL_TYPE='EfficientDet'ENV DATASET_LINK='HIDDEN'ENV TRAIN_TIME_SEC=100CMD [\"python3\", \"train_and_eval.py\"]"
},
{
"code": null,
"e": 7178,
"s": 7042,
"text": "The above Docker container trains and evaluates a deep learning model based on specifications using the base machines GPU. Pretty cool!"
},
{
"code": null,
"e": 7304,
"s": 7178,
"text": "Let’s say you have been relying on a different base image in your Dockerfile. Then, you can install NVIDIA container runtime."
},
{
"code": null,
"e": 7393,
"s": 7304,
"text": "apt-get install nvidia-container-runtimedocker run -it --rm --gpus all ubuntu nvidia-smi"
},
{
"code": null,
"e": 7484,
"s": 7393,
"text": "Now you can run other base images with nvidia container runtime (here we run ubuntu base)."
},
{
"code": null,
"e": 7701,
"s": 7484,
"text": "Now that you have you written your image to pass through the base machine’s GPU drivers, you will be able to lift the image off the current machine and deploy it to containers running on any instance that you desire."
},
{
"code": null,
"e": 7980,
"s": 7701,
"text": "The nvidia/cuda:10.2-base will only get you nvidia-smi. If you need cuDNN or nvcc --version you can pull from other NVIDIA Docker base images, namely: nvidia/cuda:10.2-devel-ubuntu18.0. (gets you nvcc cuda toolkit) andnvidia/cuda:10.2-cudnn7-devel-ubuntu18.04. (gets you cuDNN)."
},
{
"code": null,
"e": 8105,
"s": 7980,
"text": "Congratulations! Now you know how to expose GPU Drivers to your running Docker container using the NVIDIA Container Toolkit."
}
] |
How to replace rows in a MySQL table with conditions? | To set conditions and replace rows, use MySQL CASE statement. Let us first create a table −
mysql> create table DemoTable1481
-> (
-> PlayerScore int
-> );
Query OK, 0 rows affected (0.42 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1481 values(454);
Query OK, 1 row affected (0.41 sec)
mysql> insert into DemoTable1481 values(765);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1481 values(890);
Query OK, 1 row affected (0.09 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1481;
This will produce the following output −
+-------------+
| PlayerScore |
+-------------+
| 454 |
| 765 |
| 890 |
+-------------+
3 rows in set (0.00 sec)
Following is the query to replace rows in a MySQL table −
mysql> update DemoTable1481
-> set PlayerScore= case when PlayerScore=454 then 1256
-> when PlayerScore=765 then 1865
-> when PlayerScore=890 then 3990
-> end
-> ;
Query OK, 3 rows affected (0.17 sec)
Rows matched: 3 Changed: 3 Warnings: 0
Let us check the table records once again −
mysql> select * from DemoTable1481;
This will produce the following output −
+-------------+
| PlayerScore |
+-------------+
| 1256 |
| 1865 |
| 3990 |
+-------------+
3 rows in set (0.00 sec) | [
{
"code": null,
"e": 1154,
"s": 1062,
"text": "To set conditions and replace rows, use MySQL CASE statement. Let us first create a table −"
},
{
"code": null,
"e": 1264,
"s": 1154,
"text": "mysql> create table DemoTable1481\n -> (\n -> PlayerScore int\n -> );\nQuery OK, 0 rows affected (0.42 sec)"
},
{
"code": null,
"e": 1320,
"s": 1264,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1566,
"s": 1320,
"text": "mysql> insert into DemoTable1481 values(454);\nQuery OK, 1 row affected (0.41 sec)\nmysql> insert into DemoTable1481 values(765);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable1481 values(890);\nQuery OK, 1 row affected (0.09 sec)"
},
{
"code": null,
"e": 1626,
"s": 1566,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1662,
"s": 1626,
"text": "mysql> select * from DemoTable1481;"
},
{
"code": null,
"e": 1703,
"s": 1662,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1840,
"s": 1703,
"text": "+-------------+\n| PlayerScore |\n+-------------+\n| 454 |\n| 765 |\n| 890 |\n+-------------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1898,
"s": 1840,
"text": "Following is the query to replace rows in a MySQL table −"
},
{
"code": null,
"e": 2154,
"s": 1898,
"text": "mysql> update DemoTable1481\n -> set PlayerScore= case when PlayerScore=454 then 1256\n -> when PlayerScore=765 then 1865\n -> when PlayerScore=890 then 3990\n -> end\n -> ;\nQuery OK, 3 rows affected (0.17 sec)\nRows matched: 3 Changed: 3 Warnings: 0"
},
{
"code": null,
"e": 2198,
"s": 2154,
"text": "Let us check the table records once again −"
},
{
"code": null,
"e": 2234,
"s": 2198,
"text": "mysql> select * from DemoTable1481;"
},
{
"code": null,
"e": 2275,
"s": 2234,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2412,
"s": 2275,
"text": "+-------------+\n| PlayerScore |\n+-------------+\n| 1256 |\n| 1865 |\n| 3990 |\n+-------------+\n3 rows in set (0.00 sec)"
}
] |
How to get synonyms/antonyms from NLTK WordNet in Python | The WordNet is a part of Python's Natural Language Toolkit. It is a large word database of English Nouns, Adjectives, Adverbs and Verbs. These are grouped into some set of cognitive synonyms, which are called synsets.
To use the Wordnet, at first we have to install the NLTK module, then download the WordNet package.
$ sudo pip3 install nltk
$ python3
>>> import nltk
>>>nltk.download('wordnet')
In the wordnet, there are some groups of words, whose meaning are same.
In the first example, we will see how wordnet returns meaning and other details of a word. Sometimes, if some examples are available, it may also provide that.
from nltk.corpus import wordnet #Import wordnet from the NLTK
synset = wordnet.synsets("Travel")
print('Word and Type : ' + synset[0].name())
print('Synonym of Travel is: ' + synset[0].lemmas()[0].name())
print('The meaning of the word : ' + synset[0].definition())
print('Example of Travel : ' + str(synset[0].examples()))
$ python3 322a.word_info.py
Word and Type : travel.n.01
Synonym of Travel is: travel
The meaning of the word : the act of going from one place to another
Example of Travel : ['he enjoyed selling but he hated the travel']
$
In the previous example, we are getting detail information about some words. Here we will see how wordnet can send the synonyms and antonyms of a given word.
import nltk
from nltk.corpus import wordnet #Import wordnet from the NLTK
syn = list()
ant = list()
for synset in wordnet.synsets("Worse"):
for lemma in synset.lemmas():
syn.append(lemma.name()) #add the synonyms
if lemma.antonyms(): #When antonyms are available, add them into the list
ant.append(lemma.antonyms()[0].name())
print('Synonyms: ' + str(syn))
print('Antonyms: ' + str(ant))
$ python3 322b.syn_ant.py
Synonyms: ['worse', 'worse', 'worse', 'worsened', 'bad', 'bad', 'big', 'bad', 'tough', 'bad', 'spoiled', 'spoilt', 'regretful', 'sorry', 'bad', 'bad', 'uncollectible', 'bad', 'bad', 'bad', 'risky', 'high-risk', 'speculative', 'bad', 'unfit', 'unsound', 'bad', 'bad', 'bad', 'forged', 'bad', 'defective', 'worse']
Antonyms: ['better', 'better', 'good', 'unregretful']
$
The NLTK wordnet has another great feature, by using it we can check whether two words are nearly equal or not. It will return the similarity ratio from a pair of words.
import nltk
from nltk.corpus import wordnet #Import wordnet from the NLTK
first_word = wordnet.synset("Travel.v.01")
second_word = wordnet.synset("Walk.v.01")
print('Similarity: ' + str(first_word.wup_similarity(second_word)))
first_word = wordnet.synset("Good.n.01")
second_word = wordnet.synset("zebra.n.01")
print('Similarity: ' + str(first_word.wup_similarity(second_word)))
$ python3 322c.compare.py
Similarity: 0.6666666666666666
Similarity: 0.09090909090909091
$ | [
{
"code": null,
"e": 1280,
"s": 1062,
"text": "The WordNet is a part of Python's Natural Language Toolkit. It is a large word database of English Nouns, Adjectives, Adverbs and Verbs. These are grouped into some set of cognitive synonyms, which are called synsets."
},
{
"code": null,
"e": 1380,
"s": 1280,
"text": "To use the Wordnet, at first we have to install the NLTK module, then download the WordNet package."
},
{
"code": null,
"e": 1460,
"s": 1380,
"text": "$ sudo pip3 install nltk\n$ python3\n>>> import nltk\n>>>nltk.download('wordnet')\n"
},
{
"code": null,
"e": 1532,
"s": 1460,
"text": "In the wordnet, there are some groups of words, whose meaning are same."
},
{
"code": null,
"e": 1692,
"s": 1532,
"text": "In the first example, we will see how wordnet returns meaning and other details of a word. Sometimes, if some examples are available, it may also provide that."
},
{
"code": null,
"e": 2018,
"s": 1692,
"text": "from nltk.corpus import wordnet #Import wordnet from the NLTK\nsynset = wordnet.synsets(\"Travel\")\nprint('Word and Type : ' + synset[0].name())\nprint('Synonym of Travel is: ' + synset[0].lemmas()[0].name())\nprint('The meaning of the word : ' + synset[0].definition())\nprint('Example of Travel : ' + str(synset[0].examples()))"
},
{
"code": null,
"e": 2242,
"s": 2018,
"text": "$ python3 322a.word_info.py\nWord and Type : travel.n.01\nSynonym of Travel is: travel\nThe meaning of the word : the act of going from one place to another\nExample of Travel : ['he enjoyed selling but he hated the travel']\n$\n"
},
{
"code": null,
"e": 2400,
"s": 2242,
"text": "In the previous example, we are getting detail information about some words. Here we will see how wordnet can send the synonyms and antonyms of a given word."
},
{
"code": null,
"e": 2817,
"s": 2400,
"text": "import nltk\nfrom nltk.corpus import wordnet #Import wordnet from the NLTK\nsyn = list()\nant = list()\nfor synset in wordnet.synsets(\"Worse\"):\n for lemma in synset.lemmas():\n syn.append(lemma.name()) #add the synonyms\n if lemma.antonyms(): #When antonyms are available, add them into the list\n ant.append(lemma.antonyms()[0].name())\nprint('Synonyms: ' + str(syn))\nprint('Antonyms: ' + str(ant))"
},
{
"code": null,
"e": 3213,
"s": 2817,
"text": "$ python3 322b.syn_ant.py\nSynonyms: ['worse', 'worse', 'worse', 'worsened', 'bad', 'bad', 'big', 'bad', 'tough', 'bad', 'spoiled', 'spoilt', 'regretful', 'sorry', 'bad', 'bad', 'uncollectible', 'bad', 'bad', 'bad', 'risky', 'high-risk', 'speculative', 'bad', 'unfit', 'unsound', 'bad', 'bad', 'bad', 'forged', 'bad', 'defective', 'worse']\nAntonyms: ['better', 'better', 'good', 'unregretful']\n$\n"
},
{
"code": null,
"e": 3383,
"s": 3213,
"text": "The NLTK wordnet has another great feature, by using it we can check whether two words are nearly equal or not. It will return the similarity ratio from a pair of words."
},
{
"code": null,
"e": 3766,
"s": 3383,
"text": "import nltk\nfrom nltk.corpus import wordnet #Import wordnet from the NLTK\nfirst_word = wordnet.synset(\"Travel.v.01\")\nsecond_word = wordnet.synset(\"Walk.v.01\")\nprint('Similarity: ' + str(first_word.wup_similarity(second_word)))\nfirst_word = wordnet.synset(\"Good.n.01\")\nsecond_word = wordnet.synset(\"zebra.n.01\")\nprint('Similarity: ' + str(first_word.wup_similarity(second_word)))"
},
{
"code": null,
"e": 3858,
"s": 3766,
"text": "$ python3 322c.compare.py\nSimilarity: 0.6666666666666666\nSimilarity: 0.09090909090909091\n$\n"
}
] |
How to make longer subplot tick marks in Matplotlib? | To make longer subplot tick marks in matplotlib, we can use tick_params() method for minor and major ticks length and width.
Add a subplot to the current figure using subplot() method.
Add a subplot to the current figure using subplot() method.
Plot a range(2) value
Plot a range(2) value
s for x and y data points.
s for x and y data points.
Turn the minor ticks of the colorbar ON without extruding into the "extend regions".
Turn the minor ticks of the colorbar ON without extruding into the "extend regions".
Use tick_params for changing the appearance of ticks and tick labels.
Use tick_params for changing the appearance of ticks and tick labels.
To display the figure, use show() method.
To display the figure, use show() method.
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
ax1 = plt.subplot()
ax1.plot(range(2), range(2), linewidth=2)
ax1.minorticks_on()
ax1.tick_params('both', length=20, width=2, which='major')
ax1.tick_params('both', length=10, width=1, which='minor')
plt.show() | [
{
"code": null,
"e": 1187,
"s": 1062,
"text": "To make longer subplot tick marks in matplotlib, we can use tick_params() method for minor and major ticks length and width."
},
{
"code": null,
"e": 1247,
"s": 1187,
"text": "Add a subplot to the current figure using subplot() method."
},
{
"code": null,
"e": 1307,
"s": 1247,
"text": "Add a subplot to the current figure using subplot() method."
},
{
"code": null,
"e": 1329,
"s": 1307,
"text": "Plot a range(2) value"
},
{
"code": null,
"e": 1351,
"s": 1329,
"text": "Plot a range(2) value"
},
{
"code": null,
"e": 1378,
"s": 1351,
"text": "s for x and y data points."
},
{
"code": null,
"e": 1405,
"s": 1378,
"text": "s for x and y data points."
},
{
"code": null,
"e": 1490,
"s": 1405,
"text": "Turn the minor ticks of the colorbar ON without extruding into the \"extend regions\"."
},
{
"code": null,
"e": 1575,
"s": 1490,
"text": "Turn the minor ticks of the colorbar ON without extruding into the \"extend regions\"."
},
{
"code": null,
"e": 1645,
"s": 1575,
"text": "Use tick_params for changing the appearance of ticks and tick labels."
},
{
"code": null,
"e": 1715,
"s": 1645,
"text": "Use tick_params for changing the appearance of ticks and tick labels."
},
{
"code": null,
"e": 1757,
"s": 1715,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1799,
"s": 1757,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2134,
"s": 1799,
"text": "from matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nax1 = plt.subplot()\nax1.plot(range(2), range(2), linewidth=2)\nax1.minorticks_on()\nax1.tick_params('both', length=20, width=2, which='major')\nax1.tick_params('both', length=10, width=1, which='minor')\nplt.show()"
}
] |
PHP mktime() Function | The mktime function accepts hours, minutes, seconds, month, day, year as parameters (representing a date) and returns the Unix timestamp for the given date. if you haven't passed any parameters to this method, it returns the current timestamp.
mktime($hour, $minute, $second, $month, $day,$ year, $is_dst)
hours(Mandatory)
This is an integer value representing the number of hours of the day, from its start.
minute(Mandatory)
This is an integer value representing the number of minutes of an hours, from its start.
seconds(Optional)
This is an integer value representing the number seconds of a minute, from its start.
month(Mandatory)
This is an integer value representing the month of an year, which should be between 1 and 12.
day(Mandatory)
This is an integer value representing the day of a date, it should be below the allowed number of days in the given month.
year(Mandatory)
This is an integer value representing the year of a date, it should be between 1 and 32767.
is_dst(Mandatory)
This parameter can be set to 1 if the time is during daylight savings time (DST), 0 if it is not, or -1 (the default)
PHP mktime() function returns an Unix timestamp representing the given date. In case of a failure this function returns the boolean value false.
This function was first introduced in PHP Version 4.0 and, works with all the later versions.
Following example demonstrates the usage of the mktime() function −
<?php
$timestamp = mktime();
print($timestamp);
?>
This will produce following result −
1589308340
Now, letus invoke the above method by passing all the required parameters −
<?php
$timestamp = mktime(7, 36, 45, 06, 25, 2017);
print($timestamp);
?>
This will produce following result −
1498376205
<?php
$lastday = mktime(0, 0, 0, 3, 0, 2010);
echo strftime("Last day in Feb 2010 is: %dn", $lastday);
$lastday = mktime(0, 0, 0, 4, -31, 2010);
echo strftime("Last day in Feb 2010 is: %d", $lastday);
?>
This produces the following result −
Last day in Feb 2010 is: 28nLast day in Feb 2010 is: 28
45 Lectures
9 hours
Malhar Lathkar
34 Lectures
4 hours
Syed Raza
84 Lectures
5.5 hours
Frahaan Hussain
17 Lectures
1 hours
Nivedita Jain
100 Lectures
34 hours
Azaz Patel
43 Lectures
5.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3002,
"s": 2757,
"text": "The mktime function accepts hours, minutes, seconds, month, day, year as parameters (representing a date) and returns the Unix timestamp for the given date. if you haven't passed any parameters to this method, it returns the current timestamp. "
},
{
"code": null,
"e": 3065,
"s": 3002,
"text": "mktime($hour, $minute, $second, $month, $day,$ year, $is_dst)\n"
},
{
"code": null,
"e": 3082,
"s": 3065,
"text": "hours(Mandatory)"
},
{
"code": null,
"e": 3168,
"s": 3082,
"text": "This is an integer value representing the number of hours of the day, from its start."
},
{
"code": null,
"e": 3186,
"s": 3168,
"text": "minute(Mandatory)"
},
{
"code": null,
"e": 3275,
"s": 3186,
"text": "This is an integer value representing the number of minutes of an hours, from its start."
},
{
"code": null,
"e": 3293,
"s": 3275,
"text": "seconds(Optional)"
},
{
"code": null,
"e": 3379,
"s": 3293,
"text": "This is an integer value representing the number seconds of a minute, from its start."
},
{
"code": null,
"e": 3396,
"s": 3379,
"text": "month(Mandatory)"
},
{
"code": null,
"e": 3490,
"s": 3396,
"text": "This is an integer value representing the month of an year, which should be between 1 and 12."
},
{
"code": null,
"e": 3505,
"s": 3490,
"text": "day(Mandatory)"
},
{
"code": null,
"e": 3628,
"s": 3505,
"text": "This is an integer value representing the day of a date, it should be below the allowed number of days in the given month."
},
{
"code": null,
"e": 3644,
"s": 3628,
"text": "year(Mandatory)"
},
{
"code": null,
"e": 3736,
"s": 3644,
"text": "This is an integer value representing the year of a date, it should be between 1 and 32767."
},
{
"code": null,
"e": 3754,
"s": 3736,
"text": "is_dst(Mandatory)"
},
{
"code": null,
"e": 3873,
"s": 3754,
"text": "This parameter can be set to 1 if the time is during daylight savings time (DST), 0 if it is not, or -1 (the default) "
},
{
"code": null,
"e": 4019,
"s": 3873,
"text": "PHP mktime() function returns an Unix timestamp representing the given date. In case of a failure this function returns the boolean value false. "
},
{
"code": null,
"e": 4113,
"s": 4019,
"text": "This function was first introduced in PHP Version 4.0 and, works with all the later versions."
},
{
"code": null,
"e": 4181,
"s": 4113,
"text": "Following example demonstrates the usage of the mktime() function −"
},
{
"code": null,
"e": 4241,
"s": 4181,
"text": "<?php\n $timestamp = mktime(); \n print($timestamp);\n?>"
},
{
"code": null,
"e": 4278,
"s": 4241,
"text": "This will produce following result −"
},
{
"code": null,
"e": 4290,
"s": 4278,
"text": "1589308340\n"
},
{
"code": null,
"e": 4366,
"s": 4290,
"text": "Now, letus invoke the above method by passing all the required parameters −"
},
{
"code": null,
"e": 4449,
"s": 4366,
"text": "<?php\n $timestamp = mktime(7, 36, 45, 06, 25, 2017); \n print($timestamp);\n?>"
},
{
"code": null,
"e": 4486,
"s": 4449,
"text": "This will produce following result −"
},
{
"code": null,
"e": 4498,
"s": 4486,
"text": "1498376205\n"
},
{
"code": null,
"e": 4717,
"s": 4498,
"text": "<?php\n $lastday = mktime(0, 0, 0, 3, 0, 2010);\n echo strftime(\"Last day in Feb 2010 is: %dn\", $lastday); \n $lastday = mktime(0, 0, 0, 4, -31, 2010);\n echo strftime(\"Last day in Feb 2010 is: %d\", $lastday);\n?>"
},
{
"code": null,
"e": 4754,
"s": 4717,
"text": "This produces the following result −"
},
{
"code": null,
"e": 4811,
"s": 4754,
"text": "Last day in Feb 2010 is: 28nLast day in Feb 2010 is: 28\n"
},
{
"code": null,
"e": 4844,
"s": 4811,
"text": "\n 45 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 4860,
"s": 4844,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4893,
"s": 4860,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4904,
"s": 4893,
"text": " Syed Raza"
},
{
"code": null,
"e": 4939,
"s": 4904,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4956,
"s": 4939,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4989,
"s": 4956,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5004,
"s": 4989,
"text": " Nivedita Jain"
},
{
"code": null,
"e": 5039,
"s": 5004,
"text": "\n 100 Lectures \n 34 hours \n"
},
{
"code": null,
"e": 5051,
"s": 5039,
"text": " Azaz Patel"
},
{
"code": null,
"e": 5086,
"s": 5051,
"text": "\n 43 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5114,
"s": 5086,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 5121,
"s": 5114,
"text": " Print"
},
{
"code": null,
"e": 5132,
"s": 5121,
"text": " Add Notes"
}
] |
Progression - Online Quiz | Following quiz provides Multiple Choice Questions (MCQs) related to Progression. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz.
Q 1 - The sixteenth term of the A.P. 3, 5, 7,9,11.....is
A - 48
B - 50
C - 33
D - 35
Here a = 3 and d= (5-3) = 2
∴ T16 = a+ (16-1) d = a + 15d= (3 + 15*2) = 33.
Q 2 - What number of numbers arrive somewhere around 10 and 200 which are precisely separable by 7?
A - 21
B - 23
C - 25
D - 27
Requisite numbers are 14, 21, 28, 35 .., 196.
This is an A.P. in which a = 14 and d = 7
a +(n-1) d = 196 ⇒ 14+(n-1)*7 =196
= (n-1)*7 = 182 ⇒ (n-1) = 26 ⇒ n = 27.
Q 3 - On the off chance that the tenth term of the succession, a - b, a-2b, a-3b ...is 20 and its twentieth term is 10, then its xth term is:
A - 10-x
B - 20-x
C - 29-x
D - 30-x
This is an A.P. in which A = a and d = (a-b) -a = -b
T10 = 20 ⇒ a+9d = 20 ⇒ a+9*)-b) =20⇒a-9b=20 ... (i)
T20 =10⇒ a+19d = 10 ⇒ a+19*(-b) =10⇒a-19b=10 ... (ii)
On subtracting (ii) from (i) we get 10b = 10 ⇒ b=1
Putting b= 1 in (i) we get a-9*1=20 ⇒ a =29.
∴ xth term = a + (x-1) *d=29+ (x-1) * (-b)
= 29 + (x-1) * (-1) = (30-x).
Q 4 - The total 5+6+7+8+.....+19=?
A - 150
B - 170
C - 180
D - 190
This is an A.P. in which a = 5, d =1 and L=19.
Let the number of its term be n. Then,
Tṇ = 19 ⇒ a + (n-1) d =19
⇒ 5 + (n-1) * 1 = 19 ⇒ (n-1) =14 ⇒ n= 15.
∴ Sṇ = n/2 * (a+L) = 15/2 *(5+19) = 180.
Q 5 - What number of odd number pages arrives in a book of 1089 pages?
A - 542
B - 544
C - 545
D - 546
The pages are 1, 3, 5, 7...,1089.
This is an A.P. in which a= 1, d = (3-1) = 2 and L = 1089.
Let the number of these term be n. then,
(a+ (n-1) d = 1089 ⇒ 1 + (n - 1)* 2 = 1089 ⇒ (n-1 ) * 2 = 1088
n-1 =544⇒ n = 545.
∴ Required number of pages=545.
Q 6 - Which term of the G.P. 5,10,20,40 ...is 1280?
A - Eighth
B - ninth
C - tenth
D - eleventh
Let Tn = 1280. Then ar (n−i) = 1280 ⇒ Here a= 5 and r =2
∴ 5*2(n−i) =1280 ⇒256 = 2(n−i) =28 ⇒ n-1 =8 ⇒ n= 9
Q 7 - In the event that a ≠b, Then which of the accompanying proclamations is valid?
A - a+b/2= √ab
B - a+b/2< √ab
C - a+b/2> √ab
D - All of these
For any two unequal numbers a and b, we have (A.M).> (g.m)
∴ (a+b)/2 > √ab
Q 8 - A clock hums 1 time at 1o, clock, 2 times at 2o, clock, 3 times at 3o, clock etc. What will be the aggregate quantities of hums in a day?
A - 100
B - 150
C - 156
D - None of these
Total number of buzzes =2 (1+2+3+..........+12).
This is an A.P. in which a=1, d=1, n = 12 and L = 12.
(1+2+3+ .........+12) = 12/2* (1+12) = 78.
∴ Total number of buzzes = (2 * 78) = 156.
Q 9 - The number of inhabitants in microbes, society copies ever 2 minutes. How long will it take for the populace to develop from 1000 to 512000 microbes?
A - 10
B - 12
C - 14
D - 18
Let the growth be 1000, 2000, 4000 ...512000.
This is a G.P. in which a = 1000, r = 2 and tn = 512000
Tn = ar&n-1 ⇒ 1000*2 &n-1 = 512000⇒ 2 &n-1 = 512= 29 ⇒ (n-1) = 9.
∴ Time taken = (2*9) min = 18 min.
87 Lectures
22.5 hours
Programming Line
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 4217,
"s": 3892,
"text": "Following quiz provides Multiple Choice Questions (MCQs) related to Progression. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz."
},
{
"code": null,
"e": 4274,
"s": 4217,
"text": "Q 1 - The sixteenth term of the A.P. 3, 5, 7,9,11.....is"
},
{
"code": null,
"e": 4281,
"s": 4274,
"text": "A - 48"
},
{
"code": null,
"e": 4288,
"s": 4281,
"text": "B - 50"
},
{
"code": null,
"e": 4295,
"s": 4288,
"text": "C - 33"
},
{
"code": null,
"e": 4302,
"s": 4295,
"text": "D - 35"
},
{
"code": null,
"e": 4379,
"s": 4302,
"text": " Here a = 3 and d= (5-3) = 2\n∴ T16 = a+ (16-1) d = a + 15d= (3 + 15*2) = 33."
},
{
"code": null,
"e": 4479,
"s": 4379,
"text": "Q 2 - What number of numbers arrive somewhere around 10 and 200 which are precisely separable by 7?"
},
{
"code": null,
"e": 4486,
"s": 4479,
"text": "A - 21"
},
{
"code": null,
"e": 4493,
"s": 4486,
"text": "B - 23"
},
{
"code": null,
"e": 4500,
"s": 4493,
"text": "C - 25"
},
{
"code": null,
"e": 4507,
"s": 4500,
"text": "D - 27"
},
{
"code": null,
"e": 4670,
"s": 4507,
"text": "Requisite numbers are 14, 21, 28, 35 .., 196.\nThis is an A.P. in which a = 14 and d = 7\na +(n-1) d = 196 ⇒ 14+(n-1)*7 =196\n= (n-1)*7 = 182 ⇒ (n-1) = 26 ⇒ n = 27."
},
{
"code": null,
"e": 4812,
"s": 4670,
"text": "Q 3 - On the off chance that the tenth term of the succession, a - b, a-2b, a-3b ...is 20 and its twentieth term is 10, then its xth term is:"
},
{
"code": null,
"e": 4821,
"s": 4812,
"text": "A - 10-x"
},
{
"code": null,
"e": 4830,
"s": 4821,
"text": "B - 20-x"
},
{
"code": null,
"e": 4839,
"s": 4830,
"text": "C - 29-x"
},
{
"code": null,
"e": 4848,
"s": 4839,
"text": "D - 30-x"
},
{
"code": null,
"e": 5176,
"s": 4848,
"text": "This is an A.P. in which A = a and d = (a-b) -a = -b\nT10 = 20 ⇒ a+9d = 20 ⇒ a+9*)-b) =20⇒a-9b=20 ... (i)\nT20 =10⇒ a+19d = 10 ⇒ a+19*(-b) =10⇒a-19b=10 ... (ii)\nOn subtracting (ii) from (i) we get 10b = 10 ⇒ b=1\nPutting b= 1 in (i) we get a-9*1=20 ⇒ a =29.\n∴ xth term = a + (x-1) *d=29+ (x-1) * (-b)\n= 29 + (x-1) * (-1) = (30-x)."
},
{
"code": null,
"e": 5211,
"s": 5176,
"text": "Q 4 - The total 5+6+7+8+.....+19=?"
},
{
"code": null,
"e": 5219,
"s": 5211,
"text": "A - 150"
},
{
"code": null,
"e": 5227,
"s": 5219,
"text": "B - 170"
},
{
"code": null,
"e": 5235,
"s": 5227,
"text": "C - 180"
},
{
"code": null,
"e": 5243,
"s": 5235,
"text": "D - 190"
},
{
"code": null,
"e": 5440,
"s": 5243,
"text": "This is an A.P. in which a = 5, d =1 and L=19.\nLet the number of its term be n. Then,\nTṇ = 19 ⇒ a + (n-1) d =19\n⇒ 5 + (n-1) * 1 = 19 ⇒ (n-1) =14 ⇒ n= 15.\n∴ Sṇ = n/2 * (a+L) = 15/2 *(5+19) = 180."
},
{
"code": null,
"e": 5511,
"s": 5440,
"text": "Q 5 - What number of odd number pages arrives in a book of 1089 pages?"
},
{
"code": null,
"e": 5519,
"s": 5511,
"text": "A - 542"
},
{
"code": null,
"e": 5527,
"s": 5519,
"text": "B - 544"
},
{
"code": null,
"e": 5535,
"s": 5527,
"text": "C - 545"
},
{
"code": null,
"e": 5543,
"s": 5535,
"text": "D - 546"
},
{
"code": null,
"e": 5792,
"s": 5543,
"text": "The pages are 1, 3, 5, 7...,1089.\nThis is an A.P. in which a= 1, d = (3-1) = 2 and L = 1089.\nLet the number of these term be n. then,\n(a+ (n-1) d = 1089 ⇒ 1 + (n - 1)* 2 = 1089 ⇒ (n-1 ) * 2 = 1088\nn-1 =544⇒ n = 545.\n∴ Required number of pages=545."
},
{
"code": null,
"e": 5844,
"s": 5792,
"text": "Q 6 - Which term of the G.P. 5,10,20,40 ...is 1280?"
},
{
"code": null,
"e": 5855,
"s": 5844,
"text": "A - Eighth"
},
{
"code": null,
"e": 5865,
"s": 5855,
"text": "B - ninth"
},
{
"code": null,
"e": 5875,
"s": 5865,
"text": "C - tenth"
},
{
"code": null,
"e": 5888,
"s": 5875,
"text": "D - eleventh"
},
{
"code": null,
"e": 5996,
"s": 5888,
"text": "Let Tn = 1280. Then ar (n−i) = 1280 ⇒ Here a= 5 and r =2\n∴ 5*2(n−i) =1280 ⇒256 = 2(n−i) =28 ⇒ n-1 =8 ⇒ n= 9"
},
{
"code": null,
"e": 6082,
"s": 5996,
"text": "Q 7 - In the event that a ≠b, Then which of the accompanying proclamations is valid?"
},
{
"code": null,
"e": 6097,
"s": 6082,
"text": "A - a+b/2= √ab"
},
{
"code": null,
"e": 6112,
"s": 6097,
"text": "B - a+b/2< √ab"
},
{
"code": null,
"e": 6127,
"s": 6112,
"text": "C - a+b/2> √ab"
},
{
"code": null,
"e": 6144,
"s": 6127,
"text": "D - All of these"
},
{
"code": null,
"e": 6221,
"s": 6144,
"text": "For any two unequal numbers a and b, we have (A.M).> (g.m)\n∴ (a+b)/2 > √ab"
},
{
"code": null,
"e": 6365,
"s": 6221,
"text": "Q 8 - A clock hums 1 time at 1o, clock, 2 times at 2o, clock, 3 times at 3o, clock etc. What will be the aggregate quantities of hums in a day?"
},
{
"code": null,
"e": 6373,
"s": 6365,
"text": "A - 100"
},
{
"code": null,
"e": 6381,
"s": 6373,
"text": "B - 150"
},
{
"code": null,
"e": 6389,
"s": 6381,
"text": "C - 156"
},
{
"code": null,
"e": 6407,
"s": 6389,
"text": "D - None of these"
},
{
"code": null,
"e": 6596,
"s": 6407,
"text": "Total number of buzzes =2 (1+2+3+..........+12).\nThis is an A.P. in which a=1, d=1, n = 12 and L = 12.\n(1+2+3+ .........+12) = 12/2* (1+12) = 78.\n∴ Total number of buzzes = (2 * 78) = 156."
},
{
"code": null,
"e": 6752,
"s": 6596,
"text": "Q 9 - The number of inhabitants in microbes, society copies ever 2 minutes. How long will it take for the populace to develop from 1000 to 512000 microbes?"
},
{
"code": null,
"e": 6759,
"s": 6752,
"text": "A - 10"
},
{
"code": null,
"e": 6766,
"s": 6759,
"text": "B - 12"
},
{
"code": null,
"e": 6773,
"s": 6766,
"text": "C - 14"
},
{
"code": null,
"e": 6780,
"s": 6773,
"text": "D - 18"
},
{
"code": null,
"e": 6983,
"s": 6780,
"text": "Let the growth be 1000, 2000, 4000 ...512000.\nThis is a G.P. in which a = 1000, r = 2 and tn = 512000\nTn = ar&n-1 ⇒ 1000*2 &n-1 = 512000⇒ 2 &n-1 = 512= 29 ⇒ (n-1) = 9.\n∴ Time taken = (2*9) min = 18 min."
},
{
"code": null,
"e": 7019,
"s": 6983,
"text": "\n 87 Lectures \n 22.5 hours \n"
},
{
"code": null,
"e": 7037,
"s": 7019,
"text": " Programming Line"
},
{
"code": null,
"e": 7044,
"s": 7037,
"text": " Print"
},
{
"code": null,
"e": 7055,
"s": 7044,
"text": " Add Notes"
}
] |
How to reverse the column order of the Pandas DataFrame? | 01 Jun, 2021
Sometimes when working with DataFrames we might want to change or reverse the order of the column of the dataframe. In this article, let’s see how to reverse the order of the columns of a dataframe. This can be achieved in two ways –
Method 1: The sequence of columns appearing in the dataframe can be reversed by using the attribute.columns[::-1] on the corresponding dataframe. It accesses the columns from the end and outer dataframe[...] reindexes the dataframe using this new sequence provided.
Example:
Python3
# importing required modulesimport pandas as pd dataframe = pd.DataFrame([[1, 'A', "Student"], [2, 'B', "Tutor"], [3, 'C', "Instructor"]]) print("Original DataFrame")display(dataframe) # reversing the dataframeprint("Reversed DataFrame")display(dataframe[dataframe.columns[::-1]])
Output:
Method 2: iloc indexer can also be used to reverse the column order of the data frame, using the syntax iloc[:, ::-1] on the specified dataframe. The contents are not preserved in the original dataframe.
Python3
# importing required modulesimport pandas as pd dataframe = pd.DataFrame([[1, 'A', "Student"], [2, 'B', "Tutor"], [3, 'C', "Instructor"]]) print("Original DataFrame")display(dataframe) # reversing the dataframeprint("Reversed DataFrame")display(dataframe.iloc[:, ::-1])
Output:
adnanirshad158
Picked
Python pandas-dataFrame
Python Pandas-exercise
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 Jun, 2021"
},
{
"code": null,
"e": 262,
"s": 28,
"text": "Sometimes when working with DataFrames we might want to change or reverse the order of the column of the dataframe. In this article, let’s see how to reverse the order of the columns of a dataframe. This can be achieved in two ways –"
},
{
"code": null,
"e": 529,
"s": 262,
"text": "Method 1: The sequence of columns appearing in the dataframe can be reversed by using the attribute.columns[::-1] on the corresponding dataframe. It accesses the columns from the end and outer dataframe[...] reindexes the dataframe using this new sequence provided. "
},
{
"code": null,
"e": 538,
"s": 529,
"text": "Example:"
},
{
"code": null,
"e": 546,
"s": 538,
"text": "Python3"
},
{
"code": "# importing required modulesimport pandas as pd dataframe = pd.DataFrame([[1, 'A', \"Student\"], [2, 'B', \"Tutor\"], [3, 'C', \"Instructor\"]]) print(\"Original DataFrame\")display(dataframe) # reversing the dataframeprint(\"Reversed DataFrame\")display(dataframe[dataframe.columns[::-1]])",
"e": 878,
"s": 546,
"text": null
},
{
"code": null,
"e": 886,
"s": 878,
"text": "Output:"
},
{
"code": null,
"e": 1091,
"s": 886,
"text": "Method 2: iloc indexer can also be used to reverse the column order of the data frame, using the syntax iloc[:, ::-1] on the specified dataframe. The contents are not preserved in the original dataframe. "
},
{
"code": null,
"e": 1099,
"s": 1091,
"text": "Python3"
},
{
"code": "# importing required modulesimport pandas as pd dataframe = pd.DataFrame([[1, 'A', \"Student\"], [2, 'B', \"Tutor\"], [3, 'C', \"Instructor\"]]) print(\"Original DataFrame\")display(dataframe) # reversing the dataframeprint(\"Reversed DataFrame\")display(dataframe.iloc[:, ::-1])",
"e": 1420,
"s": 1099,
"text": null
},
{
"code": null,
"e": 1428,
"s": 1420,
"text": "Output:"
},
{
"code": null,
"e": 1443,
"s": 1428,
"text": "adnanirshad158"
},
{
"code": null,
"e": 1450,
"s": 1443,
"text": "Picked"
},
{
"code": null,
"e": 1474,
"s": 1450,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 1497,
"s": 1474,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 1511,
"s": 1497,
"text": "Python-pandas"
},
{
"code": null,
"e": 1518,
"s": 1511,
"text": "Python"
}
] |
Mid-Point Circle Drawing Algorithm | 19 Mar, 2022
The mid-point circle drawing algorithm is an algorithm used to determine the points needed for rasterizing a circle.
We use the mid-point algorithm to calculate all the perimeter points of the circle in the first octant and then print them along with their mirror points in the other octants. This will work because a circle is symmetric about its centre.
The algorithm is very similar to the Mid-Point Line Generation Algorithm. Here, only the boundary condition is different.
For any given pixel (x, y), the next pixel to be plotted is either (x, y+1) or (x-1, y+1). This can be decided by following the steps below.
Find the mid-point p of the two possible pixels i.e (x-0.5, y+1)If p lies inside or on the circle perimeter, we plot the pixel (x, y+1), otherwise if it’s outside we plot the pixel (x-1, y+1)
Find the mid-point p of the two possible pixels i.e (x-0.5, y+1)
If p lies inside or on the circle perimeter, we plot the pixel (x, y+1), otherwise if it’s outside we plot the pixel (x-1, y+1)
Boundary Condition : Whether the mid-point lies inside or outside the circle can be decided by using the formula:-
Given a circle centered at (0,0) and radius r and a point p(x,y) F(p) = x2 + y2 – r2 if F(p)<0, the point is inside the circleF(p)=0, the point is on the perimeterF(p)>0, the point is outside the circle
In our program, we denote F(p) with P. The value of P is calculated at the mid-point of the two contending pixels i.e. (x-0.5, y+1). Each pixel is described with a subscript k.
Pk = (Xk — 0.5)2 + (yk + 1)2 – r2 Now, xk+1 = xk or xk-1 , yk+1= yk +1∴ Pk+1 = (xk+1 – 0.5)2 + (yk+1 +1)2 – r2 = (xk+1 – 0.5)2 + [(yk +1) + 1]2 – r2 = (xk+1 – 0.5)2 + (yk +1)2 + 2(yk + 1) + 1 – r2 = (xk+1 – 0.5)2 + [ – (xk – 0.5)2 +(xk – 0.5)2 ] + (yk + 1)2 – r2 + 2(yk + 1) + 1= Pk + (xk+1 – 0.5)2 – (xk – 0.5)2 + 2(yk + 1) + 1 = Pk + (x2k+1 – x2k) – (xk+1 – xk) + 2(yk + 1) + 1 = Pk + 2(yk +1) + 1, when Pk <=0 i.e the midpoint is inside the circle (xk+1 = xk) Pk + 2(yk +1) – 2(xk – 1) + 1, when Pk>0 I.e the mid point is outside the circle(xk+1 = xk-1)
The first point to be plotted is (r, 0) on the x-axis. The initial value of P is calculated as follows:-
P1 = (r – 0.5)2 + (0+1)2 – r2 = 1.25 – r = 1 -r (When rounded off)
Examples:
Input : Centre -> (0, 0), Radius -> 3
Output : (3, 0) (3, 0) (0, 3) (0, 3)
(3, 1) (-3, 1) (3, -1) (-3, -1)
(1, 3) (-1, 3) (1, -3) (-1, -3)
(2, 2) (-2, 2) (2, -2) (-2, -2)
Input : Centre -> (4, 4), Radius -> 2
Output : (6, 4) (6, 4) (4, 6) (4, 6)
(6, 5) (2, 5) (6, 3) (2, 3)
(5, 6) (3, 6) (5, 2) (3, 2)
CPP
C
Java
Python3
C#
PHP
Javascript
// C++ program for implementing// Mid-Point Circle Drawing Algorithm#include<iostream>using namespace std; // Implementing Mid-Point Circle Drawing Algorithmvoid midPointCircleDraw(int x_centre, int y_centre, int r){ int x = r, y = 0; // Printing the initial point on the axes // after translation cout << "(" << x + x_centre << ", " << y + y_centre << ") "; // When radius is zero only a single // point will be printed if (r > 0) { cout << "(" << x + x_centre << ", " << -y + y_centre << ") "; cout << "(" << y + x_centre << ", " << x + y_centre << ") "; cout << "(" << -y + x_centre << ", " << x + y_centre << ")\n"; } // Initialising the value of P int P = 1 - r; while (x > y) { y++; // Mid-point is inside or on the perimeter if (P <= 0) P = P + 2*y + 1; // Mid-point is outside the perimeter else { x--; P = P + 2*y - 2*x + 1; } // All the perimeter points have already been printed if (x < y) break; // Printing the generated point and its reflection // in the other octants after translation cout << "(" << x + x_centre << ", " << y + y_centre << ") "; cout << "(" << -x + x_centre << ", " << y + y_centre << ") "; cout << "(" << x + x_centre << ", " << -y + y_centre << ") "; cout << "(" << -x + x_centre << ", " << -y + y_centre << ")\n"; // If the generated point is on the line x = y then // the perimeter points have already been printed if (x != y) { cout << "(" << y + x_centre << ", " << x + y_centre << ") "; cout << "(" << -y + x_centre << ", " << x + y_centre << ") "; cout << "(" << y + x_centre << ", " << -x + y_centre << ") "; cout << "(" << -y + x_centre << ", " << -x + y_centre << ")\n"; } }} // Driver codeint main(){ // To draw a circle of radius 3 centered at (0, 0) midPointCircleDraw(0, 0, 3); return 0;}
// C program for implementing// Mid-Point Circle Drawing Algorithm#include<stdio.h> // Implementing Mid-Point Circle Drawing Algorithmvoid midPointCircleDraw(int x_centre, int y_centre, int r){ int x = r, y = 0; // Printing the initial point on the axes // after translation printf("(%d, %d) ", x + x_centre, y + y_centre); // When radius is zero only a single // point will be printed if (r > 0) { printf("(%d, %d) ", x + x_centre, -y + y_centre); printf("(%d, %d) ", y + x_centre, x + y_centre); printf("(%d, %d)\n", -y + x_centre, x + y_centre); } // Initialising the value of P int P = 1 - r; while (x > y) { y++; // Mid-point is inside or on the perimeter if (P <= 0) P = P + 2*y + 1; // Mid-point is outside the perimeter else { x--; P = P + 2*y - 2*x + 1; } // All the perimeter points have already been printed if (x < y) break; // Printing the generated point and its reflection // in the other octants after translation printf("(%d, %d) ", x + x_centre, y + y_centre); printf("(%d, %d) ", -x + x_centre, y + y_centre); printf("(%d, %d) ", x + x_centre, -y + y_centre); printf("(%d, %d)\n", -x + x_centre, -y + y_centre); // If the generated point is on the line x = y then // the perimeter points have already been printed if (x != y) { printf("(%d, %d) ", y + x_centre, x + y_centre); printf("(%d, %d) ", -y + x_centre, x + y_centre); printf("(%d, %d) ", y + x_centre, -x + y_centre); printf("(%d, %d)\n", -y + x_centre, -x + y_centre); } }} // Driver codeint main(){ // To draw a circle of radius 3 centered at (0, 0) midPointCircleDraw(0, 0, 3); return 0;}
// Java program for implementing// Mid-Point Circle Drawing Algorithmclass GFG { // Implementing Mid-Point Circle // Drawing Algorithm static void midPointCircleDraw(int x_centre, int y_centre, int r) { int x = r, y = 0; // Printing the initial point // on the axes after translation System.out.print("(" + (x + x_centre) + ", " + (y + y_centre) + ")"); // When radius is zero only a single // point will be printed if (r > 0) { System.out.print("(" + (x + x_centre) + ", " + (-y + y_centre) + ")"); System.out.print("(" + (y + x_centre) + ", " + (x + y_centre) + ")"); System.out.println("(" + (-y + x_centre) + ", " + (x + y_centre) + ")"); } // Initialising the value of P int P = 1 - r; while (x > y) { y++; // Mid-point is inside or on the perimeter if (P <= 0) P = P + 2 * y + 1; // Mid-point is outside the perimeter else { x--; P = P + 2 * y - 2 * x + 1; } // All the perimeter points have already // been printed if (x < y) break; // Printing the generated point and its // reflection in the other octants after // translation System.out.print("(" + (x + x_centre) + ", " + (y + y_centre) + ")"); System.out.print("(" + (-x + x_centre) + ", " + (y + y_centre) + ")"); System.out.print("(" + (x + x_centre) + ", " + (-y + y_centre) + ")"); System.out.println("(" + (-x + x_centre) + ", " + (-y + y_centre) + ")"); // If the generated point is on the // line x = y then the perimeter points // have already been printed if (x != y) { System.out.print("(" + (y + x_centre) + ", " + (x + y_centre) + ")"); System.out.print("(" + (-y + x_centre) + ", " + (x + y_centre) + ")"); System.out.print("(" + (y + x_centre) + ", " + (-x + y_centre) + ")"); System.out.println("(" + (-y + x_centre) + ", " + (-x + y_centre) +")"); } } } // Driver code public static void main(String[] args) { // To draw a circle of radius // 3 centered at (0, 0) midPointCircleDraw(0, 0, 3); }} // This code is contributed by Anant Agarwal.
# Python3 program for implementing# Mid-Point Circle Drawing Algorithm def midPointCircleDraw(x_centre, y_centre, r): x = r y = 0 # Printing the initial point the # axes after translation print("(", x + x_centre, ", ", y + y_centre, ")", sep = "", end = "") # When radius is zero only a single # point be printed if (r > 0) : print("(", x + x_centre, ", ", -y + y_centre, ")", sep = "", end = "") print("(", y + x_centre, ", ", x + y_centre, ")", sep = "", end = "") print("(", -y + x_centre, ", ", x + y_centre, ")", sep = "") # Initialising the value of P P = 1 - r while x > y: y += 1 # Mid-point inside or on the perimeter if P <= 0: P = P + 2 * y + 1 # Mid-point outside the perimeter else: x -= 1 P = P + 2 * y - 2 * x + 1 # All the perimeter points have # already been printed if (x < y): break # Printing the generated point its reflection # in the other octants after translation print("(", x + x_centre, ", ", y + y_centre, ")", sep = "", end = "") print("(", -x + x_centre, ", ", y + y_centre, ")", sep = "", end = "") print("(", x + x_centre, ", ", -y + y_centre, ")", sep = "", end = "") print("(", -x + x_centre, ", ", -y + y_centre, ")", sep = "") # If the generated point on the line x = y then # the perimeter points have already been printed if x != y: print("(", y + x_centre, ", ", x + y_centre, ")", sep = "", end = "") print("(", -y + x_centre, ", ", x + y_centre, ")", sep = "", end = "") print("(", y + x_centre, ", ", -x + y_centre, ")", sep = "", end = "") print("(", -y + x_centre, ", ", -x + y_centre, ")", sep = "") # Driver Codeif __name__ == '__main__': # To draw a circle of radius 3 # centered at (0, 0) midPointCircleDraw(0, 0, 3) # Contributed by: SHUBHAMSINGH10# Improved by: siddharthx_07
// C# program for implementing Mid-Point// Circle Drawing Algorithmusing System; class GFG { // Implementing Mid-Point Circle // Drawing Algorithm static void midPointCircleDraw(int x_centre, int y_centre, int r) { int x = r, y = 0; // Printing the initial point on the // axes after translation Console.Write("(" + (x + x_centre) + ", " + (y + y_centre) + ")"); // When radius is zero only a single // point will be printed if (r > 0) { Console.Write("(" + (x + x_centre) + ", " + (-y + y_centre) + ")"); Console.Write("(" + (y + x_centre) + ", " + (x + y_centre) + ")"); Console.WriteLine("(" + (-y + x_centre) + ", " + (x + y_centre) + ")"); } // Initialising the value of P int P = 1 - r; while (x > y) { y++; // Mid-point is inside or on the perimeter if (P <= 0) P = P + 2 * y + 1; // Mid-point is outside the perimeter else { x--; P = P + 2 * y - 2 * x + 1; } // All the perimeter points have already // been printed if (x < y) break; // Printing the generated point and its // reflection in the other octants after // translation Console.Write("(" + (x + x_centre) + ", " + (y + y_centre) + ")"); Console.Write("(" + (-x + x_centre) + ", " + (y + y_centre) + ")"); Console.Write("(" + (x + x_centre) + ", " + (-y + y_centre) + ")"); Console.WriteLine("(" + (-x + x_centre) + ", " + (-y + y_centre) + ")"); // If the generated point is on the // line x = y then the perimeter points // have already been printed if (x != y) { Console.Write("(" + (y + x_centre) + ", " + (x + y_centre) + ")"); Console.Write("(" + (-y + x_centre) + ", " + (x + y_centre) + ")"); Console.Write("(" + (y + x_centre) + ", " + (-x + y_centre) + ")"); Console.WriteLine("(" + (-y + x_centre) + ", " + (-x + y_centre) +")"); } } } // Driver code public static void Main() { // To draw a circle of radius // 3 centered at (0, 0) midPointCircleDraw(0, 0, 3); }} // This code is contributed by nitin mittal.
<?php// PHP program for implementing// Mid-Point Circle Drawing Algorithm // Implementing Mid-Point// Circle Drawing Algorithmfunction midPointCircleDraw($x_centre, $y_centre, $r){ $x = $r; $y = 0; // Printing the initial // point on the axes // after translation echo "(",$x + $x_centre,",", $y + $y_centre,")"; // When radius is zero only a single // point will be printed if ($r > 0) { echo "(",$x + $x_centre,",", -$y + $y_centre,")"; echo "(",$y + $x_centre,",", $x + $y_centre,")"; echo "(",-$y + $x_centre,",", $x + $y_centre,")","\n"; } // Initializing the value of P $P = 1 - $r; while ($x > $y) { $y++; // Mid-point is inside // or on the perimeter if ($P <= 0) $P = $P + 2 * $y + 1; // Mid-point is outside // the perimeter else { $x--; $P = $P + 2 * $y - 2 * $x + 1; } // All the perimeter points // have already been printed if ($x < $y) break; // Printing the generated // point and its reflection // in the other octants // after translation echo "(",$x + $x_centre,",", $y + $y_centre,")"; echo "(",-$x + $x_centre,",", $y + $y_centre,")"; echo "(",$x +$x_centre,",", -$y + $y_centre,")"; echo "(",-$x + $x_centre,",", -$y + $y_centre,")","\n"; // If the generated point is // on the line x = y then // the perimeter points have // already been printed if ($x != $y) { echo "(",$y + $x_centre,",", $x + $y_centre,")"; echo "(",-$y + $x_centre,",", $x + $y_centre,")"; echo "(",$y + $x_centre,",", -$x + $y_centre,")"; echo "(",-$y + $x_centre,",", -$x + $y_centre,")","\n"; } }} // Driver code // To draw a circle of radius // 3 centered at (0, 0) midPointCircleDraw(0, 0, 3); // This code is contributed by nitin mittal.?>
<script>// javascript program for implementing// Mid-Point Circle Drawing Algorithm // Implementing Mid-Point Circle // Drawing Algorithm function midPointCircleDraw(x_centre , y_centre , r) { var x = r, y = 0; // Printing the initial point // on the axes after translation document.write("(" + (x + x_centre) + ", " + (y + y_centre) + ")"); // When radius is zero only a single // point will be printed if (r > 0) { document.write("(" + (x + x_centre) + ", " + (-y + y_centre) + ")"); document.write("(" + (y + x_centre) + ", " + (x + y_centre) + ")"); document.write("(" + (-y + x_centre) + ", " + (x + y_centre) + ")<br/>"); } // Initialising the value of P var P = 1 - r; while (x > y) { y++; // Mid-point is inside or on the perimeter if (P <= 0) P = P + 2 * y + 1; // Mid-point is outside the perimeter else { x--; P = P + 2 * y - 2 * x + 1; } // All the perimeter points have already // been printed if (x < y) break; // Printing the generated point and its // reflection in the other octants after // translation document.write("(" + (x + x_centre) + ", " + (y + y_centre) + ")"); document.write("(" + (-x + x_centre) + ", " + (y + y_centre) + ")"); document.write("(" + (x + x_centre) + ", " + (-y + y_centre) + ")"); document.write("(" + (-x + x_centre) + ", " + (-y + y_centre) + ")<br/>"); // If the generated point is on the // line x = y then the perimeter points // have already been printed if (x != y) { document.write("(" + (y + x_centre) + ", " + (x + y_centre) + ")"); document.write("(" + (-y + x_centre) + ", " + (x + y_centre) + ")"); document.write("(" + (y + x_centre) + ", " + (-x + y_centre) + ")"); document.write("(" + (-y + x_centre) + ", " + (-x + y_centre) + ")<br/>"); } } } // Driver code // To draw a circle of radius // 3 centered at (0, 0) midPointCircleDraw(0, 0, 3); // This code is contributed by umadevi9616</script>
Output:
(3, 0) (3, 0) (0, 3) (0, 3)
(3, 1) (-3, 1) (3, -1) (-3, -1)
(1, 3) (-1, 3) (1, -3) (-1, -3)
(2, 2) (-2, 2) (2, -2) (-2, -2)
Time Complexity: O(x – y)Auxiliary Space: O(1) References : Midpoint Circle Algorithm Image References : Octants of a circle, Rasterised Circle, the other images were created for this article by the geekThanks Tuhina Singh and Teva Zanker for improving this article. This article is contributed by Nabaneet Roy. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
SHUBHAMSINGH10
siddharthx_07
pankajsharmagfg
umadevi9616
simranarora5sos
adnanirshad158
tevazanker
computer-graphics
Algorithms
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Mar, 2022"
},
{
"code": null,
"e": 171,
"s": 52,
"text": "The mid-point circle drawing algorithm is an algorithm used to determine the points needed for rasterizing a circle. "
},
{
"code": null,
"e": 410,
"s": 171,
"text": "We use the mid-point algorithm to calculate all the perimeter points of the circle in the first octant and then print them along with their mirror points in the other octants. This will work because a circle is symmetric about its centre."
},
{
"code": null,
"e": 536,
"s": 414,
"text": "The algorithm is very similar to the Mid-Point Line Generation Algorithm. Here, only the boundary condition is different."
},
{
"code": null,
"e": 679,
"s": 538,
"text": "For any given pixel (x, y), the next pixel to be plotted is either (x, y+1) or (x-1, y+1). This can be decided by following the steps below."
},
{
"code": null,
"e": 873,
"s": 681,
"text": "Find the mid-point p of the two possible pixels i.e (x-0.5, y+1)If p lies inside or on the circle perimeter, we plot the pixel (x, y+1), otherwise if it’s outside we plot the pixel (x-1, y+1)"
},
{
"code": null,
"e": 938,
"s": 873,
"text": "Find the mid-point p of the two possible pixels i.e (x-0.5, y+1)"
},
{
"code": null,
"e": 1066,
"s": 938,
"text": "If p lies inside or on the circle perimeter, we plot the pixel (x, y+1), otherwise if it’s outside we plot the pixel (x-1, y+1)"
},
{
"code": null,
"e": 1183,
"s": 1066,
"text": "Boundary Condition : Whether the mid-point lies inside or outside the circle can be decided by using the formula:- "
},
{
"code": null,
"e": 1388,
"s": 1183,
"text": "Given a circle centered at (0,0) and radius r and a point p(x,y) F(p) = x2 + y2 – r2 if F(p)<0, the point is inside the circleF(p)=0, the point is on the perimeterF(p)>0, the point is outside the circle "
},
{
"code": null,
"e": 1568,
"s": 1390,
"text": "In our program, we denote F(p) with P. The value of P is calculated at the mid-point of the two contending pixels i.e. (x-0.5, y+1). Each pixel is described with a subscript k. "
},
{
"code": null,
"e": 2127,
"s": 1568,
"text": "Pk = (Xk — 0.5)2 + (yk + 1)2 – r2 Now, xk+1 = xk or xk-1 , yk+1= yk +1∴ Pk+1 = (xk+1 – 0.5)2 + (yk+1 +1)2 – r2 = (xk+1 – 0.5)2 + [(yk +1) + 1]2 – r2 = (xk+1 – 0.5)2 + (yk +1)2 + 2(yk + 1) + 1 – r2 = (xk+1 – 0.5)2 + [ – (xk – 0.5)2 +(xk – 0.5)2 ] + (yk + 1)2 – r2 + 2(yk + 1) + 1= Pk + (xk+1 – 0.5)2 – (xk – 0.5)2 + 2(yk + 1) + 1 = Pk + (x2k+1 – x2k) – (xk+1 – xk) + 2(yk + 1) + 1 = Pk + 2(yk +1) + 1, when Pk <=0 i.e the midpoint is inside the circle (xk+1 = xk) Pk + 2(yk +1) – 2(xk – 1) + 1, when Pk>0 I.e the mid point is outside the circle(xk+1 = xk-1) "
},
{
"code": null,
"e": 2233,
"s": 2127,
"text": "The first point to be plotted is (r, 0) on the x-axis. The initial value of P is calculated as follows:- "
},
{
"code": null,
"e": 2301,
"s": 2233,
"text": "P1 = (r – 0.5)2 + (0+1)2 – r2 = 1.25 – r = 1 -r (When rounded off) "
},
{
"code": null,
"e": 2313,
"s": 2301,
"text": "Examples: "
},
{
"code": null,
"e": 2511,
"s": 2313,
"text": "Input : Centre -> (0, 0), Radius -> 3\nOutput : (3, 0) (3, 0) (0, 3) (0, 3)\n (3, 1) (-3, 1) (3, -1) (-3, -1)\n (1, 3) (-1, 3) (1, -3) (-1, -3)\n (2, 2) (-2, 2) (2, -2) (-2, -2)"
},
{
"code": null,
"e": 2662,
"s": 2513,
"text": "Input : Centre -> (4, 4), Radius -> 2\nOutput : (6, 4) (6, 4) (4, 6) (4, 6)\n (6, 5) (2, 5) (6, 3) (2, 3)\n (5, 6) (3, 6) (5, 2) (3, 2)"
},
{
"code": null,
"e": 2666,
"s": 2662,
"text": "CPP"
},
{
"code": null,
"e": 2668,
"s": 2666,
"text": "C"
},
{
"code": null,
"e": 2673,
"s": 2668,
"text": "Java"
},
{
"code": null,
"e": 2681,
"s": 2673,
"text": "Python3"
},
{
"code": null,
"e": 2684,
"s": 2681,
"text": "C#"
},
{
"code": null,
"e": 2688,
"s": 2684,
"text": "PHP"
},
{
"code": null,
"e": 2699,
"s": 2688,
"text": "Javascript"
},
{
"code": "// C++ program for implementing// Mid-Point Circle Drawing Algorithm#include<iostream>using namespace std; // Implementing Mid-Point Circle Drawing Algorithmvoid midPointCircleDraw(int x_centre, int y_centre, int r){ int x = r, y = 0; // Printing the initial point on the axes // after translation cout << \"(\" << x + x_centre << \", \" << y + y_centre << \") \"; // When radius is zero only a single // point will be printed if (r > 0) { cout << \"(\" << x + x_centre << \", \" << -y + y_centre << \") \"; cout << \"(\" << y + x_centre << \", \" << x + y_centre << \") \"; cout << \"(\" << -y + x_centre << \", \" << x + y_centre << \")\\n\"; } // Initialising the value of P int P = 1 - r; while (x > y) { y++; // Mid-point is inside or on the perimeter if (P <= 0) P = P + 2*y + 1; // Mid-point is outside the perimeter else { x--; P = P + 2*y - 2*x + 1; } // All the perimeter points have already been printed if (x < y) break; // Printing the generated point and its reflection // in the other octants after translation cout << \"(\" << x + x_centre << \", \" << y + y_centre << \") \"; cout << \"(\" << -x + x_centre << \", \" << y + y_centre << \") \"; cout << \"(\" << x + x_centre << \", \" << -y + y_centre << \") \"; cout << \"(\" << -x + x_centre << \", \" << -y + y_centre << \")\\n\"; // If the generated point is on the line x = y then // the perimeter points have already been printed if (x != y) { cout << \"(\" << y + x_centre << \", \" << x + y_centre << \") \"; cout << \"(\" << -y + x_centre << \", \" << x + y_centre << \") \"; cout << \"(\" << y + x_centre << \", \" << -x + y_centre << \") \"; cout << \"(\" << -y + x_centre << \", \" << -x + y_centre << \")\\n\"; } }} // Driver codeint main(){ // To draw a circle of radius 3 centered at (0, 0) midPointCircleDraw(0, 0, 3); return 0;}",
"e": 4787,
"s": 2699,
"text": null
},
{
"code": "// C program for implementing// Mid-Point Circle Drawing Algorithm#include<stdio.h> // Implementing Mid-Point Circle Drawing Algorithmvoid midPointCircleDraw(int x_centre, int y_centre, int r){ int x = r, y = 0; // Printing the initial point on the axes // after translation printf(\"(%d, %d) \", x + x_centre, y + y_centre); // When radius is zero only a single // point will be printed if (r > 0) { printf(\"(%d, %d) \", x + x_centre, -y + y_centre); printf(\"(%d, %d) \", y + x_centre, x + y_centre); printf(\"(%d, %d)\\n\", -y + x_centre, x + y_centre); } // Initialising the value of P int P = 1 - r; while (x > y) { y++; // Mid-point is inside or on the perimeter if (P <= 0) P = P + 2*y + 1; // Mid-point is outside the perimeter else { x--; P = P + 2*y - 2*x + 1; } // All the perimeter points have already been printed if (x < y) break; // Printing the generated point and its reflection // in the other octants after translation printf(\"(%d, %d) \", x + x_centre, y + y_centre); printf(\"(%d, %d) \", -x + x_centre, y + y_centre); printf(\"(%d, %d) \", x + x_centre, -y + y_centre); printf(\"(%d, %d)\\n\", -x + x_centre, -y + y_centre); // If the generated point is on the line x = y then // the perimeter points have already been printed if (x != y) { printf(\"(%d, %d) \", y + x_centre, x + y_centre); printf(\"(%d, %d) \", -y + x_centre, x + y_centre); printf(\"(%d, %d) \", y + x_centre, -x + y_centre); printf(\"(%d, %d)\\n\", -y + x_centre, -x + y_centre); } }} // Driver codeint main(){ // To draw a circle of radius 3 centered at (0, 0) midPointCircleDraw(0, 0, 3); return 0;}",
"e": 6721,
"s": 4787,
"text": null
},
{
"code": "// Java program for implementing// Mid-Point Circle Drawing Algorithmclass GFG { // Implementing Mid-Point Circle // Drawing Algorithm static void midPointCircleDraw(int x_centre, int y_centre, int r) { int x = r, y = 0; // Printing the initial point // on the axes after translation System.out.print(\"(\" + (x + x_centre) + \", \" + (y + y_centre) + \")\"); // When radius is zero only a single // point will be printed if (r > 0) { System.out.print(\"(\" + (x + x_centre) + \", \" + (-y + y_centre) + \")\"); System.out.print(\"(\" + (y + x_centre) + \", \" + (x + y_centre) + \")\"); System.out.println(\"(\" + (-y + x_centre) + \", \" + (x + y_centre) + \")\"); } // Initialising the value of P int P = 1 - r; while (x > y) { y++; // Mid-point is inside or on the perimeter if (P <= 0) P = P + 2 * y + 1; // Mid-point is outside the perimeter else { x--; P = P + 2 * y - 2 * x + 1; } // All the perimeter points have already // been printed if (x < y) break; // Printing the generated point and its // reflection in the other octants after // translation System.out.print(\"(\" + (x + x_centre) + \", \" + (y + y_centre) + \")\"); System.out.print(\"(\" + (-x + x_centre) + \", \" + (y + y_centre) + \")\"); System.out.print(\"(\" + (x + x_centre) + \", \" + (-y + y_centre) + \")\"); System.out.println(\"(\" + (-x + x_centre) + \", \" + (-y + y_centre) + \")\"); // If the generated point is on the // line x = y then the perimeter points // have already been printed if (x != y) { System.out.print(\"(\" + (y + x_centre) + \", \" + (x + y_centre) + \")\"); System.out.print(\"(\" + (-y + x_centre) + \", \" + (x + y_centre) + \")\"); System.out.print(\"(\" + (y + x_centre) + \", \" + (-x + y_centre) + \")\"); System.out.println(\"(\" + (-y + x_centre) + \", \" + (-x + y_centre) +\")\"); } } } // Driver code public static void main(String[] args) { // To draw a circle of radius // 3 centered at (0, 0) midPointCircleDraw(0, 0, 3); }} // This code is contributed by Anant Agarwal.",
"e": 9701,
"s": 6721,
"text": null
},
{
"code": "# Python3 program for implementing# Mid-Point Circle Drawing Algorithm def midPointCircleDraw(x_centre, y_centre, r): x = r y = 0 # Printing the initial point the # axes after translation print(\"(\", x + x_centre, \", \", y + y_centre, \")\", sep = \"\", end = \"\") # When radius is zero only a single # point be printed if (r > 0) : print(\"(\", x + x_centre, \", \", -y + y_centre, \")\", sep = \"\", end = \"\") print(\"(\", y + x_centre, \", \", x + y_centre, \")\", sep = \"\", end = \"\") print(\"(\", -y + x_centre, \", \", x + y_centre, \")\", sep = \"\") # Initialising the value of P P = 1 - r while x > y: y += 1 # Mid-point inside or on the perimeter if P <= 0: P = P + 2 * y + 1 # Mid-point outside the perimeter else: x -= 1 P = P + 2 * y - 2 * x + 1 # All the perimeter points have # already been printed if (x < y): break # Printing the generated point its reflection # in the other octants after translation print(\"(\", x + x_centre, \", \", y + y_centre, \")\", sep = \"\", end = \"\") print(\"(\", -x + x_centre, \", \", y + y_centre, \")\", sep = \"\", end = \"\") print(\"(\", x + x_centre, \", \", -y + y_centre, \")\", sep = \"\", end = \"\") print(\"(\", -x + x_centre, \", \", -y + y_centre, \")\", sep = \"\") # If the generated point on the line x = y then # the perimeter points have already been printed if x != y: print(\"(\", y + x_centre, \", \", x + y_centre, \")\", sep = \"\", end = \"\") print(\"(\", -y + x_centre, \", \", x + y_centre, \")\", sep = \"\", end = \"\") print(\"(\", y + x_centre, \", \", -x + y_centre, \")\", sep = \"\", end = \"\") print(\"(\", -y + x_centre, \", \", -x + y_centre, \")\", sep = \"\") # Driver Codeif __name__ == '__main__': # To draw a circle of radius 3 # centered at (0, 0) midPointCircleDraw(0, 0, 3) # Contributed by: SHUBHAMSINGH10# Improved by: siddharthx_07",
"e": 12200,
"s": 9701,
"text": null
},
{
"code": "// C# program for implementing Mid-Point// Circle Drawing Algorithmusing System; class GFG { // Implementing Mid-Point Circle // Drawing Algorithm static void midPointCircleDraw(int x_centre, int y_centre, int r) { int x = r, y = 0; // Printing the initial point on the // axes after translation Console.Write(\"(\" + (x + x_centre) + \", \" + (y + y_centre) + \")\"); // When radius is zero only a single // point will be printed if (r > 0) { Console.Write(\"(\" + (x + x_centre) + \", \" + (-y + y_centre) + \")\"); Console.Write(\"(\" + (y + x_centre) + \", \" + (x + y_centre) + \")\"); Console.WriteLine(\"(\" + (-y + x_centre) + \", \" + (x + y_centre) + \")\"); } // Initialising the value of P int P = 1 - r; while (x > y) { y++; // Mid-point is inside or on the perimeter if (P <= 0) P = P + 2 * y + 1; // Mid-point is outside the perimeter else { x--; P = P + 2 * y - 2 * x + 1; } // All the perimeter points have already // been printed if (x < y) break; // Printing the generated point and its // reflection in the other octants after // translation Console.Write(\"(\" + (x + x_centre) + \", \" + (y + y_centre) + \")\"); Console.Write(\"(\" + (-x + x_centre) + \", \" + (y + y_centre) + \")\"); Console.Write(\"(\" + (x + x_centre) + \", \" + (-y + y_centre) + \")\"); Console.WriteLine(\"(\" + (-x + x_centre) + \", \" + (-y + y_centre) + \")\"); // If the generated point is on the // line x = y then the perimeter points // have already been printed if (x != y) { Console.Write(\"(\" + (y + x_centre) + \", \" + (x + y_centre) + \")\"); Console.Write(\"(\" + (-y + x_centre) + \", \" + (x + y_centre) + \")\"); Console.Write(\"(\" + (y + x_centre) + \", \" + (-x + y_centre) + \")\"); Console.WriteLine(\"(\" + (-y + x_centre) + \", \" + (-x + y_centre) +\")\"); } } } // Driver code public static void Main() { // To draw a circle of radius // 3 centered at (0, 0) midPointCircleDraw(0, 0, 3); }} // This code is contributed by nitin mittal.",
"e": 15165,
"s": 12200,
"text": null
},
{
"code": "<?php// PHP program for implementing// Mid-Point Circle Drawing Algorithm // Implementing Mid-Point// Circle Drawing Algorithmfunction midPointCircleDraw($x_centre, $y_centre, $r){ $x = $r; $y = 0; // Printing the initial // point on the axes // after translation echo \"(\",$x + $x_centre,\",\", $y + $y_centre,\")\"; // When radius is zero only a single // point will be printed if ($r > 0) { echo \"(\",$x + $x_centre,\",\", -$y + $y_centre,\")\"; echo \"(\",$y + $x_centre,\",\", $x + $y_centre,\")\"; echo \"(\",-$y + $x_centre,\",\", $x + $y_centre,\")\",\"\\n\"; } // Initializing the value of P $P = 1 - $r; while ($x > $y) { $y++; // Mid-point is inside // or on the perimeter if ($P <= 0) $P = $P + 2 * $y + 1; // Mid-point is outside // the perimeter else { $x--; $P = $P + 2 * $y - 2 * $x + 1; } // All the perimeter points // have already been printed if ($x < $y) break; // Printing the generated // point and its reflection // in the other octants // after translation echo \"(\",$x + $x_centre,\",\", $y + $y_centre,\")\"; echo \"(\",-$x + $x_centre,\",\", $y + $y_centre,\")\"; echo \"(\",$x +$x_centre,\",\", -$y + $y_centre,\")\"; echo \"(\",-$x + $x_centre,\",\", -$y + $y_centre,\")\",\"\\n\"; // If the generated point is // on the line x = y then // the perimeter points have // already been printed if ($x != $y) { echo \"(\",$y + $x_centre,\",\", $x + $y_centre,\")\"; echo \"(\",-$y + $x_centre,\",\", $x + $y_centre,\")\"; echo \"(\",$y + $x_centre,\",\", -$x + $y_centre,\")\"; echo \"(\",-$y + $x_centre,\",\", -$x + $y_centre,\")\",\"\\n\"; } }} // Driver code // To draw a circle of radius // 3 centered at (0, 0) midPointCircleDraw(0, 0, 3); // This code is contributed by nitin mittal.?>",
"e": 17303,
"s": 15165,
"text": null
},
{
"code": "<script>// javascript program for implementing// Mid-Point Circle Drawing Algorithm // Implementing Mid-Point Circle // Drawing Algorithm function midPointCircleDraw(x_centre , y_centre , r) { var x = r, y = 0; // Printing the initial point // on the axes after translation document.write(\"(\" + (x + x_centre) + \", \" + (y + y_centre) + \")\"); // When radius is zero only a single // point will be printed if (r > 0) { document.write(\"(\" + (x + x_centre) + \", \" + (-y + y_centre) + \")\"); document.write(\"(\" + (y + x_centre) + \", \" + (x + y_centre) + \")\"); document.write(\"(\" + (-y + x_centre) + \", \" + (x + y_centre) + \")<br/>\"); } // Initialising the value of P var P = 1 - r; while (x > y) { y++; // Mid-point is inside or on the perimeter if (P <= 0) P = P + 2 * y + 1; // Mid-point is outside the perimeter else { x--; P = P + 2 * y - 2 * x + 1; } // All the perimeter points have already // been printed if (x < y) break; // Printing the generated point and its // reflection in the other octants after // translation document.write(\"(\" + (x + x_centre) + \", \" + (y + y_centre) + \")\"); document.write(\"(\" + (-x + x_centre) + \", \" + (y + y_centre) + \")\"); document.write(\"(\" + (x + x_centre) + \", \" + (-y + y_centre) + \")\"); document.write(\"(\" + (-x + x_centre) + \", \" + (-y + y_centre) + \")<br/>\"); // If the generated point is on the // line x = y then the perimeter points // have already been printed if (x != y) { document.write(\"(\" + (y + x_centre) + \", \" + (x + y_centre) + \")\"); document.write(\"(\" + (-y + x_centre) + \", \" + (x + y_centre) + \")\"); document.write(\"(\" + (y + x_centre) + \", \" + (-x + y_centre) + \")\"); document.write(\"(\" + (-y + x_centre) + \", \" + (-x + y_centre) + \")<br/>\"); } } } // Driver code // To draw a circle of radius // 3 centered at (0, 0) midPointCircleDraw(0, 0, 3); // This code is contributed by umadevi9616</script>",
"e": 19691,
"s": 17303,
"text": null
},
{
"code": null,
"e": 19701,
"s": 19691,
"text": "Output: "
},
{
"code": null,
"e": 19825,
"s": 19701,
"text": "(3, 0) (3, 0) (0, 3) (0, 3)\n(3, 1) (-3, 1) (3, -1) (-3, -1)\n(1, 3) (-1, 3) (1, -3) (-1, -3)\n(2, 2) (-2, 2) (2, -2) (-2, -2)"
},
{
"code": null,
"e": 20513,
"s": 19825,
"text": "Time Complexity: O(x – y)Auxiliary Space: O(1) References : Midpoint Circle Algorithm Image References : Octants of a circle, Rasterised Circle, the other images were created for this article by the geekThanks Tuhina Singh and Teva Zanker for improving this article. This article is contributed by Nabaneet Roy. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 20526,
"s": 20513,
"text": "nitin mittal"
},
{
"code": null,
"e": 20541,
"s": 20526,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 20555,
"s": 20541,
"text": "siddharthx_07"
},
{
"code": null,
"e": 20571,
"s": 20555,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 20583,
"s": 20571,
"text": "umadevi9616"
},
{
"code": null,
"e": 20599,
"s": 20583,
"text": "simranarora5sos"
},
{
"code": null,
"e": 20614,
"s": 20599,
"text": "adnanirshad158"
},
{
"code": null,
"e": 20625,
"s": 20614,
"text": "tevazanker"
},
{
"code": null,
"e": 20643,
"s": 20625,
"text": "computer-graphics"
},
{
"code": null,
"e": 20654,
"s": 20643,
"text": "Algorithms"
},
{
"code": null,
"e": 20665,
"s": 20654,
"text": "Algorithms"
}
] |
How to check if the value is primitive or not in JavaScript ? | 31 Mar, 2021
In this article, we will know how to check if a value of primitive or not.
JavaScript provides six types of primitive values that include Number, String, Boolean, Undefined, Symbol, and BigInt. The size of primitive values is fixed, therefore JavaScript stores the primitive value in the call stack (Execution context).
When we access a primitive value, we manipulate the actual value stored in that variable. Thus, variables that are primitive are accessed by value. When we assign a variable that stores a primitive value to another, the value stored in the variable is created and copied into the new variable.
To check a value whether it is primitive or not we use the following approaches:
Approach 1: In this approach, we check the type of the value using the typeof operator. If the type of the value is ‘object’ or ‘function’ then the value is not primitive otherwise the value is primitive. But the typeof operator shows the null to be an “object” but actually, the null is a Primitive.
Example:
Javascript
let isPrimitive = (val) => { if(val === null){ console.log(true); return; } if(typeof val == "object" || typeof val == "function"){ console.log(false) }else{ console.log(true) }} isPrimitive(null)isPrimitive(12)isPrimitive(Number(12))isPrimitive("Hello world")isPrimitive(new String("Hello world"))isPrimitive(true)isPrimitive([])isPrimitive({})
Output:
true
true
true
true
false
true
false
false
Approach 2: In this approach, we pass the value inside Object() and check if the value is equal to Object(value). If the value is equal then the value is primitive otherwise not primitive.
Example:
Javascript
let isPrimitive = (val) => { if(val === Object(val)){ console.log(false) }else{ console.log(true) }} isPrimitive(null)isPrimitive(12)isPrimitive(Number(12))isPrimitive("Hello world")isPrimitive(new String("Hello world"))isPrimitive(true)isPrimitive([])isPrimitive({})
Output:
true
true
true
true
false
true
false
false
JavaScript-Methods
JavaScript-Questions
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Mar, 2021"
},
{
"code": null,
"e": 103,
"s": 28,
"text": "In this article, we will know how to check if a value of primitive or not."
},
{
"code": null,
"e": 348,
"s": 103,
"text": "JavaScript provides six types of primitive values that include Number, String, Boolean, Undefined, Symbol, and BigInt. The size of primitive values is fixed, therefore JavaScript stores the primitive value in the call stack (Execution context)."
},
{
"code": null,
"e": 642,
"s": 348,
"text": "When we access a primitive value, we manipulate the actual value stored in that variable. Thus, variables that are primitive are accessed by value. When we assign a variable that stores a primitive value to another, the value stored in the variable is created and copied into the new variable."
},
{
"code": null,
"e": 723,
"s": 642,
"text": "To check a value whether it is primitive or not we use the following approaches:"
},
{
"code": null,
"e": 1024,
"s": 723,
"text": "Approach 1: In this approach, we check the type of the value using the typeof operator. If the type of the value is ‘object’ or ‘function’ then the value is not primitive otherwise the value is primitive. But the typeof operator shows the null to be an “object” but actually, the null is a Primitive."
},
{
"code": null,
"e": 1033,
"s": 1024,
"text": "Example:"
},
{
"code": null,
"e": 1044,
"s": 1033,
"text": "Javascript"
},
{
"code": "let isPrimitive = (val) => { if(val === null){ console.log(true); return; } if(typeof val == \"object\" || typeof val == \"function\"){ console.log(false) }else{ console.log(true) }} isPrimitive(null)isPrimitive(12)isPrimitive(Number(12))isPrimitive(\"Hello world\")isPrimitive(new String(\"Hello world\"))isPrimitive(true)isPrimitive([])isPrimitive({})",
"e": 1422,
"s": 1044,
"text": null
},
{
"code": null,
"e": 1430,
"s": 1422,
"text": "Output:"
},
{
"code": null,
"e": 1473,
"s": 1430,
"text": "true\ntrue\ntrue\ntrue\nfalse\ntrue\nfalse\nfalse"
},
{
"code": null,
"e": 1662,
"s": 1473,
"text": "Approach 2: In this approach, we pass the value inside Object() and check if the value is equal to Object(value). If the value is equal then the value is primitive otherwise not primitive."
},
{
"code": null,
"e": 1671,
"s": 1662,
"text": "Example:"
},
{
"code": null,
"e": 1682,
"s": 1671,
"text": "Javascript"
},
{
"code": "let isPrimitive = (val) => { if(val === Object(val)){ console.log(false) }else{ console.log(true) }} isPrimitive(null)isPrimitive(12)isPrimitive(Number(12))isPrimitive(\"Hello world\")isPrimitive(new String(\"Hello world\"))isPrimitive(true)isPrimitive([])isPrimitive({})",
"e": 1966,
"s": 1682,
"text": null
},
{
"code": null,
"e": 1974,
"s": 1966,
"text": "Output:"
},
{
"code": null,
"e": 2017,
"s": 1974,
"text": "true\ntrue\ntrue\ntrue\nfalse\ntrue\nfalse\nfalse"
},
{
"code": null,
"e": 2036,
"s": 2017,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 2057,
"s": 2036,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 2068,
"s": 2057,
"text": "JavaScript"
},
{
"code": null,
"e": 2085,
"s": 2068,
"text": "Web Technologies"
},
{
"code": null,
"e": 2112,
"s": 2085,
"text": "Web technologies Questions"
}
] |
Difference Between byte, short, int and long Datatype in Java | 19 Jan, 2021
There are two types of data types namely primitive datatype/fundamental and non-primitive/derived datatype. The primitive data type is defined as local sets or default set of datatype already present while deriving a datatype or creating a set of datatype using them are known as derived data types such as an array, stack, queue, tries, etc. Let’s clear understanding of primitive data types before diving into differentiating the same.
There are eight different primitive data types in JAVA namely byte, short, int, long, float, double, boolean, and char. In primitive data type requires different amounts of memory and has some specific operations which can be performed over it. They include a total of eight data types as follows as named. Among these, the integer data types are byte, short, long, and int. The integer data types are used to store numeric values. In this article, we will discuss the difference between these four Integer data-types. JAVA does not support an unsigned version of these integer data types. The main basis of difference is size and range.
byte
char
boolean
intsignedunsigned
signed
unsigned
short
float
long
double
Now, in primitive datatype let’s differentiate byte, short, int, and long to get a better understanding of which is to be used as per the requirements as they possess different traits that play a vital role in the implementation part in any programming language.
byte datatype has a range from -128 to 127 and it requires very little memory (only 1 byte). It can be used in place of int where we are sure that the range will be very small. The compiler automatically promotes the byte variables to type int, if they are used in an expression and the value exceeds their range.short datatype is the variable range is more than byte but less than int and it also requires more memory than byte but less memory in comparison to int. The compiler automatically promotes the short variables to type int, if they are used in an expression and the value exceeds their range.int datatype is the most preferred type for numeric values.long datatype is less frequently used. It should only be used when the range of the numeric value is too high. It requires the most memory(8 bytes) in comparison to the other three data-types.
byte datatype has a range from -128 to 127 and it requires very little memory (only 1 byte). It can be used in place of int where we are sure that the range will be very small. The compiler automatically promotes the byte variables to type int, if they are used in an expression and the value exceeds their range.
short datatype is the variable range is more than byte but less than int and it also requires more memory than byte but less memory in comparison to int. The compiler automatically promotes the short variables to type int, if they are used in an expression and the value exceeds their range.
int datatype is the most preferred type for numeric values.
long datatype is less frequently used. It should only be used when the range of the numeric value is too high. It requires the most memory(8 bytes) in comparison to the other three data-types.
Conclusion:
The keyword used is ‘byte’.
The keyword used is ‘short’.
The keyword used is ‘int’.
The keyword used is ‘long’.
From above table it is evidently seen that-
If the range of the numeric value is less, and we want to save the memory we can use byte or short depending on the range of values.
While if there is a need for medium-range value then we can use the type int but when the range for the numeric values will be larger, then the long type variable must be used to hold the values.
Order in terms of range
long > int > short > byte
Order in terms of size
long> int > short> byte
Java-Data Types
Technical Scripter 2020
Difference Between
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Jan, 2021"
},
{
"code": null,
"e": 466,
"s": 28,
"text": "There are two types of data types namely primitive datatype/fundamental and non-primitive/derived datatype. The primitive data type is defined as local sets or default set of datatype already present while deriving a datatype or creating a set of datatype using them are known as derived data types such as an array, stack, queue, tries, etc. Let’s clear understanding of primitive data types before diving into differentiating the same."
},
{
"code": null,
"e": 1104,
"s": 466,
"text": "There are eight different primitive data types in JAVA namely byte, short, int, long, float, double, boolean, and char. In primitive data type requires different amounts of memory and has some specific operations which can be performed over it. They include a total of eight data types as follows as named. Among these, the integer data types are byte, short, long, and int. The integer data types are used to store numeric values. In this article, we will discuss the difference between these four Integer data-types. JAVA does not support an unsigned version of these integer data types. The main basis of difference is size and range."
},
{
"code": null,
"e": 1109,
"s": 1104,
"text": "byte"
},
{
"code": null,
"e": 1114,
"s": 1109,
"text": "char"
},
{
"code": null,
"e": 1122,
"s": 1114,
"text": "boolean"
},
{
"code": null,
"e": 1140,
"s": 1122,
"text": "intsignedunsigned"
},
{
"code": null,
"e": 1147,
"s": 1140,
"text": "signed"
},
{
"code": null,
"e": 1156,
"s": 1147,
"text": "unsigned"
},
{
"code": null,
"e": 1162,
"s": 1156,
"text": "short"
},
{
"code": null,
"e": 1168,
"s": 1162,
"text": "float"
},
{
"code": null,
"e": 1173,
"s": 1168,
"text": "long"
},
{
"code": null,
"e": 1180,
"s": 1173,
"text": "double"
},
{
"code": null,
"e": 1443,
"s": 1180,
"text": "Now, in primitive datatype let’s differentiate byte, short, int, and long to get a better understanding of which is to be used as per the requirements as they possess different traits that play a vital role in the implementation part in any programming language."
},
{
"code": null,
"e": 2300,
"s": 1443,
"text": "byte datatype has a range from -128 to 127 and it requires very little memory (only 1 byte). It can be used in place of int where we are sure that the range will be very small. The compiler automatically promotes the byte variables to type int, if they are used in an expression and the value exceeds their range.short datatype is the variable range is more than byte but less than int and it also requires more memory than byte but less memory in comparison to int. The compiler automatically promotes the short variables to type int, if they are used in an expression and the value exceeds their range.int datatype is the most preferred type for numeric values.long datatype is less frequently used. It should only be used when the range of the numeric value is too high. It requires the most memory(8 bytes) in comparison to the other three data-types."
},
{
"code": null,
"e": 2614,
"s": 2300,
"text": "byte datatype has a range from -128 to 127 and it requires very little memory (only 1 byte). It can be used in place of int where we are sure that the range will be very small. The compiler automatically promotes the byte variables to type int, if they are used in an expression and the value exceeds their range."
},
{
"code": null,
"e": 2907,
"s": 2614,
"text": "short datatype is the variable range is more than byte but less than int and it also requires more memory than byte but less memory in comparison to int. The compiler automatically promotes the short variables to type int, if they are used in an expression and the value exceeds their range."
},
{
"code": null,
"e": 2967,
"s": 2907,
"text": "int datatype is the most preferred type for numeric values."
},
{
"code": null,
"e": 3160,
"s": 2967,
"text": "long datatype is less frequently used. It should only be used when the range of the numeric value is too high. It requires the most memory(8 bytes) in comparison to the other three data-types."
},
{
"code": null,
"e": 3172,
"s": 3160,
"text": "Conclusion:"
},
{
"code": null,
"e": 3201,
"s": 3172,
"text": "The keyword used is ‘byte’."
},
{
"code": null,
"e": 3230,
"s": 3201,
"text": "The keyword used is ‘short’."
},
{
"code": null,
"e": 3257,
"s": 3230,
"text": "The keyword used is ‘int’."
},
{
"code": null,
"e": 3285,
"s": 3257,
"text": "The keyword used is ‘long’."
},
{
"code": null,
"e": 3329,
"s": 3285,
"text": "From above table it is evidently seen that-"
},
{
"code": null,
"e": 3463,
"s": 3329,
"text": " If the range of the numeric value is less, and we want to save the memory we can use byte or short depending on the range of values."
},
{
"code": null,
"e": 3659,
"s": 3463,
"text": "While if there is a need for medium-range value then we can use the type int but when the range for the numeric values will be larger, then the long type variable must be used to hold the values."
},
{
"code": null,
"e": 3683,
"s": 3659,
"text": "Order in terms of range"
},
{
"code": null,
"e": 3711,
"s": 3683,
"text": " long > int > short > byte"
},
{
"code": null,
"e": 3735,
"s": 3711,
"text": "Order in terms of size "
},
{
"code": null,
"e": 3759,
"s": 3735,
"text": "long> int > short> byte"
},
{
"code": null,
"e": 3775,
"s": 3759,
"text": "Java-Data Types"
},
{
"code": null,
"e": 3799,
"s": 3775,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3818,
"s": 3799,
"text": "Difference Between"
},
{
"code": null,
"e": 3823,
"s": 3818,
"text": "Java"
},
{
"code": null,
"e": 3842,
"s": 3823,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3847,
"s": 3842,
"text": "Java"
}
] |
Select an element or sub array by index from a Numpy Array | 29 Aug, 2020
The elements of a NumPy array are indexed just like normal arrays. The index of the first element will be 0 and the last element will be indexed n-1, where n is the total number of elements.
Each element of these ndarrays can be accessed using its index number.
Example: The following code shows how to access an element of a NumPy array.
Python3
import numpy as np # NumPy ArraynumpyArr = np.array([1, 2, 3, 4])print("numpyArr[0] =", numpyArr[0])print("numpyArr[-1] =", numpyArr[-1])
Output:
numpyArr[0] = 1
numpyArr[-1] = 4
In the first case, we accessed the first element of the array using its index number. In the second case we accessed the last element of the array by using negative indexes.
To get a sub-array, we pass a slice in place of the element index.
Syntax:
numpyArr[x:y]
Here x and y are the starting and last index of the required sub-array.
Example:
Python3
import numpy as np # NumPy ArraynumpyArr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) # the slice 3:6 is passed instead # of indexprint("Sub-Array=", numpyArr[3:6])
Output:
Sub-Array= [4 5 6]
A sub-array starting from the 3rd index up to the 6th index ( excluding the last the 6th index ) was selected. You can slice a sub-array starting from the first element by leaving the starting index blank.
Example: The following code selects a sub-array starting from the first element.
Python3
import numpy as np numpyArr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) # works same as 0:6print("Sub-Array=", numpyArr[:6])
Output:
Sub-Array= [1 2 3 4 5 6]
Similarly, leaving the left side of the colon blank will give you an array up to the last element.
Example: The following code selects a sub-array starting from a particular index up to the last index.
Python3
import numpy as np numpyArr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) # same as 3:9 or 3:n, where n is# the length of arrayprint("Sub-Array=", numpyArr[3:])
Output:
Sub-Array= [4 5 6 7 8 9]
Python numpy-Indexing
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Aug, 2020"
},
{
"code": null,
"e": 219,
"s": 28,
"text": "The elements of a NumPy array are indexed just like normal arrays. The index of the first element will be 0 and the last element will be indexed n-1, where n is the total number of elements."
},
{
"code": null,
"e": 290,
"s": 219,
"text": "Each element of these ndarrays can be accessed using its index number."
},
{
"code": null,
"e": 367,
"s": 290,
"text": "Example: The following code shows how to access an element of a NumPy array."
},
{
"code": null,
"e": 375,
"s": 367,
"text": "Python3"
},
{
"code": "import numpy as np # NumPy ArraynumpyArr = np.array([1, 2, 3, 4])print(\"numpyArr[0] =\", numpyArr[0])print(\"numpyArr[-1] =\", numpyArr[-1])",
"e": 514,
"s": 375,
"text": null
},
{
"code": null,
"e": 522,
"s": 514,
"text": "Output:"
},
{
"code": null,
"e": 556,
"s": 522,
"text": "numpyArr[0] = 1\nnumpyArr[-1] = 4\n"
},
{
"code": null,
"e": 730,
"s": 556,
"text": "In the first case, we accessed the first element of the array using its index number. In the second case we accessed the last element of the array by using negative indexes."
},
{
"code": null,
"e": 797,
"s": 730,
"text": "To get a sub-array, we pass a slice in place of the element index."
},
{
"code": null,
"e": 805,
"s": 797,
"text": "Syntax:"
},
{
"code": null,
"e": 820,
"s": 805,
"text": "numpyArr[x:y]\n"
},
{
"code": null,
"e": 892,
"s": 820,
"text": "Here x and y are the starting and last index of the required sub-array."
},
{
"code": null,
"e": 901,
"s": 892,
"text": "Example:"
},
{
"code": null,
"e": 909,
"s": 901,
"text": "Python3"
},
{
"code": "import numpy as np # NumPy ArraynumpyArr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) # the slice 3:6 is passed instead # of indexprint(\"Sub-Array=\", numpyArr[3:6])",
"e": 1071,
"s": 909,
"text": null
},
{
"code": null,
"e": 1079,
"s": 1071,
"text": "Output:"
},
{
"code": null,
"e": 1099,
"s": 1079,
"text": "Sub-Array= [4 5 6]\n"
},
{
"code": null,
"e": 1305,
"s": 1099,
"text": "A sub-array starting from the 3rd index up to the 6th index ( excluding the last the 6th index ) was selected. You can slice a sub-array starting from the first element by leaving the starting index blank."
},
{
"code": null,
"e": 1387,
"s": 1305,
"text": "Example: The following code selects a sub-array starting from the first element. "
},
{
"code": null,
"e": 1395,
"s": 1387,
"text": "Python3"
},
{
"code": "import numpy as np numpyArr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) # works same as 0:6print(\"Sub-Array=\", numpyArr[:6])",
"e": 1518,
"s": 1395,
"text": null
},
{
"code": null,
"e": 1526,
"s": 1518,
"text": "Output:"
},
{
"code": null,
"e": 1552,
"s": 1526,
"text": "Sub-Array= [1 2 3 4 5 6]\n"
},
{
"code": null,
"e": 1651,
"s": 1552,
"text": "Similarly, leaving the left side of the colon blank will give you an array up to the last element."
},
{
"code": null,
"e": 1754,
"s": 1651,
"text": "Example: The following code selects a sub-array starting from a particular index up to the last index."
},
{
"code": null,
"e": 1762,
"s": 1754,
"text": "Python3"
},
{
"code": "import numpy as np numpyArr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) # same as 3:9 or 3:n, where n is# the length of arrayprint(\"Sub-Array=\", numpyArr[3:])",
"e": 1919,
"s": 1762,
"text": null
},
{
"code": null,
"e": 1927,
"s": 1919,
"text": "Output:"
},
{
"code": null,
"e": 1953,
"s": 1927,
"text": "Sub-Array= [4 5 6 7 8 9]\n"
},
{
"code": null,
"e": 1975,
"s": 1953,
"text": "Python numpy-Indexing"
},
{
"code": null,
"e": 1988,
"s": 1975,
"text": "Python-numpy"
},
{
"code": null,
"e": 1995,
"s": 1988,
"text": "Python"
}
] |
get_object_or_404 method in Django Models | 29 Jun, 2021
Some functions are hard as well as boring to code each and every time. But Django users don’t have to worry about that because Django has some awesome built-in functions to make our work easy and enjoyable. Let’s discuss get_object_or_404() here.
This function calls the given model and get object from that if that object or model doesn’t exist it raise 404 error.
Suppose we want to fetch 3rd product from the product model then we can use:
Python3
# import get_object_or_404()from django.shortcuts import get_object_or_404 # defining viewdef product_view(request): #retrieving product (pk is primary key) product = get_object_or_404(Products, pk=3)
This is the advantage of Django if you hardcode that then you have to write this much line of code:
Python3
# import Http404from django.http import Http404 # defining viewdef product_view(request): # try except logic try: product = Products.objects.get(pk=1) except Products.DoesNotExist: raise Http404("Given query not found....")
QuerySet instance is used to filter data while fetching from the database. For example, we want to fetch only shoes then we can write:
queryset = Products.objects.filter(type='shoes')
get_object_or_404(queryset)
We can simplify above example by a single line:
get_object_or_404(Products, type='shoes')
saurabh1990aror
Django-models
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Jun, 2021"
},
{
"code": null,
"e": 275,
"s": 28,
"text": "Some functions are hard as well as boring to code each and every time. But Django users don’t have to worry about that because Django has some awesome built-in functions to make our work easy and enjoyable. Let’s discuss get_object_or_404() here."
},
{
"code": null,
"e": 394,
"s": 275,
"text": "This function calls the given model and get object from that if that object or model doesn’t exist it raise 404 error."
},
{
"code": null,
"e": 471,
"s": 394,
"text": "Suppose we want to fetch 3rd product from the product model then we can use:"
},
{
"code": null,
"e": 479,
"s": 471,
"text": "Python3"
},
{
"code": "# import get_object_or_404()from django.shortcuts import get_object_or_404 # defining viewdef product_view(request): #retrieving product (pk is primary key) product = get_object_or_404(Products, pk=3)",
"e": 687,
"s": 479,
"text": null
},
{
"code": null,
"e": 787,
"s": 687,
"text": "This is the advantage of Django if you hardcode that then you have to write this much line of code:"
},
{
"code": null,
"e": 795,
"s": 787,
"text": "Python3"
},
{
"code": "# import Http404from django.http import Http404 # defining viewdef product_view(request): # try except logic try: product = Products.objects.get(pk=1) except Products.DoesNotExist: raise Http404(\"Given query not found....\")",
"e": 1045,
"s": 795,
"text": null
},
{
"code": null,
"e": 1180,
"s": 1045,
"text": "QuerySet instance is used to filter data while fetching from the database. For example, we want to fetch only shoes then we can write:"
},
{
"code": null,
"e": 1257,
"s": 1180,
"text": "queryset = Products.objects.filter(type='shoes')\nget_object_or_404(queryset)"
},
{
"code": null,
"e": 1305,
"s": 1257,
"text": "We can simplify above example by a single line:"
},
{
"code": null,
"e": 1348,
"s": 1305,
"text": "get_object_or_404(Products, type='shoes') "
},
{
"code": null,
"e": 1364,
"s": 1348,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 1378,
"s": 1364,
"text": "Django-models"
},
{
"code": null,
"e": 1392,
"s": 1378,
"text": "Python Django"
},
{
"code": null,
"e": 1399,
"s": 1392,
"text": "Python"
}
] |
PHP Date and Time | 02 Dec, 2021
In this article, we will see how to get the date & time using the date() & time() function in PHP, we will also see the various formatting options available with these functions & understand their implementation through the examples.
Date and time are some of the most frequently used operations in PHP while executing SQL queries or designing a website etc. PHP serves us with predefined functions for these tasks. Some of the predefined functions in PHP for date and time are discussed below.
PHP date() Function: The PHP date() function converts timestamp to a more readable date and time format.
Why do we need the date() function?
The computer stores dates and times in a format called UNIX Timestamp, which measures time as a number of seconds since the beginning of the Unix epoch (midnight Greenwich Mean Time on January 1, 1970, i.e. January 1, 1970, 00:00:00 GMT ). Since this is an impractical format for humans to read, PHP converts timestamp to a format that is readable and more understandable to humans.
Syntax:
date(format, timestamp)
Explanation:
The format parameter in the date() function specifies the format of returned date and time.
The timestamp is an optional parameter, if it is not included then the current date and time will be used.
Example: The below program explains the usage of the date() function in PHP.
PHP
<?php echo "Today's date is :"; $today = date("d/m/Y"); echo $today;?>
Output:
Today's date is :05/12/2017
Formatting options available in date() function: The format parameter of the date() function is a string that can contain multiple characters allowing to generate the dates in various formats. Date-related formatting characters that are commonly used in the format string:
d: Represents day of the month; two digits with leading zeros (01 or 31).
D: Represents day of the week in the text as an abbreviation (Mon to Sun).
m: Represents month in numbers with leading zeros (01 or 12).
M: Represents month in text, abbreviated (Jan to Dec).
y: Represents year in two digits (08 or 14).
Y: Represents year in four digits (2008 or 2014).
The parts of the date can be separated by inserting other characters, like hyphens (-), dots (.), slashes (/), or spaces to add additional visual formatting.
Example: The below example explains the usage of the date() function in PHP.
PHP
<?php echo "Today's date in various formats:" . "\n"; echo date("d/m/Y") . "\n"; echo date("d-m-Y") . "\n"; echo date("d.m.Y") . "\n"; echo date("d.M.Y/D");?>
Output:
Today's date in various formats:
05/12/2017
05-12-2017
05.12.2017
05.Dec.2017/Tue
The following characters can be used along with the date() function to format the time string:
h: Represents hour in 12-hour format with leading zeros (01 to 12).
H: Represents hour in 24-hour format with leading zeros (00 to 23).
i: Represents minutes with leading zeros (00 to 59).
s: Represents seconds with leading zeros (00 to 59).
a: Represents lowercase antemeridian and post meridian (am or pm).
A: Represents uppercase antemeridian and post meridian (AM or PM).
Example: The below example explains the usage of the date() function in PHP.
PHP
<?php echo date("h:i:s") . "\n"; echo date("M,d,Y h:i:s A") . "\n"; echo date("h:i a");?>
Output:
03:04:17
Dec,05,2017 03:04:17 PM
03:04 pm
PHP time() Function: The time() function is used to get the current time as a Unix timestamp (the number of seconds since the beginning of the Unix epoch: January 1, 1970, 00:00:00 GMT).
The following characters can be used to format the time string:
h: Represents hour in 12-hour format with leading zeros (01 to 12).
H: Represents hour in 24-hour format with leading zeros (00 to 23).
i: Represents minutes with leading zeros (00 to 59).
s: Represents seconds with leading zeros (00 to 59).
a: Represents lowercase antemeridian and post meridian (am or pm).
A: Represents uppercase antemeridian and post meridian (AM or PM).
Example: The below example explains the usage of the time() function in PHP.
PHP
<?php $timestamp = time(); echo($timestamp); echo "\n"; echo(date("F d, Y h:i:s A", $timestamp));?>
Output:
1512486297
December 05, 2017 03:04:57 PM
PHP mktime() Function: The mktime() function is used to create the timestamp for a specific date and time. If no date and time are provided, the timestamp for the current date and time is returned.
Syntax:
mktime(hour, minute, second, month, day, year)
Example: The below example explains the usage of the mktime() function in PHP.
PHP
<?php echo mktime(23, 21, 50, 11, 25, 2017);?>
Output:
1511652110
The above code creates a time stamp for 25th Nov 2017,23 hrs 21mins 50secs.
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
Akanksha_Rai
bhaskargeeksforgeeks
PHP-function
PHP
Technical Scripter
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Dec, 2021"
},
{
"code": null,
"e": 262,
"s": 28,
"text": "In this article, we will see how to get the date & time using the date() & time() function in PHP, we will also see the various formatting options available with these functions & understand their implementation through the examples."
},
{
"code": null,
"e": 523,
"s": 262,
"text": "Date and time are some of the most frequently used operations in PHP while executing SQL queries or designing a website etc. PHP serves us with predefined functions for these tasks. Some of the predefined functions in PHP for date and time are discussed below."
},
{
"code": null,
"e": 629,
"s": 523,
"text": "PHP date() Function: The PHP date() function converts timestamp to a more readable date and time format."
},
{
"code": null,
"e": 666,
"s": 629,
"text": "Why do we need the date() function? "
},
{
"code": null,
"e": 1050,
"s": 666,
"text": "The computer stores dates and times in a format called UNIX Timestamp, which measures time as a number of seconds since the beginning of the Unix epoch (midnight Greenwich Mean Time on January 1, 1970, i.e. January 1, 1970, 00:00:00 GMT ). Since this is an impractical format for humans to read, PHP converts timestamp to a format that is readable and more understandable to humans. "
},
{
"code": null,
"e": 1058,
"s": 1050,
"text": "Syntax:"
},
{
"code": null,
"e": 1082,
"s": 1058,
"text": "date(format, timestamp)"
},
{
"code": null,
"e": 1095,
"s": 1082,
"text": "Explanation:"
},
{
"code": null,
"e": 1187,
"s": 1095,
"text": "The format parameter in the date() function specifies the format of returned date and time."
},
{
"code": null,
"e": 1294,
"s": 1187,
"text": "The timestamp is an optional parameter, if it is not included then the current date and time will be used."
},
{
"code": null,
"e": 1371,
"s": 1294,
"text": "Example: The below program explains the usage of the date() function in PHP."
},
{
"code": null,
"e": 1375,
"s": 1371,
"text": "PHP"
},
{
"code": "<?php echo \"Today's date is :\"; $today = date(\"d/m/Y\"); echo $today;?>",
"e": 1449,
"s": 1375,
"text": null
},
{
"code": null,
"e": 1457,
"s": 1449,
"text": "Output:"
},
{
"code": null,
"e": 1485,
"s": 1457,
"text": "Today's date is :05/12/2017"
},
{
"code": null,
"e": 1758,
"s": 1485,
"text": "Formatting options available in date() function: The format parameter of the date() function is a string that can contain multiple characters allowing to generate the dates in various formats. Date-related formatting characters that are commonly used in the format string:"
},
{
"code": null,
"e": 1832,
"s": 1758,
"text": "d: Represents day of the month; two digits with leading zeros (01 or 31)."
},
{
"code": null,
"e": 1907,
"s": 1832,
"text": "D: Represents day of the week in the text as an abbreviation (Mon to Sun)."
},
{
"code": null,
"e": 1969,
"s": 1907,
"text": "m: Represents month in numbers with leading zeros (01 or 12)."
},
{
"code": null,
"e": 2024,
"s": 1969,
"text": "M: Represents month in text, abbreviated (Jan to Dec)."
},
{
"code": null,
"e": 2069,
"s": 2024,
"text": "y: Represents year in two digits (08 or 14)."
},
{
"code": null,
"e": 2119,
"s": 2069,
"text": "Y: Represents year in four digits (2008 or 2014)."
},
{
"code": null,
"e": 2277,
"s": 2119,
"text": "The parts of the date can be separated by inserting other characters, like hyphens (-), dots (.), slashes (/), or spaces to add additional visual formatting."
},
{
"code": null,
"e": 2354,
"s": 2277,
"text": "Example: The below example explains the usage of the date() function in PHP."
},
{
"code": null,
"e": 2358,
"s": 2354,
"text": "PHP"
},
{
"code": "<?php echo \"Today's date in various formats:\" . \"\\n\"; echo date(\"d/m/Y\") . \"\\n\"; echo date(\"d-m-Y\") . \"\\n\"; echo date(\"d.m.Y\") . \"\\n\"; echo date(\"d.M.Y/D\");?>",
"e": 2522,
"s": 2358,
"text": null
},
{
"code": null,
"e": 2530,
"s": 2522,
"text": "Output:"
},
{
"code": null,
"e": 2612,
"s": 2530,
"text": "Today's date in various formats:\n05/12/2017\n05-12-2017\n05.12.2017\n05.Dec.2017/Tue"
},
{
"code": null,
"e": 2707,
"s": 2612,
"text": "The following characters can be used along with the date() function to format the time string:"
},
{
"code": null,
"e": 2775,
"s": 2707,
"text": "h: Represents hour in 12-hour format with leading zeros (01 to 12)."
},
{
"code": null,
"e": 2843,
"s": 2775,
"text": "H: Represents hour in 24-hour format with leading zeros (00 to 23)."
},
{
"code": null,
"e": 2896,
"s": 2843,
"text": "i: Represents minutes with leading zeros (00 to 59)."
},
{
"code": null,
"e": 2949,
"s": 2896,
"text": "s: Represents seconds with leading zeros (00 to 59)."
},
{
"code": null,
"e": 3016,
"s": 2949,
"text": "a: Represents lowercase antemeridian and post meridian (am or pm)."
},
{
"code": null,
"e": 3083,
"s": 3016,
"text": "A: Represents uppercase antemeridian and post meridian (AM or PM)."
},
{
"code": null,
"e": 3160,
"s": 3083,
"text": "Example: The below example explains the usage of the date() function in PHP."
},
{
"code": null,
"e": 3164,
"s": 3160,
"text": "PHP"
},
{
"code": "<?php echo date(\"h:i:s\") . \"\\n\"; echo date(\"M,d,Y h:i:s A\") . \"\\n\"; echo date(\"h:i a\");?>",
"e": 3257,
"s": 3164,
"text": null
},
{
"code": null,
"e": 3265,
"s": 3257,
"text": "Output:"
},
{
"code": null,
"e": 3307,
"s": 3265,
"text": "03:04:17\nDec,05,2017 03:04:17 PM\n03:04 pm"
},
{
"code": null,
"e": 3494,
"s": 3307,
"text": "PHP time() Function: The time() function is used to get the current time as a Unix timestamp (the number of seconds since the beginning of the Unix epoch: January 1, 1970, 00:00:00 GMT)."
},
{
"code": null,
"e": 3558,
"s": 3494,
"text": "The following characters can be used to format the time string:"
},
{
"code": null,
"e": 3626,
"s": 3558,
"text": "h: Represents hour in 12-hour format with leading zeros (01 to 12)."
},
{
"code": null,
"e": 3694,
"s": 3626,
"text": "H: Represents hour in 24-hour format with leading zeros (00 to 23)."
},
{
"code": null,
"e": 3747,
"s": 3694,
"text": "i: Represents minutes with leading zeros (00 to 59)."
},
{
"code": null,
"e": 3800,
"s": 3747,
"text": "s: Represents seconds with leading zeros (00 to 59)."
},
{
"code": null,
"e": 3867,
"s": 3800,
"text": "a: Represents lowercase antemeridian and post meridian (am or pm)."
},
{
"code": null,
"e": 3934,
"s": 3867,
"text": "A: Represents uppercase antemeridian and post meridian (AM or PM)."
},
{
"code": null,
"e": 4011,
"s": 3934,
"text": "Example: The below example explains the usage of the time() function in PHP."
},
{
"code": null,
"e": 4015,
"s": 4011,
"text": "PHP"
},
{
"code": "<?php $timestamp = time(); echo($timestamp); echo \"\\n\"; echo(date(\"F d, Y h:i:s A\", $timestamp));?>",
"e": 4119,
"s": 4015,
"text": null
},
{
"code": null,
"e": 4127,
"s": 4119,
"text": "Output:"
},
{
"code": null,
"e": 4168,
"s": 4127,
"text": "1512486297\nDecember 05, 2017 03:04:57 PM"
},
{
"code": null,
"e": 4366,
"s": 4168,
"text": "PHP mktime() Function: The mktime() function is used to create the timestamp for a specific date and time. If no date and time are provided, the timestamp for the current date and time is returned."
},
{
"code": null,
"e": 4374,
"s": 4366,
"text": "Syntax:"
},
{
"code": null,
"e": 4421,
"s": 4374,
"text": "mktime(hour, minute, second, month, day, year)"
},
{
"code": null,
"e": 4500,
"s": 4421,
"text": "Example: The below example explains the usage of the mktime() function in PHP."
},
{
"code": null,
"e": 4504,
"s": 4500,
"text": "PHP"
},
{
"code": "<?php echo mktime(23, 21, 50, 11, 25, 2017);?>",
"e": 4552,
"s": 4504,
"text": null
},
{
"code": null,
"e": 4560,
"s": 4552,
"text": "Output:"
},
{
"code": null,
"e": 4571,
"s": 4560,
"text": "1511652110"
},
{
"code": null,
"e": 4647,
"s": 4571,
"text": "The above code creates a time stamp for 25th Nov 2017,23 hrs 21mins 50secs."
},
{
"code": null,
"e": 4816,
"s": 4647,
"text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples."
},
{
"code": null,
"e": 4829,
"s": 4816,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 4850,
"s": 4829,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 4863,
"s": 4850,
"text": "PHP-function"
},
{
"code": null,
"e": 4867,
"s": 4863,
"text": "PHP"
},
{
"code": null,
"e": 4886,
"s": 4867,
"text": "Technical Scripter"
},
{
"code": null,
"e": 4903,
"s": 4886,
"text": "Web Technologies"
},
{
"code": null,
"e": 4907,
"s": 4903,
"text": "PHP"
}
] |
How to merge multiple DataFrames in R ? | 30 Apr, 2021
In this article, we will discuss how to merge multiple dataframes in R Programming Language. Dataframes can be merged both row and column wise, we can merge the columns by using cbind() function and rows by using rbind() function
cbind() is used to combine the dataframes by columns.
Syntax:
cbind(data1,data2,..............,data n)
Parameters:
where data1 and data 2 are the data frames.
Example 1:
R
# vector with student detailsnames1=c("sravan","bobby","ojaswi") # vector with marksmarks1=c(90,89,78) # pass these vectors to the # dataframe 1data1=data.frame(names1=names1,marks1=marks1)print(data1) # vector with student detailsnames2=c("gnanesh","rohith","divya") # vector with marksmarks2=c(68,99,79) # pass these vectors to the dataframe 2data2=data.frame(names2=names2,marks2=marks2)print(data2) print("-------------------------------\-------------------------------") # merging these two dataframes using cbindprint(cbind(data1,data2))
Output:
Example 2:
We can also merge specific columns in each dataframe by using $ operator we can access the dataframe column
Syntax:
dataframe_name$columnname
R
# vector with student detailsnames1=c("sravan","bobby","ojaswi") # vector with marksmarks1=c(90,89,78) # pass these vectors to the# dataframe 1data1=data.frame(names1=names1,marks1=marks1)print(data1) # vector with student detailsnames2=c("gnanesh","rohith","divya") # vector with marksmarks2=c(68,99,79) # pass these vectors to the dataframe 2data2=data.frame(names2=names2,marks2=marks2)print(data2) print("---------------------------------\-----------------------------") # merging these two data frames marks# column using cbindprint(cbind(data1$marks1,data2$marks2))
Output:
Example 3:
R
# vector with student detailsnames1=c("sravan","bobby","ojaswi") # vector with marksmarks1=c(90,89,78) # pass these vectors to the # dataframe 1data1=data.frame(names1=names1,marks1=marks1)print(data1) # vector with student detailsnames2=c("gnanesh","rohith","divya") # vector with marksmarks2=c(68,99,79) # pass these vectors to the dataframe 2data2=data.frame(names2=names2,marks2=marks2)print(data2) # vector with student detailsnames3=c("bhavya","harsha","navya") # vector with marksmarks3=c(68,99,79) # pass these vectors to the dataframe 3data3=data.frame(names3=names3,marks3=marks3)print(data3) print("-----------------------------------\---------------------------") # merging these three data framesprint(cbind(data1,data2,data3))
Output:
We can merge the rows between the dataframes using rbind() function.
Syntax:
rbind(dataframe1,dataframe2)
Example 1:
R
# create vectorsx=c(1,2,3,4,3,4,5)y=c(4,5,6,7,2,3,4) # pass these vectors to the # input of dataframe1(a)a=data.frame(x,y) # create vectorsx=c(10,20,30,40,50,60,70)y=c(40,50,60,40,50,60,70) # pass these vectors to the # input of dataframe1(a)b=data.frame(x,y) # apply rbind function to # merge rowsprint(rbind(a,b))
Output:
Example 2:
R
# create vectorsx=c(1,2,3,4,3,4,5)y=c(4,5,6,7,2,3,4) # pass these vectors to the # input of dataframe1(a)a=data.frame(x,y) # display dataframeprint(a)print("---------------------") # create vectorsx=c("sravan","bobby")y=c("Eswar","sai") # pass these vectors to the # input of dataframe1(a)b=data.frame(x,y) # display dataframeprint(b) # apply rbind function to merge rowsprint(rbind(a,b))
Output:
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
Loops in R (for, while, repeat)
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to change Row Names of DataFrame in R ?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
Remove rows with NA in one column of R DataFrame | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Apr, 2021"
},
{
"code": null,
"e": 258,
"s": 28,
"text": "In this article, we will discuss how to merge multiple dataframes in R Programming Language. Dataframes can be merged both row and column wise, we can merge the columns by using cbind() function and rows by using rbind() function"
},
{
"code": null,
"e": 312,
"s": 258,
"text": "cbind() is used to combine the dataframes by columns."
},
{
"code": null,
"e": 320,
"s": 312,
"text": "Syntax:"
},
{
"code": null,
"e": 361,
"s": 320,
"text": "cbind(data1,data2,..............,data n)"
},
{
"code": null,
"e": 373,
"s": 361,
"text": "Parameters:"
},
{
"code": null,
"e": 417,
"s": 373,
"text": "where data1 and data 2 are the data frames."
},
{
"code": null,
"e": 428,
"s": 417,
"text": "Example 1:"
},
{
"code": null,
"e": 430,
"s": 428,
"text": "R"
},
{
"code": "# vector with student detailsnames1=c(\"sravan\",\"bobby\",\"ojaswi\") # vector with marksmarks1=c(90,89,78) # pass these vectors to the # dataframe 1data1=data.frame(names1=names1,marks1=marks1)print(data1) # vector with student detailsnames2=c(\"gnanesh\",\"rohith\",\"divya\") # vector with marksmarks2=c(68,99,79) # pass these vectors to the dataframe 2data2=data.frame(names2=names2,marks2=marks2)print(data2) print(\"-------------------------------\\-------------------------------\") # merging these two dataframes using cbindprint(cbind(data1,data2))",
"e": 981,
"s": 430,
"text": null
},
{
"code": null,
"e": 989,
"s": 981,
"text": "Output:"
},
{
"code": null,
"e": 1000,
"s": 989,
"text": "Example 2:"
},
{
"code": null,
"e": 1108,
"s": 1000,
"text": "We can also merge specific columns in each dataframe by using $ operator we can access the dataframe column"
},
{
"code": null,
"e": 1116,
"s": 1108,
"text": "Syntax:"
},
{
"code": null,
"e": 1142,
"s": 1116,
"text": "dataframe_name$columnname"
},
{
"code": null,
"e": 1144,
"s": 1142,
"text": "R"
},
{
"code": "# vector with student detailsnames1=c(\"sravan\",\"bobby\",\"ojaswi\") # vector with marksmarks1=c(90,89,78) # pass these vectors to the# dataframe 1data1=data.frame(names1=names1,marks1=marks1)print(data1) # vector with student detailsnames2=c(\"gnanesh\",\"rohith\",\"divya\") # vector with marksmarks2=c(68,99,79) # pass these vectors to the dataframe 2data2=data.frame(names2=names2,marks2=marks2)print(data2) print(\"---------------------------------\\-----------------------------\") # merging these two data frames marks# column using cbindprint(cbind(data1$marks1,data2$marks2))",
"e": 1723,
"s": 1144,
"text": null
},
{
"code": null,
"e": 1731,
"s": 1723,
"text": "Output:"
},
{
"code": null,
"e": 1742,
"s": 1731,
"text": "Example 3:"
},
{
"code": null,
"e": 1744,
"s": 1742,
"text": "R"
},
{
"code": "# vector with student detailsnames1=c(\"sravan\",\"bobby\",\"ojaswi\") # vector with marksmarks1=c(90,89,78) # pass these vectors to the # dataframe 1data1=data.frame(names1=names1,marks1=marks1)print(data1) # vector with student detailsnames2=c(\"gnanesh\",\"rohith\",\"divya\") # vector with marksmarks2=c(68,99,79) # pass these vectors to the dataframe 2data2=data.frame(names2=names2,marks2=marks2)print(data2) # vector with student detailsnames3=c(\"bhavya\",\"harsha\",\"navya\") # vector with marksmarks3=c(68,99,79) # pass these vectors to the dataframe 3data3=data.frame(names3=names3,marks3=marks3)print(data3) print(\"-----------------------------------\\---------------------------\") # merging these three data framesprint(cbind(data1,data2,data3))",
"e": 2495,
"s": 1744,
"text": null
},
{
"code": null,
"e": 2503,
"s": 2495,
"text": "Output:"
},
{
"code": null,
"e": 2572,
"s": 2503,
"text": "We can merge the rows between the dataframes using rbind() function."
},
{
"code": null,
"e": 2580,
"s": 2572,
"text": "Syntax:"
},
{
"code": null,
"e": 2609,
"s": 2580,
"text": "rbind(dataframe1,dataframe2)"
},
{
"code": null,
"e": 2620,
"s": 2609,
"text": "Example 1:"
},
{
"code": null,
"e": 2622,
"s": 2620,
"text": "R"
},
{
"code": "# create vectorsx=c(1,2,3,4,3,4,5)y=c(4,5,6,7,2,3,4) # pass these vectors to the # input of dataframe1(a)a=data.frame(x,y) # create vectorsx=c(10,20,30,40,50,60,70)y=c(40,50,60,40,50,60,70) # pass these vectors to the # input of dataframe1(a)b=data.frame(x,y) # apply rbind function to # merge rowsprint(rbind(a,b))",
"e": 2942,
"s": 2622,
"text": null
},
{
"code": null,
"e": 2950,
"s": 2942,
"text": "Output:"
},
{
"code": null,
"e": 2961,
"s": 2950,
"text": "Example 2:"
},
{
"code": null,
"e": 2963,
"s": 2961,
"text": "R"
},
{
"code": "# create vectorsx=c(1,2,3,4,3,4,5)y=c(4,5,6,7,2,3,4) # pass these vectors to the # input of dataframe1(a)a=data.frame(x,y) # display dataframeprint(a)print(\"---------------------\") # create vectorsx=c(\"sravan\",\"bobby\")y=c(\"Eswar\",\"sai\") # pass these vectors to the # input of dataframe1(a)b=data.frame(x,y) # display dataframeprint(b) # apply rbind function to merge rowsprint(rbind(a,b))",
"e": 3358,
"s": 2963,
"text": null
},
{
"code": null,
"e": 3366,
"s": 3358,
"text": "Output:"
},
{
"code": null,
"e": 3373,
"s": 3366,
"text": "Picked"
},
{
"code": null,
"e": 3394,
"s": 3373,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 3406,
"s": 3394,
"text": "R-DataFrame"
},
{
"code": null,
"e": 3417,
"s": 3406,
"text": "R Language"
},
{
"code": null,
"e": 3428,
"s": 3417,
"text": "R Programs"
},
{
"code": null,
"e": 3526,
"s": 3428,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3578,
"s": 3526,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 3630,
"s": 3578,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 3662,
"s": 3630,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 3720,
"s": 3662,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 3755,
"s": 3720,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 3813,
"s": 3755,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 3857,
"s": 3813,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 3906,
"s": 3857,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 3949,
"s": 3906,
"text": "Replace Specific Characters in String in R"
}
] |
What is the meaning of spread operator (...) in Reactjs? | 23 Dec, 2020
The three dots syntax (...) is part of ES6 and not React itself and it’s used by two operators i.e. the Spread and Rest operators. The Spread operator lets you expand an iterable like an object, string, or array into its elements while the Rest operator does the inverse by reducing a set of elements into one array.
The spread operator is very useful when you want to make an exact copy of an existing array, you can use the spread operator to accomplish this quickly.
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
App.js:JavascriptJavascriptimport React, { Component } from 'react'; // Details is a component in same folderimport Details from './Details'; class App extends React.Component { render() { var person = { name: 'User', age: 22 }; return ( <div> {/* Details component which accepts props */} <Details {...person} title='Dear' /> </div> ); }} export default App;
App.js:
Javascript
import React, { Component } from 'react'; // Details is a component in same folderimport Details from './Details'; class App extends React.Component { render() { var person = { name: 'User', age: 22 }; return ( <div> {/* Details component which accepts props */} <Details {...person} title='Dear' /> </div> ); }} export default App;
Details.js (Details Component):JavascriptJavascriptimport React, { Component } from 'react'; class Details extends React.Component { render() { // To extract values in variables sent by parent component const { name, age } = { ...this.props }; return ( <div> <h3>Person Details: </h3> <ul> <li>name={this.props.title} {name}</li> <li>age={age}</li> </ul> </div> ); }} export default Details;
Details.js (Details Component):
Javascript
import React, { Component } from 'react'; class Details extends React.Component { render() { // To extract values in variables sent by parent component const { name, age } = { ...this.props }; return ( <div> <h3>Person Details: </h3> <ul> <li>name={this.props.title} {name}</li> <li>age={age}</li> </ul> </div> ); }} export default Details;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Picked
react-js
Technical Scripter 2020
JavaScript
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Dec, 2020"
},
{
"code": null,
"e": 371,
"s": 54,
"text": "The three dots syntax (...) is part of ES6 and not React itself and it’s used by two operators i.e. the Spread and Rest operators. The Spread operator lets you expand an iterable like an object, string, or array into its elements while the Rest operator does the inverse by reducing a set of elements into one array."
},
{
"code": null,
"e": 524,
"s": 371,
"text": "The spread operator is very useful when you want to make an exact copy of an existing array, you can use the spread operator to accomplish this quickly."
},
{
"code": null,
"e": 552,
"s": 524,
"text": "Creating React Application:"
},
{
"code": null,
"e": 647,
"s": 552,
"text": "Step 1: Create a React application using the following command:npx create-react-app foldername"
},
{
"code": null,
"e": 711,
"s": 647,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 743,
"s": 711,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 856,
"s": 743,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 956,
"s": 856,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 970,
"s": 956,
"text": "cd foldername"
},
{
"code": null,
"e": 1384,
"s": 970,
"text": "App.js:JavascriptJavascriptimport React, { Component } from 'react'; // Details is a component in same folderimport Details from './Details'; class App extends React.Component { render() { var person = { name: 'User', age: 22 }; return ( <div> {/* Details component which accepts props */} <Details {...person} title='Dear' /> </div> ); }} export default App;"
},
{
"code": null,
"e": 1392,
"s": 1384,
"text": "App.js:"
},
{
"code": null,
"e": 1403,
"s": 1392,
"text": "Javascript"
},
{
"code": "import React, { Component } from 'react'; // Details is a component in same folderimport Details from './Details'; class App extends React.Component { render() { var person = { name: 'User', age: 22 }; return ( <div> {/* Details component which accepts props */} <Details {...person} title='Dear' /> </div> ); }} export default App;",
"e": 1790,
"s": 1403,
"text": null
},
{
"code": null,
"e": 2247,
"s": 1790,
"text": "Details.js (Details Component):JavascriptJavascriptimport React, { Component } from 'react'; class Details extends React.Component { render() { // To extract values in variables sent by parent component const { name, age } = { ...this.props }; return ( <div> <h3>Person Details: </h3> <ul> <li>name={this.props.title} {name}</li> <li>age={age}</li> </ul> </div> ); }} export default Details;"
},
{
"code": null,
"e": 2279,
"s": 2247,
"text": "Details.js (Details Component):"
},
{
"code": null,
"e": 2290,
"s": 2279,
"text": "Javascript"
},
{
"code": "import React, { Component } from 'react'; class Details extends React.Component { render() { // To extract values in variables sent by parent component const { name, age } = { ...this.props }; return ( <div> <h3>Person Details: </h3> <ul> <li>name={this.props.title} {name}</li> <li>age={age}</li> </ul> </div> ); }} export default Details;",
"e": 2696,
"s": 2290,
"text": null
},
{
"code": null,
"e": 2809,
"s": 2696,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 2819,
"s": 2809,
"text": "npm start"
},
{
"code": null,
"e": 2826,
"s": 2819,
"text": "Picked"
},
{
"code": null,
"e": 2835,
"s": 2826,
"text": "react-js"
},
{
"code": null,
"e": 2859,
"s": 2835,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 2870,
"s": 2859,
"text": "JavaScript"
},
{
"code": null,
"e": 2889,
"s": 2870,
"text": "Technical Scripter"
}
] |
Connell Sequence | Practice | GeeksforGeeks | Connell Sequence is the sequence formed with the first odd number, i.e 1 as its first term. The subsequent terms of the sequence are made up of the first two even numbers, i.e 2 and 4, followed by the next three odd numbers, i.e 5, 7 and 9, followed by the next four even numbers, i.e 10, 12, 14 and 16 and so on ....
Given an integer n, generate the first n terms of the Connell Sequence.
Example 1:
Input: n = 6
Output: 1 2 4 5 7 9
Explaination: First one odd number. Then
two even numbers. Then three odd numbers.
Example 2:
Input: n = 2
Output: 1 2
Explaination: The sequence consists of first
odd number then one even number.
Your Task:
You do not need to read input or print anything. Your task is to complete the function connellSequence() which takes n as input parmeters and returns a list of integers containing the first n numbers of the Connell sequence.
Expected Time Complexity: O(n)
Expected Auxiliary Space: O(n)
Constraints:
1 ≤ n ≤ 105
0
vik10 months ago
vik
import mathclass Solution: def connellSequence(self, n): if n == 0: return 0 else: arr = [] for i in range(1,n+1): n = 2 * i - math.floor((1 + math.sqrt(8 * i - 7))/2) arr.append(n) return arr
0
Abhay Singh1 year ago
Abhay Singh
what is wrong with this code: #include<iostream>using namespace std;int main() {//code
int t=0;cin>>t;
while(t--){ int n=0; cin>>n; int m=0; int i=1;int s=1; while(m<=n) { for(int k=0;k<s;k++) {="" cout<<i<<"="" ";="" i+="2;" }="" i-="2;" s+="1;" m+="s;" i++;="" }="" cout<<m-s+1<<"="" "<<i;="" int="" h="n-(m-s+1);" while(h--)="" {="" cout<<i<<"="" ";="" i+="2;" }="" cout<<"\n";="" }="" return="" 0;="" }="" i="" m="" getting="" output="" limit="" exceeded="">
0
Geeky Geek2 years ago
Geeky Geek
0.1 sec solution using Vector of sets:Can also be done without storing each element of the sequence with just an equation. If you wanna know, do comment. I used vector of sets just for better presentation./* HINT: The problem is of the form of 1 odd, 2 even, 3 odd, 4 even ...Whatever n is given, we can find a number k such that 1+2+3..upto k is less than or equal to n. If the sum (k*(k+1)/2) is equal to n then there will be k sets of odd and even numbers, or else if (k*(k+1)/2) is lesser, then k+1 sets. Each set will have the same no. of elements as its index.*/#include<bits stdc++.h="">using namespace std;
int main() {int t; cin>>t; while(t--){ int n; cin>>n; vector<set<int> >v; set<int> s; set<int> ::iterator it; int k; for(int i=1;i<=(n+1)/2;i++){ if((i*(i+1))/2<=n) k=i; if((i*(i+1))/2>n) break; } if((k*(k+1))/2<n) k="k+1;" int="" count="0;" int="" j="0;" for(int="" i="1;i<=k;i++){" int="" p="i;" if(p%2!="0){" s.clear();="" while(p="">=1){ if(count+1>n) break; count++; s.insert(1+j); j=j+2; p=p-1; } v.push_back(s); } else{ s.clear(); while(p>=1){ if(count+1>n) break; else count++; s.insert(j); j=j+2; p--; }j=j-2; v.push_back(s);}}for(int i=0;i<v.size();i++){ for(it="v[i].begin();it!=v[i].end();++it){" cout<<*it<<"="" ";}}="" cout<<endl;}="" return="" 0;}="">
0
venkat2 years ago
venkat
for t in range(int(input())): n=int(input()) import math for i in range(1,n+1): x=2*i-math.floor((1+math.sqrt(8*i-7))/2) print(x,end=" ")what's wrong in this code.can anyone please help
0
Abhishek Pandey2 years ago
Abhishek Pandey
#include<iostream>using namespace std;int main() {int t;cin>>t;while(t--){ int n; cin>>n; int c=0,j=0,m=0; for(int i=1;i<=n;i++) { cout<<i+c<<" ";="" m++;="" if(c<j)="" {="" c++;="" continue;="" }="" else="" if(c="=j)" {="" c="j;" j="c+m;" m="0;" }="" }="" cout<<endl;="" }="" return="" 0;="" }="">
0
Marius Dragoi4 years ago
Marius Dragoi
When I run test case 100000 as "custom input" it works fine, but when I push SUBMIT I do not receive any answer:
Wrong Answer. !!!Wrong AnswerPossibly your code doesn't work correctly for multiple test-cases (TCs).The first test case where your code failed:
Input:100000
Its Correct output is:1 2 4 5 7 9 10 12 ........And Your Code's output is:Need Help ?
0
Mayank Bhandari4 years ago
Mayank Bhandari
https://ide.geeksforgeeks.o...
segmentation fault error. can anyone help?
0
Balaji Ijjapwar4 years ago
Balaji Ijjapwar
when i run the code with any custom input it gives correct answer ,but when i submitted the code it says wrong answer for input 6 expected output:1 2 4 5 7 11your output:1 2 4 5
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 629,
"s": 238,
"text": "Connell Sequence is the sequence formed with the first odd number, i.e 1 as its first term. The subsequent terms of the sequence are made up of the first two even numbers, i.e 2 and 4, followed by the next three odd numbers, i.e 5, 7 and 9, followed by the next four even numbers, i.e 10, 12, 14 and 16 and so on .... \nGiven an integer n, generate the first n terms of the Connell Sequence."
},
{
"code": null,
"e": 641,
"s": 629,
"text": "\nExample 1:"
},
{
"code": null,
"e": 758,
"s": 641,
"text": "Input: n = 6\nOutput: 1 2 4 5 7 9\nExplaination: First one odd number. Then \ntwo even numbers. Then three odd numbers."
},
{
"code": null,
"e": 771,
"s": 760,
"text": "Example 2:"
},
{
"code": null,
"e": 875,
"s": 771,
"text": "Input: n = 2\nOutput: 1 2\nExplaination: The sequence consists of first \nodd number then one even number."
},
{
"code": null,
"e": 1113,
"s": 877,
"text": "Your Task:\nYou do not need to read input or print anything. Your task is to complete the function connellSequence() which takes n as input parmeters and returns a list of integers containing the first n numbers of the Connell sequence."
},
{
"code": null,
"e": 1177,
"s": 1115,
"text": "Expected Time Complexity: O(n)\nExpected Auxiliary Space: O(n)"
},
{
"code": null,
"e": 1206,
"s": 1179,
"text": "Constraints:\n1 ≤ n ≤ 105 "
},
{
"code": null,
"e": 1208,
"s": 1206,
"text": "0"
},
{
"code": null,
"e": 1225,
"s": 1208,
"text": "vik10 months ago"
},
{
"code": null,
"e": 1229,
"s": 1225,
"text": "vik"
},
{
"code": null,
"e": 1513,
"s": 1229,
"text": "import mathclass Solution: def connellSequence(self, n): if n == 0: return 0 else: arr = [] for i in range(1,n+1): n = 2 * i - math.floor((1 + math.sqrt(8 * i - 7))/2) arr.append(n) return arr"
},
{
"code": null,
"e": 1515,
"s": 1513,
"text": "0"
},
{
"code": null,
"e": 1537,
"s": 1515,
"text": "Abhay Singh1 year ago"
},
{
"code": null,
"e": 1549,
"s": 1537,
"text": "Abhay Singh"
},
{
"code": null,
"e": 1636,
"s": 1549,
"text": "what is wrong with this code: #include<iostream>using namespace std;int main() {//code"
},
{
"code": null,
"e": 1652,
"s": 1636,
"text": "int t=0;cin>>t;"
},
{
"code": null,
"e": 2032,
"s": 1652,
"text": "while(t--){ int n=0; cin>>n; int m=0; int i=1;int s=1; while(m<=n) { for(int k=0;k<s;k++) {=\"\" cout<<i<<\"=\"\" \";=\"\" i+=\"2;\" }=\"\" i-=\"2;\" s+=\"1;\" m+=\"s;\" i++;=\"\" }=\"\" cout<<m-s+1<<\"=\"\" \"<<i;=\"\" int=\"\" h=\"n-(m-s+1);\" while(h--)=\"\" {=\"\" cout<<i<<\"=\"\" \";=\"\" i+=\"2;\" }=\"\" cout<<\"\\n\";=\"\" }=\"\" return=\"\" 0;=\"\" }=\"\" i=\"\" m=\"\" getting=\"\" output=\"\" limit=\"\" exceeded=\"\">"
},
{
"code": null,
"e": 2034,
"s": 2032,
"text": "0"
},
{
"code": null,
"e": 2056,
"s": 2034,
"text": "Geeky Geek2 years ago"
},
{
"code": null,
"e": 2067,
"s": 2056,
"text": "Geeky Geek"
},
{
"code": null,
"e": 2682,
"s": 2067,
"text": "0.1 sec solution using Vector of sets:Can also be done without storing each element of the sequence with just an equation. If you wanna know, do comment. I used vector of sets just for better presentation./* HINT: The problem is of the form of 1 odd, 2 even, 3 odd, 4 even ...Whatever n is given, we can find a number k such that 1+2+3..upto k is less than or equal to n. If the sum (k*(k+1)/2) is equal to n then there will be k sets of odd and even numbers, or else if (k*(k+1)/2) is lesser, then k+1 sets. Each set will have the same no. of elements as its index.*/#include<bits stdc++.h=\"\">using namespace std;"
},
{
"code": null,
"e": 3631,
"s": 2682,
"text": " int main() {int t; cin>>t; while(t--){ int n; cin>>n; vector<set<int> >v; set<int> s; set<int> ::iterator it; int k; for(int i=1;i<=(n+1)/2;i++){ if((i*(i+1))/2<=n) k=i; if((i*(i+1))/2>n) break; } if((k*(k+1))/2<n) k=\"k+1;\" int=\"\" count=\"0;\" int=\"\" j=\"0;\" for(int=\"\" i=\"1;i<=k;i++){\" int=\"\" p=\"i;\" if(p%2!=\"0){\" s.clear();=\"\" while(p=\"\">=1){ if(count+1>n) break; count++; s.insert(1+j); j=j+2; p=p-1; } v.push_back(s); } else{ s.clear(); while(p>=1){ if(count+1>n) break; else count++; s.insert(j); j=j+2; p--; }j=j-2; v.push_back(s);}}for(int i=0;i<v.size();i++){ for(it=\"v[i].begin();it!=v[i].end();++it){\" cout<<*it<<\"=\"\" \";}}=\"\" cout<<endl;}=\"\" return=\"\" 0;}=\"\">"
},
{
"code": null,
"e": 3633,
"s": 3631,
"text": "0"
},
{
"code": null,
"e": 3651,
"s": 3633,
"text": "venkat2 years ago"
},
{
"code": null,
"e": 3658,
"s": 3651,
"text": "venkat"
},
{
"code": null,
"e": 3867,
"s": 3658,
"text": "for t in range(int(input())): n=int(input()) import math for i in range(1,n+1): x=2*i-math.floor((1+math.sqrt(8*i-7))/2) print(x,end=\" \")what's wrong in this code.can anyone please help"
},
{
"code": null,
"e": 3869,
"s": 3867,
"text": "0"
},
{
"code": null,
"e": 3896,
"s": 3869,
"text": "Abhishek Pandey2 years ago"
},
{
"code": null,
"e": 3912,
"s": 3896,
"text": "Abhishek Pandey"
},
{
"code": null,
"e": 4225,
"s": 3912,
"text": "#include<iostream>using namespace std;int main() {int t;cin>>t;while(t--){ int n; cin>>n; int c=0,j=0,m=0; for(int i=1;i<=n;i++) { cout<<i+c<<\" \";=\"\" m++;=\"\" if(c<j)=\"\" {=\"\" c++;=\"\" continue;=\"\" }=\"\" else=\"\" if(c=\"=j)\" {=\"\" c=\"j;\" j=\"c+m;\" m=\"0;\" }=\"\" }=\"\" cout<<endl;=\"\" }=\"\" return=\"\" 0;=\"\" }=\"\">"
},
{
"code": null,
"e": 4227,
"s": 4225,
"text": "0"
},
{
"code": null,
"e": 4252,
"s": 4227,
"text": "Marius Dragoi4 years ago"
},
{
"code": null,
"e": 4266,
"s": 4252,
"text": "Marius Dragoi"
},
{
"code": null,
"e": 4379,
"s": 4266,
"text": "When I run test case 100000 as \"custom input\" it works fine, but when I push SUBMIT I do not receive any answer:"
},
{
"code": null,
"e": 4524,
"s": 4379,
"text": "Wrong Answer. !!!Wrong AnswerPossibly your code doesn't work correctly for multiple test-cases (TCs).The first test case where your code failed:"
},
{
"code": null,
"e": 4537,
"s": 4524,
"text": "Input:100000"
},
{
"code": null,
"e": 4623,
"s": 4537,
"text": "Its Correct output is:1 2 4 5 7 9 10 12 ........And Your Code's output is:Need Help ?"
},
{
"code": null,
"e": 4625,
"s": 4623,
"text": "0"
},
{
"code": null,
"e": 4652,
"s": 4625,
"text": "Mayank Bhandari4 years ago"
},
{
"code": null,
"e": 4668,
"s": 4652,
"text": "Mayank Bhandari"
},
{
"code": null,
"e": 4699,
"s": 4668,
"text": "https://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 4742,
"s": 4699,
"text": "segmentation fault error. can anyone help?"
},
{
"code": null,
"e": 4744,
"s": 4742,
"text": "0"
},
{
"code": null,
"e": 4771,
"s": 4744,
"text": "Balaji Ijjapwar4 years ago"
},
{
"code": null,
"e": 4787,
"s": 4771,
"text": "Balaji Ijjapwar"
},
{
"code": null,
"e": 4965,
"s": 4787,
"text": "when i run the code with any custom input it gives correct answer ,but when i submitted the code it says wrong answer for input 6 expected output:1 2 4 5 7 11your output:1 2 4 5"
},
{
"code": null,
"e": 5111,
"s": 4965,
"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": 5147,
"s": 5111,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5157,
"s": 5147,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5167,
"s": 5157,
"text": "\nContest\n"
},
{
"code": null,
"e": 5230,
"s": 5167,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5378,
"s": 5230,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 5586,
"s": 5378,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 5692,
"s": 5586,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Ceil The Floor | Practice | GeeksforGeeks | Given an unsorted array Arr[] of N integers and an integer X, find floor and ceiling of X in Arr[0..N-1].
Floor of X is the largest element which is smaller than or equal to X. Floor of X doesn’t exist if X is smaller than smallest element of Arr[].
Ceil of X is the smallest element which is greater than or equal to X. Ceil of X doesn’t exist if X is greater than greatest element of Arr[].
Example 1:
Input:
N = 8, X = 7
Arr[] = {5, 6, 8, 9, 6, 5, 5, 6}
Output: 6 8
Explanation:
Floor of 7 is 6 and ceil of 7
is 8.
Example 2:
Input:
N = 8, X = 10
Arr[] = {5, 6, 8, 9, 6, 5, 5, 6}
Output: 9 -1
Explanation:
Floor of 10 is 9 but ceil of 10 is not
possible.
Your Task:
You don't need to read input or print anything. Your task is to complete the function getFloorAndCeil() which takes the array of integers arr, n and x as parameters and returns a pair of integers denoting the answer. Return -1 if floor or ceil is not present.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints :
1 ≤ N ≤ 105
1 ≤ Arr[i], X ≤ 106
0
codewithshoaib191 month ago
Pair getFloorAndCeil(int[] arr, int n, int x) { // code here Arrays.sort(arr); int a=ceilOfANumber(arr,x); int b=floorOfANumber(arr,x); Pair p=new Pair(a,b); return p; } public static int ceilOfANumber(int[] arr, int x) { int s = 0; int n = arr.length; int e = n - 1; int res = -1; while (s <= e) { int mid = s + (e - s) / 2; if (arr[mid] == x) { return arr[mid]; } else if (arr[mid] < x) { res = arr[mid]; s = mid + 1; } else if (arr[mid] > x) { e = mid - 1; } } return res; } public static int floorOfANumber(int[] arr, int target) { int s = 0; int n = arr.length; int e = n - 1; int res = -1; while (s <= e) { int mid = s + (e - s) / 2; if (arr[mid] == target) { return arr[mid]; } else if (arr[mid] < target) { s = mid + 1; } else if (arr[mid] > target) { res = arr[mid]; e = mid - 1; } } return res; }
0
akash15100132 months ago
#User function Template for python3def getFloorAndCeil(arr, n, x): floor = -1 ceil = max(arr) F=False C=False i = 0 while(i<=n-1): if arr[i] <= x and arr[i] >= floor: floor = arr[i] F=True if arr[i] >= x and arr[i] <= ceil: ceil = arr[i] C=True i = i+1 if C == False: ceil = -1 if F == False: floor = -1 return (floor,ceil)
0
palshivanshpal2 months ago
Pair getFloorAndCeil(int[] arr, int n, int x) { Arrays.sort(arr); int f=-1,c=-1; for(int i=0;i<n;i++){ if(arr[i]<=x) f=arr[i]; if(arr[i]>=x){ c=arr[i]; break; } } Pair p1=new Pair(f,c); return p1; }
0
imabhishek022 months ago
Easy solution with bad time complexity:
pair<int, int> getFloorAndCeil(int arr[], int n, int x) {
int start=0;
int end=n-1;
int res=-1;
while(start<=end)
{
int mid=start +(end-start)/2;
if(arr[mid]==x)
{
res= arr[mid];
}
else if(arr[mid]<x)
{
res=arr[mid];
start=mid+1;
}else
{
end=mid-1;
}
}
int s=0;
int e=n-1;
int r=-1;
while(s<=e)
{
int m=s +(e-s)/2;
if(arr[m]==x)
{
r= arr[m];
}
else if(arr[m]<x)
{
s=m+1;
}else
{
r=arr[m];
e=m-1;
}
}
return {res,r};
}
0
hemantkrkrayla6 months ago
C++ solution
pair<int, int> getFloorAndCeil(int arr[], int n, int x) {
// code here
int ceil_of_x = 1e9;
int floor_of_x = -1e9;
for(int i=0;i<n;i++) {
if(arr[i] >= x) {
ceil_of_x = min(ceil_of_x,arr[i]);
}
if(arr[i] <= x) {
floor_of_x = max(floor_of_x,arr[i]);
}
}
if(ceil_of_x==1e9) {
ceil_of_x = -1;
}
if(floor_of_x==-1e9) {
floor_of_x = -1;
}
return make_pair(floor_of_x,ceil_of_x);
}
+1
badgujarsachin836 months ago
pair<int, int> getFloorAndCeil(int arr[], int n, int x) {
// code here
int f=-1;
int c=100000;
for(int i=0;i<n;i++){
if(arr[i]<=x){
f=max(arr[i],f);
}
if(arr[i]>=x){
c=min(arr[i],c);
}
}
if(c==100000){
c=-1;
}
return {f,c};
}
+1
gaurlakshya24267 months ago
c++ solution
pair<int, int> getFloorAndCeil(int arr[], int n, int x) {
int flor=-1;
int ceel=INT_MAX;
for(int i=0;i<n;i++){
if(arr[i]<=x){
flor=max(flor,arr[i]);
}
if(arr[i]>=x){
ceel=min(ceel,arr[i]);
}
}
if(ceel==INT_MAX) ceel=-1;
return {flor,ceel};
}
0
Kartik Verma10 months ago
Kartik Verma
https://uploads.disquscdn.c...
0
Sanjit Paul1 year ago
Sanjit Paul
Very easy Java solutionhttps://ide.geeksforgeeks.o...
-1
Rohit Yadav1 year ago
Rohit Yadav
def getFloorAndCeil(arr, n, x): # code here mn=[-1] mx=[] for i in range (n): if x >= arr[i]: mn.append(arr[i]) if x<= arr[i]: mx.append(arr[i]) if len(mx)==0: return max(mn),'-1' else: return max(mn) ,min(mx)
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 332,
"s": 226,
"text": "Given an unsorted array Arr[] of N integers and an integer X, find floor and ceiling of X in Arr[0..N-1]."
},
{
"code": null,
"e": 476,
"s": 332,
"text": "Floor of X is the largest element which is smaller than or equal to X. Floor of X doesn’t exist if X is smaller than smallest element of Arr[]."
},
{
"code": null,
"e": 619,
"s": 476,
"text": "Ceil of X is the smallest element which is greater than or equal to X. Ceil of X doesn’t exist if X is greater than greatest element of Arr[]."
},
{
"code": null,
"e": 630,
"s": 619,
"text": "Example 1:"
},
{
"code": null,
"e": 746,
"s": 630,
"text": "Input:\nN = 8, X = 7\nArr[] = {5, 6, 8, 9, 6, 5, 5, 6}\nOutput: 6 8\nExplanation:\nFloor of 7 is 6 and ceil of 7 \nis 8.\n"
},
{
"code": null,
"e": 757,
"s": 746,
"text": "Example 2:"
},
{
"code": null,
"e": 888,
"s": 757,
"text": "Input:\nN = 8, X = 10\nArr[] = {5, 6, 8, 9, 6, 5, 5, 6}\nOutput: 9 -1\nExplanation:\nFloor of 10 is 9 but ceil of 10 is not \npossible.\n"
},
{
"code": null,
"e": 1159,
"s": 888,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function getFloorAndCeil() which takes the array of integers arr, n and x as parameters and returns a pair of integers denoting the answer. Return -1 if floor or ceil is not present."
},
{
"code": null,
"e": 1221,
"s": 1159,
"text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1267,
"s": 1221,
"text": "Constraints :\n1 ≤ N ≤ 105\n1 ≤ Arr[i], X ≤ 106"
},
{
"code": null,
"e": 1271,
"s": 1269,
"text": "0"
},
{
"code": null,
"e": 1299,
"s": 1271,
"text": "codewithshoaib191 month ago"
},
{
"code": null,
"e": 2448,
"s": 1299,
"text": "Pair getFloorAndCeil(int[] arr, int n, int x) { // code here Arrays.sort(arr); int a=ceilOfANumber(arr,x); int b=floorOfANumber(arr,x); Pair p=new Pair(a,b); return p; } public static int ceilOfANumber(int[] arr, int x) { int s = 0; int n = arr.length; int e = n - 1; int res = -1; while (s <= e) { int mid = s + (e - s) / 2; if (arr[mid] == x) { return arr[mid]; } else if (arr[mid] < x) { res = arr[mid]; s = mid + 1; } else if (arr[mid] > x) { e = mid - 1; } } return res; } public static int floorOfANumber(int[] arr, int target) { int s = 0; int n = arr.length; int e = n - 1; int res = -1; while (s <= e) { int mid = s + (e - s) / 2; if (arr[mid] == target) { return arr[mid]; } else if (arr[mid] < target) { s = mid + 1; } else if (arr[mid] > target) { res = arr[mid]; e = mid - 1; } } return res; }"
},
{
"code": null,
"e": 2450,
"s": 2448,
"text": "0"
},
{
"code": null,
"e": 2475,
"s": 2450,
"text": "akash15100132 months ago"
},
{
"code": null,
"e": 2917,
"s": 2475,
"text": "#User function Template for python3def getFloorAndCeil(arr, n, x): floor = -1 ceil = max(arr) F=False C=False i = 0 while(i<=n-1): if arr[i] <= x and arr[i] >= floor: floor = arr[i] F=True if arr[i] >= x and arr[i] <= ceil: ceil = arr[i] C=True i = i+1 if C == False: ceil = -1 if F == False: floor = -1 return (floor,ceil)"
},
{
"code": null,
"e": 2919,
"s": 2917,
"text": "0"
},
{
"code": null,
"e": 2946,
"s": 2919,
"text": "palshivanshpal2 months ago"
},
{
"code": null,
"e": 3251,
"s": 2946,
"text": "Pair getFloorAndCeil(int[] arr, int n, int x) { Arrays.sort(arr); int f=-1,c=-1; for(int i=0;i<n;i++){ if(arr[i]<=x) f=arr[i]; if(arr[i]>=x){ c=arr[i]; break; } } Pair p1=new Pair(f,c); return p1; }"
},
{
"code": null,
"e": 3253,
"s": 3251,
"text": "0"
},
{
"code": null,
"e": 3278,
"s": 3253,
"text": "imabhishek022 months ago"
},
{
"code": null,
"e": 3318,
"s": 3278,
"text": "Easy solution with bad time complexity:"
},
{
"code": null,
"e": 4009,
"s": 3318,
"text": "pair<int, int> getFloorAndCeil(int arr[], int n, int x) {\n int start=0;\n int end=n-1;\n int res=-1;\n \n while(start<=end)\n {\n int mid=start +(end-start)/2;\n if(arr[mid]==x)\n {\n res= arr[mid];\n }\n else if(arr[mid]<x)\n {\n res=arr[mid];\n start=mid+1;\n }else\n {\n end=mid-1;\n }\n }\n int s=0;\n int e=n-1;\n int r=-1;\n \n while(s<=e)\n {\n int m=s +(e-s)/2;\n if(arr[m]==x)\n {\n r= arr[m];\n }\n else if(arr[m]<x)\n {\n \n s=m+1;\n }else\n {\n r=arr[m];\n e=m-1;\n }\n }\n return {res,r};\n}"
},
{
"code": null,
"e": 4011,
"s": 4009,
"text": "0"
},
{
"code": null,
"e": 4038,
"s": 4011,
"text": "hemantkrkrayla6 months ago"
},
{
"code": null,
"e": 4051,
"s": 4038,
"text": "C++ solution"
},
{
"code": null,
"e": 4543,
"s": 4051,
"text": "pair<int, int> getFloorAndCeil(int arr[], int n, int x) {\n // code here\n int ceil_of_x = 1e9;\n int floor_of_x = -1e9;\n for(int i=0;i<n;i++) {\n if(arr[i] >= x) {\n ceil_of_x = min(ceil_of_x,arr[i]);\n }\n if(arr[i] <= x) {\n floor_of_x = max(floor_of_x,arr[i]);\n }\n }\n if(ceil_of_x==1e9) {\n ceil_of_x = -1;\n }\n if(floor_of_x==-1e9) {\n floor_of_x = -1;\n }\n return make_pair(floor_of_x,ceil_of_x);\n \n}"
},
{
"code": null,
"e": 4546,
"s": 4543,
"text": "+1"
},
{
"code": null,
"e": 4575,
"s": 4546,
"text": "badgujarsachin836 months ago"
},
{
"code": null,
"e": 4897,
"s": 4575,
"text": "pair<int, int> getFloorAndCeil(int arr[], int n, int x) {\n // code here\n int f=-1;\n int c=100000;\n for(int i=0;i<n;i++){\n if(arr[i]<=x){\n f=max(arr[i],f);\n }\n if(arr[i]>=x){\n c=min(arr[i],c);\n }\n }\n if(c==100000){\n c=-1;\n }\n return {f,c};\n}"
},
{
"code": null,
"e": 4900,
"s": 4897,
"text": "+1"
},
{
"code": null,
"e": 4928,
"s": 4900,
"text": "gaurlakshya24267 months ago"
},
{
"code": null,
"e": 4941,
"s": 4928,
"text": "c++ solution"
},
{
"code": null,
"e": 5269,
"s": 4941,
"text": "pair<int, int> getFloorAndCeil(int arr[], int n, int x) {\n int flor=-1;\n int ceel=INT_MAX;\n for(int i=0;i<n;i++){\n if(arr[i]<=x){\n flor=max(flor,arr[i]);\n }\n if(arr[i]>=x){\n ceel=min(ceel,arr[i]);\n }\n }\n if(ceel==INT_MAX) ceel=-1;\n \n return {flor,ceel}; \n}"
},
{
"code": null,
"e": 5271,
"s": 5269,
"text": "0"
},
{
"code": null,
"e": 5297,
"s": 5271,
"text": "Kartik Verma10 months ago"
},
{
"code": null,
"e": 5310,
"s": 5297,
"text": "Kartik Verma"
},
{
"code": null,
"e": 5341,
"s": 5310,
"text": "https://uploads.disquscdn.c..."
},
{
"code": null,
"e": 5343,
"s": 5341,
"text": "0"
},
{
"code": null,
"e": 5365,
"s": 5343,
"text": "Sanjit Paul1 year ago"
},
{
"code": null,
"e": 5377,
"s": 5365,
"text": "Sanjit Paul"
},
{
"code": null,
"e": 5431,
"s": 5377,
"text": "Very easy Java solutionhttps://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 5434,
"s": 5431,
"text": "-1"
},
{
"code": null,
"e": 5456,
"s": 5434,
"text": "Rohit Yadav1 year ago"
},
{
"code": null,
"e": 5468,
"s": 5456,
"text": "Rohit Yadav"
},
{
"code": null,
"e": 5748,
"s": 5468,
"text": "def getFloorAndCeil(arr, n, x): # code here mn=[-1] mx=[] for i in range (n): if x >= arr[i]: mn.append(arr[i]) if x<= arr[i]: mx.append(arr[i]) if len(mx)==0: return max(mn),'-1' else: return max(mn) ,min(mx)"
},
{
"code": null,
"e": 5894,
"s": 5748,
"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": 5930,
"s": 5894,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5940,
"s": 5930,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5950,
"s": 5940,
"text": "\nContest\n"
},
{
"code": null,
"e": 6013,
"s": 5950,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6161,
"s": 6013,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 6369,
"s": 6161,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 6475,
"s": 6369,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Practical Pandas: Synthetic Store Sales Analysis | by Soner Yıldırım | Towards Data Science | I’m skipping the part where I mention the great features and dominance of Pandas in the field of data science.
This post is more like a practical guide that demonstrates how Pandas can be used in data analysis. I will also try to provide a semi-structured approach to a data analysis task.
I call it “synthetic” because the data will be created randomly. Let’s start with creating our store sales dataset.
import numpy as npimport pandas as pdstores = pd.Series(['A','B','C','D']*125).sample(500)cities = pd.Series(['Rome','Madrid','Houston']*200).sample(500). reset_index(drop = True)
We have created two random series of stores and cities using the sample function of Pandas. The sample size must be equal to or less than the size of the original series. That is the reason we extended the lists by multiplying with constants.
It is time to put them together in a dataframe along with dates and sales.
df = pd.DataFrame({'day':np.random.randint(1,30, size=500), 'month':np.random.randint(1,12, size=500),'year':2020,'store':stores,'city':cities,'product1':np.random.randint(50, size=500),'product2':np.random.randint(40, size=500),'product3':np.random.randint(30, size=500)})df.head()
The sale quantities of 3 products are listed based on store-city-date combinations. It is better to also have a “date” column by combining separate day, month, and year. We will locate the new “date” column right after the “year” column which can be done with the insert function.
df.insert(3, 'date', pd.to_datetime(df[['day','month','year']]))df.head()
The first parameter of the index function indicates the location of the new column.
Note: Since we randomly generate the data, it can result in a date of February 30th which does not exist. In that case, the to_datetime function will raise an error saying that “day is out of bound for the month”. You can either limit your days at 29 or re-run the random functions.
We now have our synthetic data. One way to start the analysis is to check if there is any seasonality in sales quantities. We can use the groupby function to group sales by month and then plot the result.
df[['month','product1','product2','product3']].groupby('month')\.mean().plot(figsize=(10,6), fontsize=12, title='Monthly Sales of Products')
The product 1 and 2 seem to have a seasonality whereas product 3 is more stable. We have checked the sales in terms of monthly averages.
The sale quantities at different store-city combinations may provide valuable insight which can be achieved by the groupby function as well. Instead of plotting the results, we will use the Style property of pandas to make the results more appealing than plain numbers.
df[['store','city','product1','product2','product3']]\.groupby(['store','city'])\.mean().style.highlight_max(color='lightgreen', axis=0)\.highlight_min(color='orange', axis=0)
In addition to store-city average sales, the minimum and maximum values in each column are highlighted. It is definitely more appealing to use in reports than plain numbers.
There are other styling options available. Let’s do another one.
df[['store','city','product1','product2','product3']]\.groupby(['store','city'])\.mean().style.bar(color='lightgreen')
The sizes of the bars are proportional to the values in the column.
The original dataset had “day”, “month”, and “year” as separate columns. We combined them into a “date” column with an appropriate data type.
In a typical analysis, we are likely to have lots of columns so it is a good practice to eliminate redundant or repetitive ones. Thus, we can drop “day”, “month”, and “year” columns since the data provided by them is store in the “date” column.
df.drop(['day','month','year'], axis=1, inplace=True)df.head()
We have used the “month” column in our analysis. We can still use the individual parts of the dates by using the dt accessor.
df['date'].dt.month[:5]0 8 1 11 2 8 3 4 4 11
In the beginning, we checked the monthly averages of sales quantities. The monthly averages may not be detailed enough in some cases. Pandas is highly flexible in terms of selecting the frequency.
The following code will plot 10-day sales averages of product1.
df[['date','product1']].groupby('date').mean()\.resample('10D').mean().plot(figsize=(10,6), fontsize=12,title="10-Day Average Sales")
We first grouped the sales by date which gives us the daily averages. Then resample function is used to downsample dates to 10-day periods. The mean applied to take the average of 10-day periods. Finally, the results are plotted.
We can also create density plots with Pandas. For instance, we can use the kde function to plot density distributions of the sale quantities. KDE (kernel density estimation) is a non-parametric way to estimate the probability density function (PDF) of a random variable.
subset = df[['store','city','product1','product2','product3']]subset.plot.kde(figsize=(12,6), alpha=1, fontsize=12)
Please note that KDE is an estimation, not the actual probability distribution. This is the reason why we see negative values in the plots.
Let’s get our analysis a little more specific. For instance, you may want to see the largest increase or decrease between the average sales in two consecutive days. As an example, we will check in store A.
df[df.store == 'A'].groupby('date').mean()
These are the daily averages of sales quantities in store A. The diff function returns the differences between two consecutive rows.
df[df.store == 'A']\.groupby('date').mean().diff().sort_values(by='product1')[:5]
We have sorted the values in ascending order by product1 to see the largest decreases in the sale quantities of product1. The sale quantity of product1 was decreased by 37 on 2020–10–28 compared to the previous day.
Similarly, we can find the largest increases in product2.
df[df.store == 'A'].groupby('date').mean().diff().\sort_values(by='product2', ascending=False)[:5]
We have covered some techniques that can be used in a typical data analysis task. Pandas' capabilities extend far beyond the techniques discussed here. You will discover more as you need to complete the tasks.
Thank you for reading. Please let me know if you have any feedback. | [
{
"code": null,
"e": 283,
"s": 172,
"text": "I’m skipping the part where I mention the great features and dominance of Pandas in the field of data science."
},
{
"code": null,
"e": 462,
"s": 283,
"text": "This post is more like a practical guide that demonstrates how Pandas can be used in data analysis. I will also try to provide a semi-structured approach to a data analysis task."
},
{
"code": null,
"e": 578,
"s": 462,
"text": "I call it “synthetic” because the data will be created randomly. Let’s start with creating our store sales dataset."
},
{
"code": null,
"e": 758,
"s": 578,
"text": "import numpy as npimport pandas as pdstores = pd.Series(['A','B','C','D']*125).sample(500)cities = pd.Series(['Rome','Madrid','Houston']*200).sample(500). reset_index(drop = True)"
},
{
"code": null,
"e": 1001,
"s": 758,
"text": "We have created two random series of stores and cities using the sample function of Pandas. The sample size must be equal to or less than the size of the original series. That is the reason we extended the lists by multiplying with constants."
},
{
"code": null,
"e": 1076,
"s": 1001,
"text": "It is time to put them together in a dataframe along with dates and sales."
},
{
"code": null,
"e": 1362,
"s": 1076,
"text": "df = pd.DataFrame({'day':np.random.randint(1,30, size=500), 'month':np.random.randint(1,12, size=500),'year':2020,'store':stores,'city':cities,'product1':np.random.randint(50, size=500),'product2':np.random.randint(40, size=500),'product3':np.random.randint(30, size=500)})df.head()"
},
{
"code": null,
"e": 1643,
"s": 1362,
"text": "The sale quantities of 3 products are listed based on store-city-date combinations. It is better to also have a “date” column by combining separate day, month, and year. We will locate the new “date” column right after the “year” column which can be done with the insert function."
},
{
"code": null,
"e": 1717,
"s": 1643,
"text": "df.insert(3, 'date', pd.to_datetime(df[['day','month','year']]))df.head()"
},
{
"code": null,
"e": 1801,
"s": 1717,
"text": "The first parameter of the index function indicates the location of the new column."
},
{
"code": null,
"e": 2084,
"s": 1801,
"text": "Note: Since we randomly generate the data, it can result in a date of February 30th which does not exist. In that case, the to_datetime function will raise an error saying that “day is out of bound for the month”. You can either limit your days at 29 or re-run the random functions."
},
{
"code": null,
"e": 2289,
"s": 2084,
"text": "We now have our synthetic data. One way to start the analysis is to check if there is any seasonality in sales quantities. We can use the groupby function to group sales by month and then plot the result."
},
{
"code": null,
"e": 2430,
"s": 2289,
"text": "df[['month','product1','product2','product3']].groupby('month')\\.mean().plot(figsize=(10,6), fontsize=12, title='Monthly Sales of Products')"
},
{
"code": null,
"e": 2567,
"s": 2430,
"text": "The product 1 and 2 seem to have a seasonality whereas product 3 is more stable. We have checked the sales in terms of monthly averages."
},
{
"code": null,
"e": 2837,
"s": 2567,
"text": "The sale quantities at different store-city combinations may provide valuable insight which can be achieved by the groupby function as well. Instead of plotting the results, we will use the Style property of pandas to make the results more appealing than plain numbers."
},
{
"code": null,
"e": 3013,
"s": 2837,
"text": "df[['store','city','product1','product2','product3']]\\.groupby(['store','city'])\\.mean().style.highlight_max(color='lightgreen', axis=0)\\.highlight_min(color='orange', axis=0)"
},
{
"code": null,
"e": 3187,
"s": 3013,
"text": "In addition to store-city average sales, the minimum and maximum values in each column are highlighted. It is definitely more appealing to use in reports than plain numbers."
},
{
"code": null,
"e": 3252,
"s": 3187,
"text": "There are other styling options available. Let’s do another one."
},
{
"code": null,
"e": 3371,
"s": 3252,
"text": "df[['store','city','product1','product2','product3']]\\.groupby(['store','city'])\\.mean().style.bar(color='lightgreen')"
},
{
"code": null,
"e": 3439,
"s": 3371,
"text": "The sizes of the bars are proportional to the values in the column."
},
{
"code": null,
"e": 3581,
"s": 3439,
"text": "The original dataset had “day”, “month”, and “year” as separate columns. We combined them into a “date” column with an appropriate data type."
},
{
"code": null,
"e": 3826,
"s": 3581,
"text": "In a typical analysis, we are likely to have lots of columns so it is a good practice to eliminate redundant or repetitive ones. Thus, we can drop “day”, “month”, and “year” columns since the data provided by them is store in the “date” column."
},
{
"code": null,
"e": 3889,
"s": 3826,
"text": "df.drop(['day','month','year'], axis=1, inplace=True)df.head()"
},
{
"code": null,
"e": 4015,
"s": 3889,
"text": "We have used the “month” column in our analysis. We can still use the individual parts of the dates by using the dt accessor."
},
{
"code": null,
"e": 4078,
"s": 4015,
"text": "df['date'].dt.month[:5]0 8 1 11 2 8 3 4 4 11"
},
{
"code": null,
"e": 4275,
"s": 4078,
"text": "In the beginning, we checked the monthly averages of sales quantities. The monthly averages may not be detailed enough in some cases. Pandas is highly flexible in terms of selecting the frequency."
},
{
"code": null,
"e": 4339,
"s": 4275,
"text": "The following code will plot 10-day sales averages of product1."
},
{
"code": null,
"e": 4473,
"s": 4339,
"text": "df[['date','product1']].groupby('date').mean()\\.resample('10D').mean().plot(figsize=(10,6), fontsize=12,title=\"10-Day Average Sales\")"
},
{
"code": null,
"e": 4703,
"s": 4473,
"text": "We first grouped the sales by date which gives us the daily averages. Then resample function is used to downsample dates to 10-day periods. The mean applied to take the average of 10-day periods. Finally, the results are plotted."
},
{
"code": null,
"e": 4974,
"s": 4703,
"text": "We can also create density plots with Pandas. For instance, we can use the kde function to plot density distributions of the sale quantities. KDE (kernel density estimation) is a non-parametric way to estimate the probability density function (PDF) of a random variable."
},
{
"code": null,
"e": 5090,
"s": 4974,
"text": "subset = df[['store','city','product1','product2','product3']]subset.plot.kde(figsize=(12,6), alpha=1, fontsize=12)"
},
{
"code": null,
"e": 5230,
"s": 5090,
"text": "Please note that KDE is an estimation, not the actual probability distribution. This is the reason why we see negative values in the plots."
},
{
"code": null,
"e": 5436,
"s": 5230,
"text": "Let’s get our analysis a little more specific. For instance, you may want to see the largest increase or decrease between the average sales in two consecutive days. As an example, we will check in store A."
},
{
"code": null,
"e": 5479,
"s": 5436,
"text": "df[df.store == 'A'].groupby('date').mean()"
},
{
"code": null,
"e": 5612,
"s": 5479,
"text": "These are the daily averages of sales quantities in store A. The diff function returns the differences between two consecutive rows."
},
{
"code": null,
"e": 5694,
"s": 5612,
"text": "df[df.store == 'A']\\.groupby('date').mean().diff().sort_values(by='product1')[:5]"
},
{
"code": null,
"e": 5910,
"s": 5694,
"text": "We have sorted the values in ascending order by product1 to see the largest decreases in the sale quantities of product1. The sale quantity of product1 was decreased by 37 on 2020–10–28 compared to the previous day."
},
{
"code": null,
"e": 5968,
"s": 5910,
"text": "Similarly, we can find the largest increases in product2."
},
{
"code": null,
"e": 6067,
"s": 5968,
"text": "df[df.store == 'A'].groupby('date').mean().diff().\\sort_values(by='product2', ascending=False)[:5]"
},
{
"code": null,
"e": 6277,
"s": 6067,
"text": "We have covered some techniques that can be used in a typical data analysis task. Pandas' capabilities extend far beyond the techniques discussed here. You will discover more as you need to complete the tasks."
}
] |
Code in Java, Execute as C++.. How To Call Java Method From C++ Using... | by Dwi Prasetyo Adi Nugroho | Towards Data Science | Java and C++ remain two of the most popular programming languages. The two languages have different designs and characteristics. Depending on the problem, one might work better than the other. However, at some point, we need to integrate these languages, e.g. calling a method written in Java to your C++ code. The need to integrate Java and C++ is not something new. In fact, we can find a tutorial dated back to 1996. Since then, the two languages have developed remarkably.
In this tutorial, we are going to learn how to call a java method from a C++ using GraalVM native image. If this is the first time you heard about GraalVM, you might be interested in checking out their homepage. GraalVM is a virtual machine that you can use to run a Java application. It’s based on JVM, but with additional features such as ahead of time compilation, fewer memory footprints, and other advanced optimizations. Additionally, GraalVM provides a native image plugin that you can use to compile a Java application to a native application. That means your application can run without requiring a JVM installed and running. Interestingly, you can also use this native image plugin to compile your Java application into a shared library and load it from your C++ code. This comes very handily when you code mainly written in C++ but you want to use an existing Java library on some part of it.
Before diving into the tutorial, let’s have a look at how this thing works. Basically, what you will do are the following:
Write your method in Java.Compile the Java code to C++ shared library (yourlib.so) and header (yourlib.h) file using GraalVM.Load the library and header to your C++ project.
Write your method in Java.
Compile the Java code to C++ shared library (yourlib.so) and header (yourlib.h) file using GraalVM.
Load the library and header to your C++ project.
In this example, we will simulate a use case where you want to use a function from a third-party Java library on your C++ project. Particularly, we are interested to use one of the math functions from Google’s Guava library.
First, we need to set up a maven project for our java method. Building our project in maven helps us to import the dependencies as well as utilizing the GraalVM native image plugin to create the shared library. Once the project is created, add the dependencies to Guava library (or any library that you need) and the GraalVM library to your pom.xml file:
<dependencies> <!-- https://mvnrepository.com/artifact/org.graalvm.nativeimage/svm --> <dependency> <groupId>org.graalvm.nativeimage</groupId> <artifactId>svm</artifactId> <version>19.3.1</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>28.2-jre</version> </dependency></dependencies>
Next, add the following plugin to build your java code to C++ shared library:
<build> <finalName>libmymath</finalName> <plugins> <plugin> <groupId>com.oracle.substratevm</groupId> <artifactId>native-image-maven-plugin</artifactId> <version>20.0.0</version> <executions> <execution> <goals> <goal>native-image</goal> </goals> <phase>package</phase> </execution> </executions> <configuration> <buildArgs>--shared -H:Name=libmymath</buildArgs> </configuration> </plugin> </plugins></build>
Let’s have a look at the bold parts. On the <finalName> tag, put a name that you want as the name of your library. Note the version that you specify on the <version> tag as you will need it later. On the <buildArgs>, we specify the shared and name parameter to instruct the GraalVM native image to create a shared library instead of a native executable. Put the same name as finalName on the Name parameter.
Now let’s prepare our Java method. Given an integer input x, we are interested to calculate the nearest power of 2 greater x. For example, if x is 14 it will return 16, as 16 is the nearest power of 2 greater than 14. Below is the snippet of our function. Note that we need to put an additional first parameter thread of type IsolateThread to bridge our Java and C++ execution. This parameter has to be in the first position. We also need to specify the name of the method in the CEntryPoint annotation. This is the method name that we will refer to in our C++ code. You can check the complete java project in this repository.
import com.google.common.math.IntMath;import org.graalvm.nativeimage.IsolateThread;import org.graalvm.nativeimage.c.function.CEntryPoint;public class MyMath { @CEntryPoint (name = "ceilingPowerOfTwo") public static int ceilingPowerOfTwo(IsolateThread thread, int x) { return IntMath.ceilingPowerOfTwo(x); }}
Having our project set, we now need to run mvn package to compile our Java method to a shared library. However, as this functionality only available on GraalVM, we will need to set up the GraalVM and point our JAVA_HOME to the GraalVM binary. Therefore, you will need to do the following:
Download GraalVM. Make sure you pick the correct architecture, java version, and the GraalVM version that you specify in the pom.xml. Specifically, this example project uses GraalVM 20.0.0 for Java 8.Install the native-image extension by using the gu binary. In a Unix environment, you can do that using: <path_to_graalvm_directory>graalvm-ce-java8–20.0.0 2bin/gu install native-imageUpdate JAVA_HOME to point to the downloaded GraalVM directory. In a Unix environment, you can use export JAVA_HOME=<path_to_graalvm_directory/graalvm-ce-java8–20.0.0 2/>.
Download GraalVM. Make sure you pick the correct architecture, java version, and the GraalVM version that you specify in the pom.xml. Specifically, this example project uses GraalVM 20.0.0 for Java 8.
Install the native-image extension by using the gu binary. In a Unix environment, you can do that using: <path_to_graalvm_directory>graalvm-ce-java8–20.0.0 2bin/gu install native-image
Update JAVA_HOME to point to the downloaded GraalVM directory. In a Unix environment, you can use export JAVA_HOME=<path_to_graalvm_directory/graalvm-ce-java8–20.0.0 2/>.
Now you can call the mvn package install to build the shared library. It will generate several files: graal_isolate.h, graal_isolate_dynamic.h, libmymath.h, libmymath_dynamic.h, and libmymath.so (or in other formats in other OS). Aside from our own library, it will also generate Graal VM C++ libraries.
Let’s now use our shared library in the following simple C++ project. Put the generated file inside the directory of this C++ project. For example, you can create an include folder and put these files inside this folder.
#include <iostream>#include <libmymath.h>int main() { graal_isolate_t *isolate = NULL; graal_isolatethread_t *thread = NULL; if (graal_create_isolate(NULL, &isolate, &thread) != 0) { fprintf(stderr, "initialization error\n"); return 1; } printf("Result> %d\n",ceilingPowerOfTwo(thread, 14)); return 0;}
Compile the C++ code using the following command and try to run it.
g++ ceilingPowerOfTwoCpp.cpp -L includes/ -I includes/ -lmymath -o ceilingPowerOfTwoCpp
Note: you might need to set the includes directory to LD_LIBRARY_PATH using:
export LD_LIBRARY_PATH=<path_to_includes_directory>
Interoperability is an inevitable requirement in the world where programming languages are growing concurrently. The shared library feature of GraalVM Native Image provides an easy way to embed Java method to a C++ program, which enables the writing of complex user-defined functions and the use of the third-party library. A promising example might be on the development of a data processing framework that aims both high performance and high-level APIs.
If you want to read more about GraalVM, head on to their home page. The full code for this tutorial is available in this repository. | [
{
"code": null,
"e": 648,
"s": 171,
"text": "Java and C++ remain two of the most popular programming languages. The two languages have different designs and characteristics. Depending on the problem, one might work better than the other. However, at some point, we need to integrate these languages, e.g. calling a method written in Java to your C++ code. The need to integrate Java and C++ is not something new. In fact, we can find a tutorial dated back to 1996. Since then, the two languages have developed remarkably."
},
{
"code": null,
"e": 1552,
"s": 648,
"text": "In this tutorial, we are going to learn how to call a java method from a C++ using GraalVM native image. If this is the first time you heard about GraalVM, you might be interested in checking out their homepage. GraalVM is a virtual machine that you can use to run a Java application. It’s based on JVM, but with additional features such as ahead of time compilation, fewer memory footprints, and other advanced optimizations. Additionally, GraalVM provides a native image plugin that you can use to compile a Java application to a native application. That means your application can run without requiring a JVM installed and running. Interestingly, you can also use this native image plugin to compile your Java application into a shared library and load it from your C++ code. This comes very handily when you code mainly written in C++ but you want to use an existing Java library on some part of it."
},
{
"code": null,
"e": 1675,
"s": 1552,
"text": "Before diving into the tutorial, let’s have a look at how this thing works. Basically, what you will do are the following:"
},
{
"code": null,
"e": 1849,
"s": 1675,
"text": "Write your method in Java.Compile the Java code to C++ shared library (yourlib.so) and header (yourlib.h) file using GraalVM.Load the library and header to your C++ project."
},
{
"code": null,
"e": 1876,
"s": 1849,
"text": "Write your method in Java."
},
{
"code": null,
"e": 1976,
"s": 1876,
"text": "Compile the Java code to C++ shared library (yourlib.so) and header (yourlib.h) file using GraalVM."
},
{
"code": null,
"e": 2025,
"s": 1976,
"text": "Load the library and header to your C++ project."
},
{
"code": null,
"e": 2250,
"s": 2025,
"text": "In this example, we will simulate a use case where you want to use a function from a third-party Java library on your C++ project. Particularly, we are interested to use one of the math functions from Google’s Guava library."
},
{
"code": null,
"e": 2605,
"s": 2250,
"text": "First, we need to set up a maven project for our java method. Building our project in maven helps us to import the dependencies as well as utilizing the GraalVM native image plugin to create the shared library. Once the project is created, add the dependencies to Guava library (or any library that you need) and the GraalVM library to your pom.xml file:"
},
{
"code": null,
"e": 3011,
"s": 2605,
"text": "<dependencies> <!-- https://mvnrepository.com/artifact/org.graalvm.nativeimage/svm --> <dependency> <groupId>org.graalvm.nativeimage</groupId> <artifactId>svm</artifactId> <version>19.3.1</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>28.2-jre</version> </dependency></dependencies>"
},
{
"code": null,
"e": 3089,
"s": 3011,
"text": "Next, add the following plugin to build your java code to C++ shared library:"
},
{
"code": null,
"e": 3723,
"s": 3089,
"text": "<build> <finalName>libmymath</finalName> <plugins> <plugin> <groupId>com.oracle.substratevm</groupId> <artifactId>native-image-maven-plugin</artifactId> <version>20.0.0</version> <executions> <execution> <goals> <goal>native-image</goal> </goals> <phase>package</phase> </execution> </executions> <configuration> <buildArgs>--shared -H:Name=libmymath</buildArgs> </configuration> </plugin> </plugins></build>"
},
{
"code": null,
"e": 4131,
"s": 3723,
"text": "Let’s have a look at the bold parts. On the <finalName> tag, put a name that you want as the name of your library. Note the version that you specify on the <version> tag as you will need it later. On the <buildArgs>, we specify the shared and name parameter to instruct the GraalVM native image to create a shared library instead of a native executable. Put the same name as finalName on the Name parameter."
},
{
"code": null,
"e": 4758,
"s": 4131,
"text": "Now let’s prepare our Java method. Given an integer input x, we are interested to calculate the nearest power of 2 greater x. For example, if x is 14 it will return 16, as 16 is the nearest power of 2 greater than 14. Below is the snippet of our function. Note that we need to put an additional first parameter thread of type IsolateThread to bridge our Java and C++ execution. This parameter has to be in the first position. We also need to specify the name of the method in the CEntryPoint annotation. This is the method name that we will refer to in our C++ code. You can check the complete java project in this repository."
},
{
"code": null,
"e": 5081,
"s": 4758,
"text": "import com.google.common.math.IntMath;import org.graalvm.nativeimage.IsolateThread;import org.graalvm.nativeimage.c.function.CEntryPoint;public class MyMath { @CEntryPoint (name = \"ceilingPowerOfTwo\") public static int ceilingPowerOfTwo(IsolateThread thread, int x) { return IntMath.ceilingPowerOfTwo(x); }}"
},
{
"code": null,
"e": 5370,
"s": 5081,
"text": "Having our project set, we now need to run mvn package to compile our Java method to a shared library. However, as this functionality only available on GraalVM, we will need to set up the GraalVM and point our JAVA_HOME to the GraalVM binary. Therefore, you will need to do the following:"
},
{
"code": null,
"e": 5925,
"s": 5370,
"text": "Download GraalVM. Make sure you pick the correct architecture, java version, and the GraalVM version that you specify in the pom.xml. Specifically, this example project uses GraalVM 20.0.0 for Java 8.Install the native-image extension by using the gu binary. In a Unix environment, you can do that using: <path_to_graalvm_directory>graalvm-ce-java8–20.0.0 2bin/gu install native-imageUpdate JAVA_HOME to point to the downloaded GraalVM directory. In a Unix environment, you can use export JAVA_HOME=<path_to_graalvm_directory/graalvm-ce-java8–20.0.0 2/>."
},
{
"code": null,
"e": 6126,
"s": 5925,
"text": "Download GraalVM. Make sure you pick the correct architecture, java version, and the GraalVM version that you specify in the pom.xml. Specifically, this example project uses GraalVM 20.0.0 for Java 8."
},
{
"code": null,
"e": 6311,
"s": 6126,
"text": "Install the native-image extension by using the gu binary. In a Unix environment, you can do that using: <path_to_graalvm_directory>graalvm-ce-java8–20.0.0 2bin/gu install native-image"
},
{
"code": null,
"e": 6482,
"s": 6311,
"text": "Update JAVA_HOME to point to the downloaded GraalVM directory. In a Unix environment, you can use export JAVA_HOME=<path_to_graalvm_directory/graalvm-ce-java8–20.0.0 2/>."
},
{
"code": null,
"e": 6786,
"s": 6482,
"text": "Now you can call the mvn package install to build the shared library. It will generate several files: graal_isolate.h, graal_isolate_dynamic.h, libmymath.h, libmymath_dynamic.h, and libmymath.so (or in other formats in other OS). Aside from our own library, it will also generate Graal VM C++ libraries."
},
{
"code": null,
"e": 7007,
"s": 6786,
"text": "Let’s now use our shared library in the following simple C++ project. Put the generated file inside the directory of this C++ project. For example, you can create an include folder and put these files inside this folder."
},
{
"code": null,
"e": 7342,
"s": 7007,
"text": "#include <iostream>#include <libmymath.h>int main() { graal_isolate_t *isolate = NULL; graal_isolatethread_t *thread = NULL; if (graal_create_isolate(NULL, &isolate, &thread) != 0) { fprintf(stderr, \"initialization error\\n\"); return 1; } printf(\"Result> %d\\n\",ceilingPowerOfTwo(thread, 14)); return 0;}"
},
{
"code": null,
"e": 7410,
"s": 7342,
"text": "Compile the C++ code using the following command and try to run it."
},
{
"code": null,
"e": 7498,
"s": 7410,
"text": "g++ ceilingPowerOfTwoCpp.cpp -L includes/ -I includes/ -lmymath -o ceilingPowerOfTwoCpp"
},
{
"code": null,
"e": 7575,
"s": 7498,
"text": "Note: you might need to set the includes directory to LD_LIBRARY_PATH using:"
},
{
"code": null,
"e": 7627,
"s": 7575,
"text": "export LD_LIBRARY_PATH=<path_to_includes_directory>"
},
{
"code": null,
"e": 8083,
"s": 7627,
"text": "Interoperability is an inevitable requirement in the world where programming languages are growing concurrently. The shared library feature of GraalVM Native Image provides an easy way to embed Java method to a C++ program, which enables the writing of complex user-defined functions and the use of the third-party library. A promising example might be on the development of a data processing framework that aims both high performance and high-level APIs."
}
] |
Bayesian Optimization: A step by step approach | by Avishek Nag | Towards Data Science | Optimizing a function is super important in many of the real life analytics use cases. By optimization we mean, either find an maximum or minimum of the target function with a certain set of parameter combination. Finding out that min or max value as well as the parameters should be the objective. In this article, we will discuss about basics of optimizing an unknown costly function with Bayesian approach.
From basic calculus we know that to find an max or min value of a function we need to solve the derivative equation for x like below:
Roots of the equation will be the optimal values of parameter x which in turn gives the optimal value of the function f(x). It is simple as long as you know the full algebraic form of the function f(x). But, in many real life scenarios, things are not so simple. If it is a black box, then you will only know output & input values of any f(x), but the full form will be unknown to you. So, analytically you cannot find the derivatives. On top of that, the function may be very costly to invoke. Consider two use cases like below:
1. Finding out the optimal hyperparameter combination of a neural network
Consider a large & complex Neural Network that solves a classification problem. Hyperparameters may be the number of hidden units, number of hidden layers, etc in that network. Relation between these can be thought as a hypothetical function that takes the hyperparameters as input and returns classification accuracy as output. Off course, you don’t know the actual algebraic form of this function . One way of finding the optimal combination will be trying out various random combinations by training the network repeatedly. The root of the problem lies there. We cannot afford that repeated training as it is a very large & complex network and training takes a lot of time & resources. Bayesian optimization can help here.
2. Excavation of an archeological site — finding optimal ‘digs’
Not only for software (like Neural Netowork case), Bayesian optimization also helps to overcome a challenge in physical world. In an archeological site, the major question comes into the mind of the experts : “where to dig ?”. And need not to be mentioned, digging is a costly & “blackbox” operation, all in terms of man-power, money & time. The function can be thought as if it returns the list of resources available in an site and parameters could be location details, and some other very domain specific stuff. Finding that location is the challenge and Bayesian approach can solve it.
In all of the cases, some initial runs of the function are needed for estimation. Consider following function:
It is “white box” (as derivatives can be found analytically) and does not look very costly at first glance and , but for out convenience, assume that it is costly & “black box” in nature and takes lot of time to return the output. Let’s run some simulations,
x = np.random.randn(5,2)y = costly_function(x)pd.DataFrame(data={'y':y, 'x0':x[:,0], 'x1':x[:,1]})
And the result,
The function takes two parameters x0 & x1. For costly functions like the above one, we can only afford to call that a few number of times. It may happen, that the initial function result & input may be given to us in a file or database. We then have to find out the optimal(minimum or maximum) value and the parameter combination responsible (x0 & x1, in this case) for that. We will never know the actual algebraic form, the analytical form of the derivatives and thus have to do the optimization numerically.
In Bayesian Optimization, an initial set of input/output combination is generally given as said above or may be generated from the function. For two use cases discussed above, it can be achieved like below:
Neural Network is trained a number of times on different hyper-parameter combinations and the accuracies are captured & stored. This set can be used as initial data points.In an archeological excavation operation , several initial digs can be performed to gather information about the site. It works as initial data points.
Neural Network is trained a number of times on different hyper-parameter combinations and the accuracies are captured & stored. This set can be used as initial data points.
In an archeological excavation operation , several initial digs can be performed to gather information about the site. It works as initial data points.
In short, it is a constrained optimization which solves two problem as given below:
i) Finding out the optimal parameters that give optimal value of the black box function in a numerical way as analytically derivatives cannot be found.
ii) Keeping the number of function calls in the overall process as minimum as possible as it is very costly. (Apart from initial few runs)
Bayesian approach is based on statistical modelling of the “blackbox” function and intelligent exploration of the parameter space. Few nomenclatures are important to know.
1. Surrogate Model
It is the statistical/probabilistic modelling of the “blackbox” function. It works as a proxy to the later. For experimenting with different parameters, this model is used to simulate function output instead of calling the actual costly function. A Gaussian Process Regression (it is a multivariate Gaussian Stochastic process) is used as “surrogate” in Bayesian Optimization.
2. Acquisition Function
It is a metric function which decides which parameter value that can return the optimal value from the function. There are many variations of it. We will work with the one “Expected Improvement”.
3. Exploration vs Exploitation
It is typical strategy to compensate between local & global optimal values in the parameter space. Consider the graph as given below:
www.shutterstock.com
While doing the parameter space exploration, many such local optimal data points can be found where the function has high or low value. But, the process should not stop there as more optimal values may be there in some other area. It is known as “Exploration”. On the other hand, importance should also be given to the points those are returning optimal (high or low) values from the function consistently. It is “Exploitation”. So, both have some significance. It is a trivial decision, “when to explore for more optimal data points in different locations or when to exploit & go in the same direction”. This is the area where Bayesian Optimization beats traditional Random search or Grid search approach for parameter space as it takes a middle ground. It helps to achieve the target more quickly with a small number of actual function calls. Other two methods go for blind searching that completely ignores this fact. Searching has to be very precise & “to the point” to reduce cost. Bayesian approach takes care of it pretty well.
In short, acquisition function uses “Exploration vs Exploitation” strategy to decide optimal parameter search in an iterative manner. Inside these iterations, surrogate model helps to get simulated output of the function. Any Bayesian Approach is based on the concept of “Prior/Posterior” duo. Initial runs of the function as mentioned in previous section are used as starting points or “Priors” and in each iteration, these “Priors” are enriched with “Posterior” data points. After few iterations, optimal data points are reached and the entire process stops there. We will see all of these in action next.
We will use the same “costly_function” with two parameters declared in previous section as our target function to be optimized i.e., we need to maximize it at present case. It is assumed that the function is “black box” and output of few runs will be given to us. We will define a class “BayesianOptimizer” and declare its functions & attributes in a step by step manner.
Let us first create the structure of the class and declare its attributes.
“gauss_pr” is the surrogate model as mentioned in previous sections. “x_init” & “y_init” are as usual the parameters & outputs of the function from the initial set of runs. You will see usage of other attributes in a timely manner.
Now, we will create a function named “_get_expected_improvement” inside the same class which is the heart of Bayesian approach. It is the desired acquisition function mentioned earlier. Let’s discuss a few theory before jumping into this.
Whenever a new data point is tried, we need to compute a metric known as “Expected Improvement” or “EI” that gives the weightage of the data point. The formulae is given by:
where
This looks little complex at first. “mu(f(x))” is the prediction (i.e, the ‘y’ value) from the Gaussian process for a new data point x. “max{f(x)}” is the maximum of the predictions from the entire list of priors at current stage (again it is obtained from the Gaussian process). “sigma(f(x))” is as usual is the standard deviation of the prediction for the new data point x. The difference between “mu(f(x))” & “max{f(x)}” is just to check the improvement of the search process. A higher value indicates that the new data point is returning a high value from the function which is “significantly” higher than the maximum obtained so far. This “significance” is obtained by multiplying the difference with the cumulative probability density. So, it gives an expected or overall “mean” improvement and off course it is the “Exploitation” part. This value is also augmented by a magical factor “sigma(f(x))”. It gives the uncertainty to the “EI” metric and is the secret of handling the “Exploration” part. “mu(f(x))” and “sigma(f(x))” balance each others effect quite well and as a result EI(x) takes a middle ground.
Now, we will see the implementation of this function,
It avoids the actual function call and uses the Gaussian process as a proxy. So, the trial with different points happens through the proxy Gaussian Process, not the actual function. This is one of the secrets of “cost reduction”.
How this Gaussian process is built iteratively, we will see later.
Next, this acquisition function is used to compute the “EI” metrics in a neighborhood of randomly selected data points, numerically it is maximized with numerical derivative computation. Don’t get confused here !! We just again said “numerical derivatives” of the function. But, it is not the target costly function. It is about maximizing the acquisition function. Just think for a moment !! We will only be interested in that data point which gives maximum value of the “EI”, i.e., gives the maximum improvement of the target function (‘y’ value) from the current maximum one.
Off course, it will give the right direction where we should keep searching the parameter space and avoid unnecessary blind exploration . This is the second secret of “cost reduction”.
We will see the implementation next,
A batch (mentioned by “batch_size”) of randomly generated data points are tried and for each one, acquisition function is maximized (actually a negative function is minimized just to match the “scipy” library support. Minimizing negative of a function is equivalent to maximizing it) in that direction. Again, maximum of the “EI” from iterations is taken and returned with the corresponding parameter x value. Maximizing numerically with a starting point and again taking the maximum from the results actually gives right direction to parameter x with a right amount of mean & uncertainty in it. It is a trade-off between breadth-search (uncertainty) and depth-search(mean) and gets best effects from the the both.
Now, the next part is the actual work. You saw that there is a Gaussian process regressor as surrogate model. It is used to build a model iteratively on top of “Prior” data points. “optimize” function is the one which does all of this. It is shown below.
Steps of the above one can be summarized as follows:
i) Find out the maximum and corresponding parameter x from initial “prior” data points
ii) Build a Gaussian Process with the initial “prior” data points. Gaussian Process uses Maximum Likelihood Estimation to find a right joint distribution between parameters.
iii) Get the next best parameter x using acquisition function. As said in earlier sections, it is the step where trial & error with different data points happens with the help of the Gaussian model without calling the actual “costly” target function.
iv) Get the ‘y’ value for that parameter value x using the real target function. It is the “posterior” data point.
v) Update “Priors” with the “Posterior” data, update the current maximum value from the “priors” and then again go to step ii)
vi) At the end, return the current maximum “y” value and the corresponding parameter x.
You will notice that we are also doing some distance computation and capturing current best samples (nothing but current maximum y and the corresponding x). Distances are computed between two consecutive probable next x value from function “_get_next_probable_point”. It shows the progress of the algorithm. You will see that in results.
We will use two sample parameters with 2-dimensions as initial data points. We can use n-dimension as the “costly_function” is generic enough to handle that.
sample_x = np.array([[8,1],[6.2,5.3]])sample_y = costly_function(sample_x)
Now, it is time to use “BayesianOptimizer” class,
bopt = BayesianOptimizer(target_func=costly_function, x_init=sample_x, y_init=sample_y, n_iter=200, scale=10, batch_size=30)bopt.optimize()
It triggers the searching with a neighborhood size of 30 and for 200 iterations. The result is shown below:
So, the maximum value of the costly function is 3.7 for parameters x0=1.92 and x1=3.62. You might have noticed that in the definition of costly function we have introduced a random noise just to make its derivatives difficult to compute.
Remember as said earlier many times, body or definition of “costly_function” will never be available to you. Here, for our understanding we just created one dummy function. But, in reality, that won’t be the case. sample x & y may be given to you as dataset or there will be some public/privately hosted “blackbox” API which can be invoked to get y values for any x.
Now, we will some other results from the computations,
Distances can be plotted,
pd.DataFrame(bopt.distances_).plot()
Notice, distances between two consecutive probable next x point is decreasing over the iterations. It is expected. Gaussian model becomes more mature after each iteration and its predictions become more perfect which results accurate “EI” values. Ultimately it reaches more closer to the optimal x after each iteration and thus the distance starts decreasing.
Now, we will see how ‘y’ values are changing over the iterations,
bopt.best_samples_['y'].plot()
Notice, y is reaching to its maximum in a step wise manner. Each iteration is producing a better estimate of maximum ‘y’.
Now, the same plot for computed ‘EI’
bopt.best_samples_['ei'].plot()
‘EI’ is decreasing as expected. Think about it !!. After each iteration, a better y is produced, so that means there is less chance for bigger improvement as we are progressing towards optimal.
One big question “How do you decide n_iter ?” Changing its value will definitely affect our estimation of maximum. One thing to be noted here,
n_iter is equal to the number of times the real costly function is called in the entire optimization process except initialization part
So, off course its value depends on how much cost are we ready to bear.
Consider use case 1 of Neural Network model. If there is a cloud environment which charges its customer per “training” run of the deep neural network and a budget constraint is there, then “n_iter” has to be set accordingly (as in this case target function is training of the network & getting the accuracy).
Bayesian approach tries to give an estimate of the function by reducing real calls, so its accuracy may not be as good as RandomSearch or GridSearch in some cases.
Bayesian Optimization is useful when cost is more important rather than very minute level accuracy.
Source code can be found here, | [
{
"code": null,
"e": 582,
"s": 172,
"text": "Optimizing a function is super important in many of the real life analytics use cases. By optimization we mean, either find an maximum or minimum of the target function with a certain set of parameter combination. Finding out that min or max value as well as the parameters should be the objective. In this article, we will discuss about basics of optimizing an unknown costly function with Bayesian approach."
},
{
"code": null,
"e": 716,
"s": 582,
"text": "From basic calculus we know that to find an max or min value of a function we need to solve the derivative equation for x like below:"
},
{
"code": null,
"e": 1246,
"s": 716,
"text": "Roots of the equation will be the optimal values of parameter x which in turn gives the optimal value of the function f(x). It is simple as long as you know the full algebraic form of the function f(x). But, in many real life scenarios, things are not so simple. If it is a black box, then you will only know output & input values of any f(x), but the full form will be unknown to you. So, analytically you cannot find the derivatives. On top of that, the function may be very costly to invoke. Consider two use cases like below:"
},
{
"code": null,
"e": 1320,
"s": 1246,
"text": "1. Finding out the optimal hyperparameter combination of a neural network"
},
{
"code": null,
"e": 2046,
"s": 1320,
"text": "Consider a large & complex Neural Network that solves a classification problem. Hyperparameters may be the number of hidden units, number of hidden layers, etc in that network. Relation between these can be thought as a hypothetical function that takes the hyperparameters as input and returns classification accuracy as output. Off course, you don’t know the actual algebraic form of this function . One way of finding the optimal combination will be trying out various random combinations by training the network repeatedly. The root of the problem lies there. We cannot afford that repeated training as it is a very large & complex network and training takes a lot of time & resources. Bayesian optimization can help here."
},
{
"code": null,
"e": 2110,
"s": 2046,
"text": "2. Excavation of an archeological site — finding optimal ‘digs’"
},
{
"code": null,
"e": 2700,
"s": 2110,
"text": "Not only for software (like Neural Netowork case), Bayesian optimization also helps to overcome a challenge in physical world. In an archeological site, the major question comes into the mind of the experts : “where to dig ?”. And need not to be mentioned, digging is a costly & “blackbox” operation, all in terms of man-power, money & time. The function can be thought as if it returns the list of resources available in an site and parameters could be location details, and some other very domain specific stuff. Finding that location is the challenge and Bayesian approach can solve it."
},
{
"code": null,
"e": 2811,
"s": 2700,
"text": "In all of the cases, some initial runs of the function are needed for estimation. Consider following function:"
},
{
"code": null,
"e": 3070,
"s": 2811,
"text": "It is “white box” (as derivatives can be found analytically) and does not look very costly at first glance and , but for out convenience, assume that it is costly & “black box” in nature and takes lot of time to return the output. Let’s run some simulations,"
},
{
"code": null,
"e": 3169,
"s": 3070,
"text": "x = np.random.randn(5,2)y = costly_function(x)pd.DataFrame(data={'y':y, 'x0':x[:,0], 'x1':x[:,1]})"
},
{
"code": null,
"e": 3185,
"s": 3169,
"text": "And the result,"
},
{
"code": null,
"e": 3696,
"s": 3185,
"text": "The function takes two parameters x0 & x1. For costly functions like the above one, we can only afford to call that a few number of times. It may happen, that the initial function result & input may be given to us in a file or database. We then have to find out the optimal(minimum or maximum) value and the parameter combination responsible (x0 & x1, in this case) for that. We will never know the actual algebraic form, the analytical form of the derivatives and thus have to do the optimization numerically."
},
{
"code": null,
"e": 3903,
"s": 3696,
"text": "In Bayesian Optimization, an initial set of input/output combination is generally given as said above or may be generated from the function. For two use cases discussed above, it can be achieved like below:"
},
{
"code": null,
"e": 4227,
"s": 3903,
"text": "Neural Network is trained a number of times on different hyper-parameter combinations and the accuracies are captured & stored. This set can be used as initial data points.In an archeological excavation operation , several initial digs can be performed to gather information about the site. It works as initial data points."
},
{
"code": null,
"e": 4400,
"s": 4227,
"text": "Neural Network is trained a number of times on different hyper-parameter combinations and the accuracies are captured & stored. This set can be used as initial data points."
},
{
"code": null,
"e": 4552,
"s": 4400,
"text": "In an archeological excavation operation , several initial digs can be performed to gather information about the site. It works as initial data points."
},
{
"code": null,
"e": 4636,
"s": 4552,
"text": "In short, it is a constrained optimization which solves two problem as given below:"
},
{
"code": null,
"e": 4788,
"s": 4636,
"text": "i) Finding out the optimal parameters that give optimal value of the black box function in a numerical way as analytically derivatives cannot be found."
},
{
"code": null,
"e": 4927,
"s": 4788,
"text": "ii) Keeping the number of function calls in the overall process as minimum as possible as it is very costly. (Apart from initial few runs)"
},
{
"code": null,
"e": 5099,
"s": 4927,
"text": "Bayesian approach is based on statistical modelling of the “blackbox” function and intelligent exploration of the parameter space. Few nomenclatures are important to know."
},
{
"code": null,
"e": 5118,
"s": 5099,
"text": "1. Surrogate Model"
},
{
"code": null,
"e": 5495,
"s": 5118,
"text": "It is the statistical/probabilistic modelling of the “blackbox” function. It works as a proxy to the later. For experimenting with different parameters, this model is used to simulate function output instead of calling the actual costly function. A Gaussian Process Regression (it is a multivariate Gaussian Stochastic process) is used as “surrogate” in Bayesian Optimization."
},
{
"code": null,
"e": 5519,
"s": 5495,
"text": "2. Acquisition Function"
},
{
"code": null,
"e": 5715,
"s": 5519,
"text": "It is a metric function which decides which parameter value that can return the optimal value from the function. There are many variations of it. We will work with the one “Expected Improvement”."
},
{
"code": null,
"e": 5746,
"s": 5715,
"text": "3. Exploration vs Exploitation"
},
{
"code": null,
"e": 5880,
"s": 5746,
"text": "It is typical strategy to compensate between local & global optimal values in the parameter space. Consider the graph as given below:"
},
{
"code": null,
"e": 5901,
"s": 5880,
"text": "www.shutterstock.com"
},
{
"code": null,
"e": 6936,
"s": 5901,
"text": "While doing the parameter space exploration, many such local optimal data points can be found where the function has high or low value. But, the process should not stop there as more optimal values may be there in some other area. It is known as “Exploration”. On the other hand, importance should also be given to the points those are returning optimal (high or low) values from the function consistently. It is “Exploitation”. So, both have some significance. It is a trivial decision, “when to explore for more optimal data points in different locations or when to exploit & go in the same direction”. This is the area where Bayesian Optimization beats traditional Random search or Grid search approach for parameter space as it takes a middle ground. It helps to achieve the target more quickly with a small number of actual function calls. Other two methods go for blind searching that completely ignores this fact. Searching has to be very precise & “to the point” to reduce cost. Bayesian approach takes care of it pretty well."
},
{
"code": null,
"e": 7544,
"s": 6936,
"text": "In short, acquisition function uses “Exploration vs Exploitation” strategy to decide optimal parameter search in an iterative manner. Inside these iterations, surrogate model helps to get simulated output of the function. Any Bayesian Approach is based on the concept of “Prior/Posterior” duo. Initial runs of the function as mentioned in previous section are used as starting points or “Priors” and in each iteration, these “Priors” are enriched with “Posterior” data points. After few iterations, optimal data points are reached and the entire process stops there. We will see all of these in action next."
},
{
"code": null,
"e": 7916,
"s": 7544,
"text": "We will use the same “costly_function” with two parameters declared in previous section as our target function to be optimized i.e., we need to maximize it at present case. It is assumed that the function is “black box” and output of few runs will be given to us. We will define a class “BayesianOptimizer” and declare its functions & attributes in a step by step manner."
},
{
"code": null,
"e": 7991,
"s": 7916,
"text": "Let us first create the structure of the class and declare its attributes."
},
{
"code": null,
"e": 8223,
"s": 7991,
"text": "“gauss_pr” is the surrogate model as mentioned in previous sections. “x_init” & “y_init” are as usual the parameters & outputs of the function from the initial set of runs. You will see usage of other attributes in a timely manner."
},
{
"code": null,
"e": 8462,
"s": 8223,
"text": "Now, we will create a function named “_get_expected_improvement” inside the same class which is the heart of Bayesian approach. It is the desired acquisition function mentioned earlier. Let’s discuss a few theory before jumping into this."
},
{
"code": null,
"e": 8636,
"s": 8462,
"text": "Whenever a new data point is tried, we need to compute a metric known as “Expected Improvement” or “EI” that gives the weightage of the data point. The formulae is given by:"
},
{
"code": null,
"e": 8642,
"s": 8636,
"text": "where"
},
{
"code": null,
"e": 9759,
"s": 8642,
"text": "This looks little complex at first. “mu(f(x))” is the prediction (i.e, the ‘y’ value) from the Gaussian process for a new data point x. “max{f(x)}” is the maximum of the predictions from the entire list of priors at current stage (again it is obtained from the Gaussian process). “sigma(f(x))” is as usual is the standard deviation of the prediction for the new data point x. The difference between “mu(f(x))” & “max{f(x)}” is just to check the improvement of the search process. A higher value indicates that the new data point is returning a high value from the function which is “significantly” higher than the maximum obtained so far. This “significance” is obtained by multiplying the difference with the cumulative probability density. So, it gives an expected or overall “mean” improvement and off course it is the “Exploitation” part. This value is also augmented by a magical factor “sigma(f(x))”. It gives the uncertainty to the “EI” metric and is the secret of handling the “Exploration” part. “mu(f(x))” and “sigma(f(x))” balance each others effect quite well and as a result EI(x) takes a middle ground."
},
{
"code": null,
"e": 9813,
"s": 9759,
"text": "Now, we will see the implementation of this function,"
},
{
"code": null,
"e": 10043,
"s": 9813,
"text": "It avoids the actual function call and uses the Gaussian process as a proxy. So, the trial with different points happens through the proxy Gaussian Process, not the actual function. This is one of the secrets of “cost reduction”."
},
{
"code": null,
"e": 10110,
"s": 10043,
"text": "How this Gaussian process is built iteratively, we will see later."
},
{
"code": null,
"e": 10689,
"s": 10110,
"text": "Next, this acquisition function is used to compute the “EI” metrics in a neighborhood of randomly selected data points, numerically it is maximized with numerical derivative computation. Don’t get confused here !! We just again said “numerical derivatives” of the function. But, it is not the target costly function. It is about maximizing the acquisition function. Just think for a moment !! We will only be interested in that data point which gives maximum value of the “EI”, i.e., gives the maximum improvement of the target function (‘y’ value) from the current maximum one."
},
{
"code": null,
"e": 10874,
"s": 10689,
"text": "Off course, it will give the right direction where we should keep searching the parameter space and avoid unnecessary blind exploration . This is the second secret of “cost reduction”."
},
{
"code": null,
"e": 10911,
"s": 10874,
"text": "We will see the implementation next,"
},
{
"code": null,
"e": 11626,
"s": 10911,
"text": "A batch (mentioned by “batch_size”) of randomly generated data points are tried and for each one, acquisition function is maximized (actually a negative function is minimized just to match the “scipy” library support. Minimizing negative of a function is equivalent to maximizing it) in that direction. Again, maximum of the “EI” from iterations is taken and returned with the corresponding parameter x value. Maximizing numerically with a starting point and again taking the maximum from the results actually gives right direction to parameter x with a right amount of mean & uncertainty in it. It is a trade-off between breadth-search (uncertainty) and depth-search(mean) and gets best effects from the the both."
},
{
"code": null,
"e": 11881,
"s": 11626,
"text": "Now, the next part is the actual work. You saw that there is a Gaussian process regressor as surrogate model. It is used to build a model iteratively on top of “Prior” data points. “optimize” function is the one which does all of this. It is shown below."
},
{
"code": null,
"e": 11934,
"s": 11881,
"text": "Steps of the above one can be summarized as follows:"
},
{
"code": null,
"e": 12021,
"s": 11934,
"text": "i) Find out the maximum and corresponding parameter x from initial “prior” data points"
},
{
"code": null,
"e": 12195,
"s": 12021,
"text": "ii) Build a Gaussian Process with the initial “prior” data points. Gaussian Process uses Maximum Likelihood Estimation to find a right joint distribution between parameters."
},
{
"code": null,
"e": 12446,
"s": 12195,
"text": "iii) Get the next best parameter x using acquisition function. As said in earlier sections, it is the step where trial & error with different data points happens with the help of the Gaussian model without calling the actual “costly” target function."
},
{
"code": null,
"e": 12561,
"s": 12446,
"text": "iv) Get the ‘y’ value for that parameter value x using the real target function. It is the “posterior” data point."
},
{
"code": null,
"e": 12688,
"s": 12561,
"text": "v) Update “Priors” with the “Posterior” data, update the current maximum value from the “priors” and then again go to step ii)"
},
{
"code": null,
"e": 12776,
"s": 12688,
"text": "vi) At the end, return the current maximum “y” value and the corresponding parameter x."
},
{
"code": null,
"e": 13114,
"s": 12776,
"text": "You will notice that we are also doing some distance computation and capturing current best samples (nothing but current maximum y and the corresponding x). Distances are computed between two consecutive probable next x value from function “_get_next_probable_point”. It shows the progress of the algorithm. You will see that in results."
},
{
"code": null,
"e": 13272,
"s": 13114,
"text": "We will use two sample parameters with 2-dimensions as initial data points. We can use n-dimension as the “costly_function” is generic enough to handle that."
},
{
"code": null,
"e": 13347,
"s": 13272,
"text": "sample_x = np.array([[8,1],[6.2,5.3]])sample_y = costly_function(sample_x)"
},
{
"code": null,
"e": 13397,
"s": 13347,
"text": "Now, it is time to use “BayesianOptimizer” class,"
},
{
"code": null,
"e": 13537,
"s": 13397,
"text": "bopt = BayesianOptimizer(target_func=costly_function, x_init=sample_x, y_init=sample_y, n_iter=200, scale=10, batch_size=30)bopt.optimize()"
},
{
"code": null,
"e": 13645,
"s": 13537,
"text": "It triggers the searching with a neighborhood size of 30 and for 200 iterations. The result is shown below:"
},
{
"code": null,
"e": 13883,
"s": 13645,
"text": "So, the maximum value of the costly function is 3.7 for parameters x0=1.92 and x1=3.62. You might have noticed that in the definition of costly function we have introduced a random noise just to make its derivatives difficult to compute."
},
{
"code": null,
"e": 14250,
"s": 13883,
"text": "Remember as said earlier many times, body or definition of “costly_function” will never be available to you. Here, for our understanding we just created one dummy function. But, in reality, that won’t be the case. sample x & y may be given to you as dataset or there will be some public/privately hosted “blackbox” API which can be invoked to get y values for any x."
},
{
"code": null,
"e": 14305,
"s": 14250,
"text": "Now, we will some other results from the computations,"
},
{
"code": null,
"e": 14331,
"s": 14305,
"text": "Distances can be plotted,"
},
{
"code": null,
"e": 14368,
"s": 14331,
"text": "pd.DataFrame(bopt.distances_).plot()"
},
{
"code": null,
"e": 14728,
"s": 14368,
"text": "Notice, distances between two consecutive probable next x point is decreasing over the iterations. It is expected. Gaussian model becomes more mature after each iteration and its predictions become more perfect which results accurate “EI” values. Ultimately it reaches more closer to the optimal x after each iteration and thus the distance starts decreasing."
},
{
"code": null,
"e": 14794,
"s": 14728,
"text": "Now, we will see how ‘y’ values are changing over the iterations,"
},
{
"code": null,
"e": 14825,
"s": 14794,
"text": "bopt.best_samples_['y'].plot()"
},
{
"code": null,
"e": 14947,
"s": 14825,
"text": "Notice, y is reaching to its maximum in a step wise manner. Each iteration is producing a better estimate of maximum ‘y’."
},
{
"code": null,
"e": 14984,
"s": 14947,
"text": "Now, the same plot for computed ‘EI’"
},
{
"code": null,
"e": 15016,
"s": 14984,
"text": "bopt.best_samples_['ei'].plot()"
},
{
"code": null,
"e": 15210,
"s": 15016,
"text": "‘EI’ is decreasing as expected. Think about it !!. After each iteration, a better y is produced, so that means there is less chance for bigger improvement as we are progressing towards optimal."
},
{
"code": null,
"e": 15353,
"s": 15210,
"text": "One big question “How do you decide n_iter ?” Changing its value will definitely affect our estimation of maximum. One thing to be noted here,"
},
{
"code": null,
"e": 15489,
"s": 15353,
"text": "n_iter is equal to the number of times the real costly function is called in the entire optimization process except initialization part"
},
{
"code": null,
"e": 15561,
"s": 15489,
"text": "So, off course its value depends on how much cost are we ready to bear."
},
{
"code": null,
"e": 15870,
"s": 15561,
"text": "Consider use case 1 of Neural Network model. If there is a cloud environment which charges its customer per “training” run of the deep neural network and a budget constraint is there, then “n_iter” has to be set accordingly (as in this case target function is training of the network & getting the accuracy)."
},
{
"code": null,
"e": 16034,
"s": 15870,
"text": "Bayesian approach tries to give an estimate of the function by reducing real calls, so its accuracy may not be as good as RandomSearch or GridSearch in some cases."
},
{
"code": null,
"e": 16134,
"s": 16034,
"text": "Bayesian Optimization is useful when cost is more important rather than very minute level accuracy."
}
] |
C++ default constructor | A class constructor is a special member function of a class that is executed whenever we create new objects of that class.
A constructor will have exact same name as the class and it does not have any return type at all, not even void. Constructors can be very useful for setting initial values for certain member variables.
Following example explains the concept of constructor −
Live Demo
#include <iostream>
using namespace std;
class Line {
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor
private:
double length;
};
// Member functions definitions including constructor
Line::Line(void) {
cout << "Object is being created" << endl;
}
void Line::setLength( double len ) {
length = len;
}
double Line::getLength( void ) {
return length;
}
// Main function for the program
int main() {
Line line;
// set line length
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
}
Object is being created
Length of line : 6 | [
{
"code": null,
"e": 1185,
"s": 1062,
"text": "A class constructor is a special member function of a class that is executed whenever we create new objects of that class."
},
{
"code": null,
"e": 1387,
"s": 1185,
"text": "A constructor will have exact same name as the class and it does not have any return type at all, not even void. Constructors can be very useful for setting initial values for certain member variables."
},
{
"code": null,
"e": 1443,
"s": 1387,
"text": "Following example explains the concept of constructor −"
},
{
"code": null,
"e": 1454,
"s": 1443,
"text": " Live Demo"
},
{
"code": null,
"e": 2077,
"s": 1454,
"text": "#include <iostream>\nusing namespace std;\nclass Line {\n public:\n void setLength( double len );\n double getLength( void );\n Line(); // This is the constructor\n private:\n double length;\n};\n// Member functions definitions including constructor\nLine::Line(void) {\n cout << \"Object is being created\" << endl;\n}\nvoid Line::setLength( double len ) {\n length = len;\n}\ndouble Line::getLength( void ) {\n return length;\n}\n// Main function for the program\nint main() {\n Line line;\n // set line length\n line.setLength(6.0);\n cout << \"Length of line : \" << line.getLength() <<endl;\n return 0;\n}"
},
{
"code": null,
"e": 2120,
"s": 2077,
"text": "Object is being created\nLength of line : 6"
}
] |
Creating Golden Ratio Calculator using PyQt5 - GeeksforGeeks | 10 Jul, 2020
In this article we will see how we can create a golden ratio calculator using PyQt5. In mathematics, two quantities are in the golden ratio if their ratio is the same as the ratio of their sum to the larger of the two quantities. The value of golden ratio is 1.61803398875. Below is how the golden ratio calculator will look like
PyQt5 is cross-platform GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided by this library. Below is the command to install the PyQt5
pip install PyQt5
Concept :Below is the formula for calculating golden ratio
A / B = (A + B) / A = golden_ratio
Here A is the larger length and B is the shorter i.e second part of the length and the value of golden ratio is 1.61803398875.
GUI Implementation Steps :1. Create a heading label that display the calculator name2. Create three radio buttons for first, second and sum of the lengths3. Create three spin boxes for user to enter the specific length4. Create push button for calculating the other values according tot golden ratio5. Create a label to show the calculated values
Back-End Implementation :1. Initially make all the spin boxes disable2. Add same action to all the three radio button3. Inside the radio button method which radio button is checked4. According to the checked radio button make the corresponding spin box enable and make the rest of the spin box disable5. Also assign the flag values according to the selected radio button6. Add same action to all three spin boxes7. Inside the spin box action check which spin box is enabled and make other spin box values zero8. Add action to the push button9. Inside the push button action check the flag according to the flag with the help of golden ratio formula calculate the other two lengths10. Format the calculated values and show the values with the help of result label
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import datetimeimport sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # width of window self.w_width = 400 # height of window self.w_height = 430 # setting geometry self.setGeometry(100, 100, self.w_width, self.w_height) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating head label head = QLabel("Golden Ratio Calculator", self) head.setWordWrap(True) # setting geometry to the head head.setGeometry(0, 10, 400, 60) # font font = QFont('Times', 15) font.setBold(True) font.setItalic(True) font.setUnderline(True) # setting font to the head head.setFont(font) # setting alignment of the head head.setAlignment(Qt.AlignCenter) # setting color effect to the head color = QGraphicsColorizeEffect(self) color.setColor(Qt.darkCyan) head.setGraphicsEffect(color) # creating a radio button self.length1 = QRadioButton("First Length (A)", self) # setting geometry self.length1.setGeometry(50, 90, 140, 40) # setting font self.length1.setFont(QFont('Times', 9)) # creating a spin box self.l1 = QSpinBox(self) self.l1.setMaximum(999999) # setting geometry to the spin box self.l1.setGeometry(200, 90, 160, 40) # setting font self.l1.setFont(QFont('Times', 9)) # setting alignment self.l1.setAlignment(Qt.AlignCenter) # creating a radio button self.length2 = QRadioButton("Second Length (B)", self) # setting geometry self.length2.setGeometry(50, 150, 145, 40) # setting font self.length2.setFont(QFont('Times', 9)) # creating a spin box self.l2 = QSpinBox(self) self.l2.setMaximum(999999) # setting geometry to the spin box self.l2.setGeometry(200, 150, 160, 40) # setting font self.l2.setFont(QFont('Times', 9)) # setting alignment self.l2.setAlignment(Qt.AlignCenter) # creating a radio button self.length_sum = QRadioButton("First + Second ", self) # setting geometry self.length_sum.setGeometry(50, 200, 140, 40) # setting font self.length_sum.setFont(QFont('Times', 9)) # creating a spin box self.l_s = QSpinBox(self) self.l_s.setMaximum(999999) # setting geometry to the spin box self.l_s.setGeometry(200, 200, 160, 40) # setting font self.l_s.setFont(QFont('Times', 9)) # setting alignment self.l_s.setAlignment(Qt.AlignCenter) # adding same action to all the radio button self.length1.clicked.connect(self.radio_method) self.length2.clicked.connect(self.radio_method) self.length_sum.clicked.connect(self.radio_method) # adding same action to all the spin box self.l1.valueChanged.connect(self.spin_method) self.l2.valueChanged.connect(self.spin_method) self.l_s.valueChanged.connect(self.spin_method) # making all the spin box disabled self.l1.setDisabled(True) self.l2.setDisabled(True) self.l_s.setDisabled(True) # creating a push button calculate = QPushButton("Calculate", self) # setting geometry to the push button calculate.setGeometry(100, 270, 200, 40) # adding action to the button calculate.clicked.connect(self.calculate) # adding color effect to the push button color = QGraphicsColorizeEffect() color.setColor(Qt.blue) calculate.setGraphicsEffect(color) # creating a label to show result self.result = QLabel(self) # setting properties to result label self.result.setAlignment(Qt.AlignCenter) # setting geometry self.result.setGeometry(50, 330, 300, 70) # making it multi line self.result.setWordWrap(True) # setting stylesheet # adding border and background self.result.setStyleSheet("QLabel" "{" "border : 3px solid black;" "background : white;" "}") # setting font self.result.setFont(QFont('Arial', 11)) # method called by the radio buttons def radio_method(self): # checking who is checked and who is unchecked # if first radio button is checked if self.length1.isChecked(): # making first spin box enable self.l1.setEnabled(True) # making rest two spin box disable self.l2.setDisabled(True) self.l_s.setDisabled(True) # assigning flags self.check1 = True self.check2 = False self.check_sum = False elif self.length2.isChecked(): # making second spin box enable self.l2.setEnabled(True) # making rest two spin box disable self.l1.setDisabled(True) self.l_s.setDisabled(True) # assigning flags self.check1 = False self.check2 = True self.check_sum = False elif self.length_sum.isChecked(): # making third spin box enable self.l_s.setEnabled(True) # making rest two spin box disable self.l1.setDisabled(True) self.l2.setDisabled(True) # assigning flags self.check1 = False self.check2 = False self.check_sum = True def spin_method(self): # finding who called the method if self.l1.isEnabled(): # setting current values self.l2.setValue(0) self.l_s.setValue(0) elif self.l2.isEnabled(): # setting current values self.l1.setValue(0) self.l_s.setValue(0) else: # setting current values self.l2.setValue(0) self.l1.setValue(0) def calculate(self): golden = 1.61803398875 # if first value is selected if self.check1 == True: # getting spin box value A = self.l1.value() B = A / golden Sum = A + B elif self.check2 == True: # getting spin box value B = self.l2.value() A = B * golden Sum = A + B else: # getting spin box value Sum = self.l_s.value() A = Sum / golden B = Sum - A # formatting values upto two decimal A = "{:.2f}".format(A) B = "{:.2f}".format(B) Sum = "{:.2f}".format(Sum) # setting text to the label self.result.setText("A = " + str(A) + ", B = " + str(B) + " and Sum = " + str(Sum)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
PyQt-exercise
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Selecting rows in pandas DataFrame based on conditions
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n10 Jul, 2020"
},
{
"code": null,
"e": 24622,
"s": 24292,
"text": "In this article we will see how we can create a golden ratio calculator using PyQt5. In mathematics, two quantities are in the golden ratio if their ratio is the same as the ratio of their sum to the larger of the two quantities. The value of golden ratio is 1.61803398875. Below is how the golden ratio calculator will look like"
},
{
"code": null,
"e": 24868,
"s": 24622,
"text": "PyQt5 is cross-platform GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided by this library. Below is the command to install the PyQt5"
},
{
"code": null,
"e": 24886,
"s": 24868,
"text": "pip install PyQt5"
},
{
"code": null,
"e": 24945,
"s": 24886,
"text": "Concept :Below is the formula for calculating golden ratio"
},
{
"code": null,
"e": 24981,
"s": 24945,
"text": "A / B = (A + B) / A = golden_ratio\n"
},
{
"code": null,
"e": 25108,
"s": 24981,
"text": "Here A is the larger length and B is the shorter i.e second part of the length and the value of golden ratio is 1.61803398875."
},
{
"code": null,
"e": 25455,
"s": 25108,
"text": "GUI Implementation Steps :1. Create a heading label that display the calculator name2. Create three radio buttons for first, second and sum of the lengths3. Create three spin boxes for user to enter the specific length4. Create push button for calculating the other values according tot golden ratio5. Create a label to show the calculated values"
},
{
"code": null,
"e": 26218,
"s": 25455,
"text": "Back-End Implementation :1. Initially make all the spin boxes disable2. Add same action to all the three radio button3. Inside the radio button method which radio button is checked4. According to the checked radio button make the corresponding spin box enable and make the rest of the spin box disable5. Also assign the flag values according to the selected radio button6. Add same action to all three spin boxes7. Inside the spin box action check which spin box is enabled and make other spin box values zero8. Add action to the push button9. Inside the push button action check the flag according to the flag with the help of golden ratio formula calculate the other two lengths10. Format the calculated values and show the values with the help of result label"
},
{
"code": null,
"e": 26246,
"s": 26218,
"text": "Below is the implementation"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import datetimeimport sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # width of window self.w_width = 400 # height of window self.w_height = 430 # setting geometry self.setGeometry(100, 100, self.w_width, self.w_height) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating head label head = QLabel(\"Golden Ratio Calculator\", self) head.setWordWrap(True) # setting geometry to the head head.setGeometry(0, 10, 400, 60) # font font = QFont('Times', 15) font.setBold(True) font.setItalic(True) font.setUnderline(True) # setting font to the head head.setFont(font) # setting alignment of the head head.setAlignment(Qt.AlignCenter) # setting color effect to the head color = QGraphicsColorizeEffect(self) color.setColor(Qt.darkCyan) head.setGraphicsEffect(color) # creating a radio button self.length1 = QRadioButton(\"First Length (A)\", self) # setting geometry self.length1.setGeometry(50, 90, 140, 40) # setting font self.length1.setFont(QFont('Times', 9)) # creating a spin box self.l1 = QSpinBox(self) self.l1.setMaximum(999999) # setting geometry to the spin box self.l1.setGeometry(200, 90, 160, 40) # setting font self.l1.setFont(QFont('Times', 9)) # setting alignment self.l1.setAlignment(Qt.AlignCenter) # creating a radio button self.length2 = QRadioButton(\"Second Length (B)\", self) # setting geometry self.length2.setGeometry(50, 150, 145, 40) # setting font self.length2.setFont(QFont('Times', 9)) # creating a spin box self.l2 = QSpinBox(self) self.l2.setMaximum(999999) # setting geometry to the spin box self.l2.setGeometry(200, 150, 160, 40) # setting font self.l2.setFont(QFont('Times', 9)) # setting alignment self.l2.setAlignment(Qt.AlignCenter) # creating a radio button self.length_sum = QRadioButton(\"First + Second \", self) # setting geometry self.length_sum.setGeometry(50, 200, 140, 40) # setting font self.length_sum.setFont(QFont('Times', 9)) # creating a spin box self.l_s = QSpinBox(self) self.l_s.setMaximum(999999) # setting geometry to the spin box self.l_s.setGeometry(200, 200, 160, 40) # setting font self.l_s.setFont(QFont('Times', 9)) # setting alignment self.l_s.setAlignment(Qt.AlignCenter) # adding same action to all the radio button self.length1.clicked.connect(self.radio_method) self.length2.clicked.connect(self.radio_method) self.length_sum.clicked.connect(self.radio_method) # adding same action to all the spin box self.l1.valueChanged.connect(self.spin_method) self.l2.valueChanged.connect(self.spin_method) self.l_s.valueChanged.connect(self.spin_method) # making all the spin box disabled self.l1.setDisabled(True) self.l2.setDisabled(True) self.l_s.setDisabled(True) # creating a push button calculate = QPushButton(\"Calculate\", self) # setting geometry to the push button calculate.setGeometry(100, 270, 200, 40) # adding action to the button calculate.clicked.connect(self.calculate) # adding color effect to the push button color = QGraphicsColorizeEffect() color.setColor(Qt.blue) calculate.setGraphicsEffect(color) # creating a label to show result self.result = QLabel(self) # setting properties to result label self.result.setAlignment(Qt.AlignCenter) # setting geometry self.result.setGeometry(50, 330, 300, 70) # making it multi line self.result.setWordWrap(True) # setting stylesheet # adding border and background self.result.setStyleSheet(\"QLabel\" \"{\" \"border : 3px solid black;\" \"background : white;\" \"}\") # setting font self.result.setFont(QFont('Arial', 11)) # method called by the radio buttons def radio_method(self): # checking who is checked and who is unchecked # if first radio button is checked if self.length1.isChecked(): # making first spin box enable self.l1.setEnabled(True) # making rest two spin box disable self.l2.setDisabled(True) self.l_s.setDisabled(True) # assigning flags self.check1 = True self.check2 = False self.check_sum = False elif self.length2.isChecked(): # making second spin box enable self.l2.setEnabled(True) # making rest two spin box disable self.l1.setDisabled(True) self.l_s.setDisabled(True) # assigning flags self.check1 = False self.check2 = True self.check_sum = False elif self.length_sum.isChecked(): # making third spin box enable self.l_s.setEnabled(True) # making rest two spin box disable self.l1.setDisabled(True) self.l2.setDisabled(True) # assigning flags self.check1 = False self.check2 = False self.check_sum = True def spin_method(self): # finding who called the method if self.l1.isEnabled(): # setting current values self.l2.setValue(0) self.l_s.setValue(0) elif self.l2.isEnabled(): # setting current values self.l1.setValue(0) self.l_s.setValue(0) else: # setting current values self.l2.setValue(0) self.l1.setValue(0) def calculate(self): golden = 1.61803398875 # if first value is selected if self.check1 == True: # getting spin box value A = self.l1.value() B = A / golden Sum = A + B elif self.check2 == True: # getting spin box value B = self.l2.value() A = B * golden Sum = A + B else: # getting spin box value Sum = self.l_s.value() A = Sum / golden B = Sum - A # formatting values upto two decimal A = \"{:.2f}\".format(A) B = \"{:.2f}\".format(B) Sum = \"{:.2f}\".format(Sum) # setting text to the label self.result.setText(\"A = \" + str(A) + \", B = \" + str(B) + \" and Sum = \" + str(Sum)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 33728,
"s": 26246,
"text": null
},
{
"code": null,
"e": 33737,
"s": 33728,
"text": "Output :"
},
{
"code": null,
"e": 33751,
"s": 33737,
"text": "PyQt-exercise"
},
{
"code": null,
"e": 33762,
"s": 33751,
"text": "Python-gui"
},
{
"code": null,
"e": 33774,
"s": 33762,
"text": "Python-PyQt"
},
{
"code": null,
"e": 33781,
"s": 33774,
"text": "Python"
},
{
"code": null,
"e": 33879,
"s": 33781,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33911,
"s": 33879,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 33953,
"s": 33911,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 34009,
"s": 33953,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 34051,
"s": 34009,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 34082,
"s": 34051,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 34104,
"s": 34082,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 34159,
"s": 34104,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 34198,
"s": 34159,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 34227,
"s": 34198,
"text": "Create a directory in Python"
}
] |
Destructors in C++ - GeeksforGeeks | 09 Sep, 2021
What is a destructor? Destructor is an instance member function which is invoked automatically whenever an object is going to be destroyed. Meaning, a destructor is the last function that is going to be called before an object is destroyed.
The thing is to be noted here, if the object is created by using new or the constructor uses new to allocate memory which resides in the heap memory or the free store, the destructor should use delete to free the memory.
Syntax:
~constructor-name();
Properties of Destructor:
Destructor function is automatically invoked when the objects are destroyed.
It cannot be declared static or const.
The destructor does not have arguments.
It has no return type not even void.
An object of a class with a Destructor cannot become a member of the union.
A destructor should be declared in the public section of the class.
The programmer cannot access the address of destructor.
When is destructor called? A destructor function is called automatically when the object goes out of scope: (1) the function ends (2) the program ends (3) a block containing local variables ends (4) a delete operator is called
How are destructors different from a normal member function? Destructors have same name as the class preceded by a tilde (~) Destructors don’t take any argument and don’t return anything
CPP
class String {private: char* s; int size; public: String(char*); // constructor ~String(); // destructor}; String::String(char* c){ size = strlen(c); s = new char[size + 1]; strcpy(s, c);}String::~String() { delete[] s; }
Can there be more than one destructor in a class? No, there can only one destructor in a class with classname preceded by ~, no parameters and no return type.
When do we need to write a user-defined destructor? If we do not write our own destructor in class, compiler creates a default destructor for us. The default destructor works fine unless we have dynamically allocated memory or pointer in class. When a class contains a pointer to memory allocated in class, we should write a destructor to release memory before the class instance is destroyed. This must be done to avoid memory leak.
Can a destructor be virtual? Yes, In fact, it is always a good idea to make destructors virtual in base class when we have a virtual function. See virtual destructor for more details. You may like to take a quiz on destructors.
Related Articles : Constructors in C++ Virtual Destructor Pure virtual destructor in C++Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
itskawal2000
pushapbadyal07
divyanshubargali
user_ax8z
cpp-destructor
C++
School Programming
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
std::sort() in C++ STL
Bitwise Operators in C/C++
Socket Programming in C/C++
Python Dictionary
Reverse a string in Java
Interfaces in Java
Overriding in Java
Different ways of Reading a text file in Java | [
{
"code": null,
"e": 26960,
"s": 26932,
"text": "\n09 Sep, 2021"
},
{
"code": null,
"e": 27201,
"s": 26960,
"text": "What is a destructor? Destructor is an instance member function which is invoked automatically whenever an object is going to be destroyed. Meaning, a destructor is the last function that is going to be called before an object is destroyed."
},
{
"code": null,
"e": 27425,
"s": 27201,
"text": "The thing is to be noted here, if the object is created by using new or the constructor uses new to allocate memory which resides in the heap memory or the free store, the destructor should use delete to free the memory. "
},
{
"code": null,
"e": 27433,
"s": 27425,
"text": "Syntax:"
},
{
"code": null,
"e": 27454,
"s": 27433,
"text": "~constructor-name();"
},
{
"code": null,
"e": 27480,
"s": 27454,
"text": "Properties of Destructor:"
},
{
"code": null,
"e": 27557,
"s": 27480,
"text": "Destructor function is automatically invoked when the objects are destroyed."
},
{
"code": null,
"e": 27596,
"s": 27557,
"text": "It cannot be declared static or const."
},
{
"code": null,
"e": 27636,
"s": 27596,
"text": "The destructor does not have arguments."
},
{
"code": null,
"e": 27673,
"s": 27636,
"text": "It has no return type not even void."
},
{
"code": null,
"e": 27749,
"s": 27673,
"text": "An object of a class with a Destructor cannot become a member of the union."
},
{
"code": null,
"e": 27817,
"s": 27749,
"text": "A destructor should be declared in the public section of the class."
},
{
"code": null,
"e": 27873,
"s": 27817,
"text": "The programmer cannot access the address of destructor."
},
{
"code": null,
"e": 28102,
"s": 27873,
"text": "When is destructor called? A destructor function is called automatically when the object goes out of scope: (1) the function ends (2) the program ends (3) a block containing local variables ends (4) a delete operator is called "
},
{
"code": null,
"e": 28289,
"s": 28102,
"text": "How are destructors different from a normal member function? Destructors have same name as the class preceded by a tilde (~) Destructors don’t take any argument and don’t return anything"
},
{
"code": null,
"e": 28293,
"s": 28289,
"text": "CPP"
},
{
"code": "class String {private: char* s; int size; public: String(char*); // constructor ~String(); // destructor}; String::String(char* c){ size = strlen(c); s = new char[size + 1]; strcpy(s, c);}String::~String() { delete[] s; }",
"e": 28536,
"s": 28293,
"text": null
},
{
"code": null,
"e": 28695,
"s": 28536,
"text": "Can there be more than one destructor in a class? No, there can only one destructor in a class with classname preceded by ~, no parameters and no return type."
},
{
"code": null,
"e": 29129,
"s": 28695,
"text": "When do we need to write a user-defined destructor? If we do not write our own destructor in class, compiler creates a default destructor for us. The default destructor works fine unless we have dynamically allocated memory or pointer in class. When a class contains a pointer to memory allocated in class, we should write a destructor to release memory before the class instance is destroyed. This must be done to avoid memory leak."
},
{
"code": null,
"e": 29357,
"s": 29129,
"text": "Can a destructor be virtual? Yes, In fact, it is always a good idea to make destructors virtual in base class when we have a virtual function. See virtual destructor for more details. You may like to take a quiz on destructors."
},
{
"code": null,
"e": 29570,
"s": 29357,
"text": "Related Articles : Constructors in C++ Virtual Destructor Pure virtual destructor in C++Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 29583,
"s": 29570,
"text": "itskawal2000"
},
{
"code": null,
"e": 29598,
"s": 29583,
"text": "pushapbadyal07"
},
{
"code": null,
"e": 29615,
"s": 29598,
"text": "divyanshubargali"
},
{
"code": null,
"e": 29625,
"s": 29615,
"text": "user_ax8z"
},
{
"code": null,
"e": 29640,
"s": 29625,
"text": "cpp-destructor"
},
{
"code": null,
"e": 29644,
"s": 29640,
"text": "C++"
},
{
"code": null,
"e": 29663,
"s": 29644,
"text": "School Programming"
},
{
"code": null,
"e": 29667,
"s": 29663,
"text": "CPP"
},
{
"code": null,
"e": 29765,
"s": 29667,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29783,
"s": 29765,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 29829,
"s": 29783,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 29852,
"s": 29829,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 29879,
"s": 29852,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 29907,
"s": 29879,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 29925,
"s": 29907,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29950,
"s": 29925,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 29969,
"s": 29950,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 29988,
"s": 29969,
"text": "Overriding in Java"
}
] |
How many ways to call garbage collector (GC) in Java?
| The garbage collection in Java is carried by a daemon thread called Garbage Collector(GC). Instead of waiting until JVM to run a garbage collector we can request JVM to run the garbage collector. There is no guarantee whether the JVM will accept our request or not.
In Java, we can call the garbage collector manually in two ways
By using System class
By using Runtime class
System class has a static method gc(), which is used to request JVM to call garbage collector.
public class SystemClassTest {
public static void main(String[] args){
SystemClassTest test = new SystemClassTest();
test = null;
System.gc();
}
public void finalize() {
System.out.println("Garbage collected");
}
}
Garbage collected
Runtime is a singleton class in Java and we can get a runtime object using the getRuntime() method. The gc() method is from Runtime class and it is an instance method.
public class RuntimeClassTest {
public static void main(String[] args) {
RuntimeClassTest test = new RuntimeClassTest();
test = null;
Runtime.getRuntime().gc();
}
public void finalize() {
System.out.println("Garbage Collected");
}
}
Garbage collected | [
{
"code": null,
"e": 1328,
"s": 1062,
"text": "The garbage collection in Java is carried by a daemon thread called Garbage Collector(GC). Instead of waiting until JVM to run a garbage collector we can request JVM to run the garbage collector. There is no guarantee whether the JVM will accept our request or not."
},
{
"code": null,
"e": 1392,
"s": 1328,
"text": "In Java, we can call the garbage collector manually in two ways"
},
{
"code": null,
"e": 1414,
"s": 1392,
"text": "By using System class"
},
{
"code": null,
"e": 1437,
"s": 1414,
"text": "By using Runtime class"
},
{
"code": null,
"e": 1532,
"s": 1437,
"text": "System class has a static method gc(), which is used to request JVM to call garbage collector."
},
{
"code": null,
"e": 1783,
"s": 1532,
"text": "public class SystemClassTest {\n public static void main(String[] args){\n SystemClassTest test = new SystemClassTest();\n test = null;\n System.gc();\n }\n public void finalize() {\n System.out.println(\"Garbage collected\");\n }\n}"
},
{
"code": null,
"e": 1801,
"s": 1783,
"text": "Garbage collected"
},
{
"code": null,
"e": 1969,
"s": 1801,
"text": "Runtime is a singleton class in Java and we can get a runtime object using the getRuntime() method. The gc() method is from Runtime class and it is an instance method."
},
{
"code": null,
"e": 2238,
"s": 1969,
"text": "public class RuntimeClassTest {\n public static void main(String[] args) {\n RuntimeClassTest test = new RuntimeClassTest();\n test = null;\n Runtime.getRuntime().gc();\n }\n public void finalize() {\n System.out.println(\"Garbage Collected\");\n }\n}"
},
{
"code": null,
"e": 2256,
"s": 2238,
"text": "Garbage collected"
}
] |
Thirty Fast Text Pre-Processing Code and Benchmarks For Natural Language Processing | by Bruce H. Cottman, Ph.D. | Towards Data Science | Estimates state that 70%–85% of the world’s data is text (unstructured data) [1]. As a result, new deep learning language models (transformers) have caused explosive growth in industry applications [5,6.11].
This blog is not an article introducing you to Natural Language Processing. Instead, it assumes you are familiar with noise reduction and normalization of text. It covers text preprocessing up to producing tokens and lemmas from the text.
We stop at feeding the sequence of tokens into a Natural Language model.
The feeding of that sequence of tokens into a Natural Language model to accomplish a specific model task is not covered.
In production-grade Natural Language Processing (NLP), what is covered in this blog is that fast text pre-processing (noise cleaning and normalization) is critical.
I discuss packages we use for production-level NLP;I detail the production-level NLP preprocessing text tasks with python code and packages;Finally, I report benchmarks for NLP text pre-processing tasks.
I discuss packages we use for production-level NLP;
I detail the production-level NLP preprocessing text tasks with python code and packages;
Finally, I report benchmarks for NLP text pre-processing tasks.
We segment NLP into two major steps (for the convenience of this article):
Text pre-processing into tokens. We clean (noise removal) and then normalize the text. The goal is to transform the text into a corpus that any NLP model can use. A goal is rarely achieved until the introduction of the transformer [2].A corpus is an input of text preprocessed into a sequence of tokens into NLP models for training or prediction.
Text pre-processing into tokens. We clean (noise removal) and then normalize the text. The goal is to transform the text into a corpus that any NLP model can use. A goal is rarely achieved until the introduction of the transformer [2].
A corpus is an input of text preprocessed into a sequence of tokens into NLP models for training or prediction.
The rest of this article is devoted to noise removal text and normalization of text into tokens/lemmas (Step 1: text pre-processing).
Noise removal deletes or transforms things in the text that degrade the NLP task model.
Noise removal is usually an NLP task-dependent. For example, e-mail may or may not be removed if it is a text classification task or a text redaction task.
I show replacement or removal of the noise.
Normalization of the corpus is transforming the text into a common form. The most frequent example is normalization by transforming all characters to lowercase.
In follow-on blogs, we will cover different deep learning language models and Transformers (Steps 2-n) fed by the corpus token/lemma stream.
There are many NLP packages available. We use spaCy [2], textacy [4], Hugging Face transformers [5], and regex [7] in most of our NLP production applications. The following are some of the “factoids” we used in our decision process.
Note: The following “factoids” may be biased. That is why we refer to them as “factoids.”
NLTK [3]
NLTK is a string processing library. All the tools take strings as input and return strings or lists of strings as output [3].
NLTK is a good choice if you want to explore different NLP with a corpus whose length is less than a million words.
NLTK is a bad choice if you want to go into production with your NLP application [3].
The use of regex is pervasive throughout our text-preprocessing code. Regex is a fast string processor. Regex, in various forms, has been around for over 50 years. Regex support is part of the standard library of Java and Python and is built into the syntax of others, including Perl and ECMAScript (JavaScript);
spaCy is a moderate choice if you want to research different NLP models with a corpus whose length is greater than a million words.
If you use a selection from spaCy [3], Hugging Face [5], fast.ai [13], and GPT-3 [6], then you are performing SOTA (state-of-the-art) research of different NLP models (my opinion at the time of writing this blog).
spaCy is a good choice if you want to go into production with your NLP application.
spaCy is an NLP library implemented both in Python and Cython. Because of the Cython, parts of spaCy are faster than if implemented in Python [3];
spacy is the fastest package we know of for NLP operations;
spacy is available for operating systems MS Windows, macOS, and Ubuntu [3];
spaCy runs natively on Nvidia GPUs [3];
explosion/spaCy has 16,900 stars on Github (7/22/2020);
spaCy has 138 public repository implementations on GitHub;
spaCy comes with pre-trained statistical models and word vectors;
spaCy transforms text into document objects, vocabulary objects, word-token objects, and other useful objects resulting from parsing the text ;
Doc class has several useful attributes and methods. Significantly, you can create new operations on these objects as well as extend a class with new attributes (adding to the spaCy pipeline);
spaCy features tokenization for 50+ languages;
We create long_, a long string with extra whitespace, emoji, email addresses, $ symbols, HTML tags, punctuation, and other text that may or may not be noise for the downstream NLP task and/or model.
MULPIPIER = int(3.8e3)text_l = 300%time long_s = ':( 😻 😈 #google +1 608-444-0000 08-444-0004 608-444-00003 ext. 508 'long_s += ' 888 eihtg DoD Fee https://medium.com/ #hash ## Document Title</title> 'long_s += ':( cat- \n nip'long_s += ' immed- \n natedly <html><h2>2nd levelheading</h2></html> . , 'long_s += '# [email protected] [email protected] can\'t Be a ckunk. $4 $123,456 won\'t seven 'long_s +=' $Shine $$beighty?$ 'long_s *= MULPIPIERprint('size: {:g} {}'.format(len(long_s),long_s[:text_l]))
output =>
CPU times: user 3 μs, sys: 1 μs, total: 4 μsWall time: 8.11 μssize: 1.159e+06 :( 😻 😈 #google +1 608-444-0000 08-444-0004 608-444-00003 ext. 508 888 eihtg DoD Fee https://medium.com/ #hash ## Document Title</title> :( cat- nip immed- natedly <html><h2>2nd levelheading</h2></html> . , # [email protected] [email protected] can't Be a ckunk. $4 $123,456 won't seven $Shine $$beigh
A string, long_s of 1.159 million characters is created in 8.11 μs.
All benchmarks are run within a Docker container on MacOS Version 14.0 (14.0).
Model Name: Mac ProProcessor Name: 12-Core Intel Xeon E5Processor Speed: 2.7 GHzTotal Number of Cores: 24L2 Cache (per Core): 256 KBL3 Cache: 30 MBHyper-Threading Technology: EnabledMemory: 64 GB
Note: Corpus/text pre-processing is dependent on the end-point NLP analysis task. Sentiment Analysis requires different corpus/text pre-processing steps than document redaction. The corpus/text pre-processing steps given here are for a range of NLP analysis tasks. Usually, a subset of the given corpus/text pre-processing steps is needed for each NLP task. Also, some of the required corpus/text pre-processing steps may not be given here.
from textacy.preprocessing.replace import replace_hashtags%time text = replace_hashtags(long_s,replace_with= '_HASH_')print('size: {:g} {}'.format(len(text),text[:text_l])))
output =>
CPU times: user 223 ms, sys: 66 μs, total: 223 msWall time: 223 mssize: 1.159e+06 :( 😻 😈 _HASH_ +1 608-444-0000 08-444-0004 608-444-00003 ext. 508 888 eihtg DoD Fee https://medium.com/ _HASH_ ## Document Title</title> :( cat- nip immed- natedly <html><h2>2nd levelheading</h2></html> . , # [email protected] [email protected] can't Be a ckunk. $4 $123,456 won't seven $Shine $$beigh
Notice that #google and #hash are swapped with_HASH_,and ##and _# are untouched. A million characters were processed in 200 ms. Fast enough for a big corpus of a billion characters (example: web server log).
from textacy.preprocessing.replace import replace_hashtags%time text = replace_hashtags(long_s,replace_with= '')print('size: {:g} {}'.format(len(text),text[:text_l]))
output =>
CPU times: user 219 ms, sys: 0 ns, total: 219 msWall time: 220 mssize: 1.1134e+06 :( 😻 😈 +1 608-444-0000 08-444-0004 608-444-00003 ext. 508 888 eihtg DoD Fee https://medium.com/ ## Document Title</title> :( cat- nip immed- natedly <html><h2>2nd levelheading</h2></html> . , # [email protected] [email protected] can't Be a ckunk. $4 $123,456 won't seven $Shine $$beighty?$
Notice that #google and #hash are removed and ##,and _# are untouched. A million characters were processed in 200 ms.
from textacy.preprocessing.replace import replace_phone_numbers%time text = replace_phone_numbers(long_s,replace_with= '_PHONE_')print('size: {:g} {}'.format(len(text),text[:text_l]))
output =>
CPU times: user 384 ms, sys: 1.59 ms, total: 386 msWall time: 383 mssize: 1.0792e+06 :( 😻 😈 _PHONE_ 08-_PHONE_ 608-444-00003 ext. 508 888 eihtg
Notice phone number 08-444-0004 and 608-444-00003 ext. 508 were not transformed.
RE_PHONE_NUMBER: Pattern = re.compile( # core components of a phone number r"(?:^|(?<=[^\w)]))(\+?1[ .-]?)?(\(?\d{2,3}\)?[ .-]?)?(\d{2,3}[ .-]?\d{2,5})" # extensions, etc. r"(\s?(?:ext\.?|[#x-])\s?\d{2,6})?(?:$|(?=\W))", flags=re.UNICODE | re.IGNORECASE)text = RE_PHONE_NUMBER.sub('_PHoNE_', long_s)print('size: {:g} {}'.format(len(text),text[:text_l]))
output =>
CPU times: user 353 ms, sys: 0 ns, total: 353 msWall time: 350 mssize: 1.0108e+06 :( 😻 😈 _PHoNE_ _PHoNE_ _PHoNE_ 888 eihtg DoD Fee https://medium.com/ ## Document Title</title> :( cat- nip immed- natedly <html><h2>2nd levelheading</h2></html> . , # [email protected] [email protected] can't Be a ckunk. $4 $123,456 won't seven $Shine $$beighty?$
Notice phone number 08-444-0004 and 608-444-00003 ext. 508 were transformed. A million characters were processed in 350 ms.
Using the improved RE_PHONE_NUMBER pattern, we put '' in for 'PHoNE' to remove phone numbers from the corpus.
text = RE_PHONE_NUMBER.sub('', long_s)print('size: {:g} {}'.format(len(text),text[:text_l]))
output =>
CPU times: user 353 ms, sys: 459 μs, total: 353 msWall time: 351 mssize: 931000 :( 😻 😈 888 eihtg DoD Fee https://medium.com/ ## Document Title</title> :( cat- nip immed- natedly <html><h2>2nd levelheading</h2></html> . , # [email protected] [email protected] can't Be a ckunk. $4 $123,456 won't seven $Shine $$beighty?$
A million characters were processed in 375 ms.
I admit removing HTML metadata is my favorite. Not because I like the task, but because I screen-scrape frequently. A lot of useful data resides on an IBM mainframe, VAX-780 (huh?), or whatever terminal-emulation that results in an HTML-based report.
These techniques of web scraping of reports generate text that has HTML tags. However, HTML tags are typically considered noise as they are parts of the text with little or no value in the follow-on NLP task.
Remember, we created a test string (long_s) a little over million characters long with some HTML tags. We remove the HTML tags using BeautifulSoup.
from bs4 import BeautifulSoup%time long_s = BeautifulSoup(long_s,'html.parser').get_text()print('size: {:g} {}'.format(len(long_s),long_s[:text_l])))
output =>
CPU times: user 954 ms, sys: 17.7 ms, total: 971 msWall time: 971 mssize: 817000 :( 😻 😈 888 eihtg DoD Fee https://medium.com/ ## Document Title :( cat- nip immed- natedly 2nd levelheading
The result is that BeautifulSoup can remove over 7,000 HTML tags in a million-character corpus in one second. Scaling linearly, a billion-character corpus, about 200 million words, or approximately 2000 books, would require about 200 seconds.
The rate for HTML tag removal byBeautifulSoup is about 0. 1 second per book. An acceptable rate for our production requirements.
I only benchmark BeautifulSoup. If you know of a competitive alternative method, please let me know.
Note: The compute times you get maybe multiples of time longer or shorter if you are using the cloud or Spark.
The currency symbols “[$¢£¤¥ƒ֏؋৲৳૱௹฿៛M元円圆圓ریال\u20A0-\u20C0] “ are replaced with _CUR_using the textacy package:
%time textr = textacy.preprocessing.replace.replace_currency_symbols(long_s)print('size: {:g} {}'.format(len(textr),textr[:text_l]))
output =>
CPU times: user 31.2 ms, sys: 1.67 ms, total: 32.9 msWall time: 33.7 mssize: 908200 :( 😻 😈 888 eihtg DoD Fee https://medium.com/ ## Document Title :( cat- nip immed- natedly 2nd levelheading . , # [email protected] [email protected] can't Be a ckunk. _CUR_4 _CUR_123,456 won't seven _CUR_Shine _CUR__CUR_beighty?_CUR_
Note: The option textacy replace_<something> enables you to specify the replacement text. _CUR_ is the default substitution text for replace_currency_symbols.
You may have the currency symbol $ in your text. In this case, you can use a regex:
%time text = re.sub('\$', '_DOL_', long_s)print('size: {:g} {}'.format(len(text),text[:250]))
output =>
CPU times: user 8.06 ms, sys: 0 ns, total: 8.06 msWall time: 8.25 mssize: 1.3262e+06 :( 😻 😈 #google +1 608-444-0000 08-444-0004 608-444-00003 ext. 508 888 eihtg DoD Fee https://medium.com/ #hash ## <html><title>Document Title</title></html> :( cat- nip immed- natedly <html><h2>2nd levelheading</h2></html> . , # [email protected] [email protected] can't Be a ckunk. _DOL_4 _DOL_123,456 won't seven _DOL_Shine _DOL__DOL_beighty?_DOL_ :
Note: All symbol $ in your text will be removed. Don't use it if you have LaTex or any text where multiple symbols $ are used.
from textacy.preprocessing.replace import replace_urls%time text = replace_urls(long_s,replace_with= '_URL_')print('size: {:g} {}'.format(len(text),text[:text_l]))
output =>
CPU times: user 649 ms, sys: 112 μs, total: 649 msWall time: 646 mssize: 763800 :( 😻 😈 888 eihtg DoD Fee _URL_ ## Document Title :(
from textacy.preprocessing.replace import replace_urls%time text = replace_urls(long_s,replace_with= '')print('size: {:g} {}'.format(len(text),text[:text_l]))
output =>
CPU times: user 633 ms, sys: 1.35 ms, total: 635 msWall time: 630 mssize: 744800 :( 😻 😈 888 eihtg DoD Fee ## Document Title :(
The rate for URL replace, or removal is about 4,000 URLs per 1 million characters per second. Fast enough for 10 books in a corpus.
%time text = textacy.preprocessing.replace.replace_emails(long_s)print('size: {:g} {}'.format(len(text),text[:text_l]))
output =>
CPU times: user 406 ms, sys: 125 μs, total: 406 msWall time: 402 mssize: 725800 :( 😻 😈 888 eihtg DoD Fee ## Document Title :( cat- nip immed- natedly 2nd levelheading . , # _EMAIL_ _EMAIL_ can't Be a ckunk. $4 $123,456 won't seven $Shine $$beighty?$
The rate for email reference replace is about 8,000 emails per 1.7 million characters per second. Fast enough for 17 books in a corpus.
from textacy.preprocessing.replace import replace_emails%time text = textacy.preprocessing.replace.replace_emails(long_s,replace_with= '')print('size: {:g} {}'.format(len(text),text[:text_l]))
output =>
CPU times: user 413 ms, sys: 1.68 ms, total: 415 msWall time: 412 mssize: 672600 :( 😻 😈 888 eihtg DoD Fee ## Document Title :( cat- nip immed- natedly 2nd levelheading . , # can't Be a ckunk. $4 $123,456 won't seven $Shine $$beighty?$
The rate for email reference removal is about 8,000 emails per 1.1 million characters per second. Fast enough for 11 books in a corpus.
from textacy.preprocessing.normalize import normalize_hyphenated_words%time long_s = normalize_hyphenated_words(long_s)print('size: {:g} {}'.format(len(long_s),long_s[:text_l])))
output =>
CPU times: user 186 ms, sys: 4.58 ms, total: 191 msWall time: 190 mssize: 642200 :( 😻 😈 888 eihtg DoD Fee ## Document Title :( catnip immednatedly
Approximately 8,000 hyphenated words, cat — nip and immed- iately (misspelled) were corrected in a corpus of 640,000 characters in 190 ms or about 3 million per second.
### - **all characters to lower case;**%time long_s = long_s.lower()print('size: {:g} {}'.format(len(long_s),long_s[:text_l]))
output =>
CPU times: user 4.82 ms, sys: 953 μs, total: 5.77 msWall time: 5.97 mssize: 642200:( 😻 😈 888 eihtg dod fee ## document title :( catnip immednatedly 2nd levelheading . , # can't be a ckunk. $4 $123,456 won't seven $shine $$beighty?$
I only benchmark the .lower Python function. The rate for lower case transformation by.lower() of a Python string of a million characters is about 6 ms. A rate that far exceeds our production rate requirements.
%time text = re.sub(' +', ' ', long_s)print('size: {:g} {}'.format(len(text),text[:text_l]))
output =>
CPU times: user 44.9 ms, sys: 2.89 ms, total: 47.8 msWall time: 47.8 mssize: 570000 :( 😻 😈 888 eihtg dod fee ## document title :( catnip immednatedly 2nd levelheading . , # can't be a ckunk. $4 $123,456 won't seven $shine $$beighty?$
The rate is about 0.1 seconds for 1 million characters.
from textacy.preprocessing.normalize import normalize_whitespace%time text= normalize_whitespace(long_s)print('size: {:g} {}'.format(len(text),text[:text_l]))
output =>
CPU times: user 199 ms, sys: 3.06 ms, total: 203 msWall time: 201 mssize: 569999 :( 😻 😈 888 eihtg dod fee ## document title :( catnip immednatedly 2nd levelheading . , # can't be a ckunk. $4 $123,456 won't seven $shine $$beighty?$
normalize_whitespce is 5x slower but more general. For safety in production, we use normalize_whitespce.To date, we do not think we had any problems with faster regex.
from textacy.preprocessing.remove import remove_punctuation%time text = remove_punctuation(long_s, marks=',.#$?')print('size: {:g} {}'.format(len(text),text[:text_l]))
output =>
CPU times: user 34.5 ms, sys: 4.82 ms, total: 39.3 msWall time: 39.3 mssize: 558599 :( 😻 😈 888 eihtg dod fee document title :( catnip immednatedly 2nd levelheading can't be a ckunk 4 123 456 won't seven shine beighty
To text pre-process with spaCy, we transform the text into a corpus Doc object. We can then use the sequence of word tokens objects of which a Doc object consists. Each token consists of attributes (discussed above) that we use later in this article to pre-process the corpus.
Our text pre-processing end goal (usually) is to produce tokens that feed into our NLP models.
spaCy reverses the stream of pre-processing text and then transforming text into tokens. spaCy creates a Doc of tokens. You then pre-process the tokens by their attributes.
The result is that parsing text into a Doc object is where the majority of computation lies. As we will see, pre-processing the sequence of tokens by their attributes is fast.
import en_core_web_lgnlp = en_core_web_lg.load()do = nlp.disable_pipes(["tagger", "parser"])%time emoji = Emoji(nlp)nlp.max_length = len(long_s) + 10%time nlp.add_pipe(emoji, first=True)%time long_s_doc = nlp(long_s)print('size: {:g} {}'.format(len(long_s_doc),long_s_doc[:text_l]))
output =>
CPU times: user 303 ms, sys: 22.6 ms, total: 326 msWall time: 326 msCPU times: user 23 μs, sys: 0 ns, total: 23 μsWall time: 26.7 μsCPU times: user 7.22 s, sys: 1.89 s, total: 9.11 sWall time: 9.12 ssize: 129199 :( 😻 😈 888 eihtg dod fee document title :( catnip immednatedly 2nd levelheading can't be a ckunk 4 123 456 won't seven shine beighty
Creating the token sequence required 14,000 tokens per second. We will quite a speedup when we use NVIDIA GPU.
nlp.pipe_namesoutput =>['emoji', 'ner']
Note: The tokenizer is a “special” component and isn’t part of the regular pipeline. It also doesn’t show up in nlp.pipe_names. The reason is that there can only be one tokenizer, and while all other pipeline components take a Doc and return it, the tokenizer takes a string of text and turns it into a Doc. You can still customize the tokenizer. You can either create your ownTokenizer class from scratch or even replace it with an entirely custom function.
As we saw earlier, spaCy provides convenience methods for many other pre-processing tasks. It turns — for example, to remove stop words, you can reference the .is_stop attribute.
dir(token[0])output=>'ancestors', 'check_flag', 'children', 'cluster', 'conjuncts', 'dep', 'dep_', 'doc', 'ent_id', 'ent_id_', 'ent_iob', 'ent_iob_', 'ent_kb_id', 'ent_kb_id_', 'ent_type', 'ent_type_', 'get_extension', 'has_extension', 'has_vector', 'head', 'i', 'idx', 'is_alpha', 'is_ancestor', 'is_ascii', 'is_bracket', 'is_currency', 'is_digit', 'is_left_punct', 'is_lower', 'is_oov', 'is_punct', 'is_quote', 'is_right_punct', 'is_sent_end', 'is_sent_start', 'is_space', 'is_stop', 'is_title', 'is_upper', 'lang', 'lang_', 'left_edge', 'lefts', 'lemma', 'lemma_', 'lex_id', 'like_email', 'like_num', 'like_url', 'lower', 'lower_', 'morph', 'n_lefts', 'n_rights', 'nbor', 'norm', 'norm_', 'orth', 'orth_', 'pos', 'pos_', 'prefix', 'prefix_', 'prob', 'rank', 'remove_extension', 'right_edge', 'rights', 'sent', 'sent_start', 'sentiment', 'set_extension', 'shape', 'shape_', 'similarity', 'string', 'subtree', 'suffix', 'suffix_', 'tag', 'tag_', 'tensor', 'text', 'text_with_ws', 'vector', 'vector_norm', 'vocab', 'whitespace_']
Attributes added by emoji and new.
dir(long_s_doc[0]._)output =>['emoji_desc', 'get', 'has', 'is_emoji', 'set', 'trf_alignment', 'trf_all_attentions', 'trf_all_hidden_states', 'trf_d_all_attentions', 'trf_d_all_hidden_states', 'trf_d_last_hidden_state', 'trf_d_pooler_output', 'trf_end', 'trf_last_hidden_state', 'trf_pooler_output', 'trf_separator', 'trf_start', 'trf_word_pieces', 'trf_word_pieces_'
I show spaCy performing preprocessing that results in a Python string corpus. Then, the corpus is used to create a new sequence of spaCy tokens (Doc).
There is a faster way to accomplish spaCy preprocessing with spaCy pipeline extensions [2], which I show in an upcoming blog.
EMOJI Sentiment Score is not a text preprocessor in the classic sense.
However, we find that emoji almost always is the dominating text in a document.
For example, two similar phrases from legal notes e-mail with opposite sentiment.
The client was challenging. :(The client was difficult. :)
We calculate the only emoji when present in a note or e-mail.
%time scl = [EMOJI_TO_SENTIMENT_VALUE[token.text] for token in long_s_doc if (token.text in EMOJI_TO_SENTIMENT_VALUE)]len(scl), sum(scl), sum(scl)/len(scl)
output =>
CPU times: user 179 ms, sys: 0 ns, total: 179 msWall time: 178 ms(15200, 1090.7019922523152, 0.07175671001659968)
The sentiment was 0.07 (neutral) for 0.5 million characters “note” with 15,200 emojis and emojicons in 178 ms. A fast sentiment analysis calculation!
You can remove emoji using the spaCy pipeline add-on
%time long_s_doc_no_emojicon = [token for token in long_s_doc if token._.is_emoji == False]print('size: {:g} {}'.format(len(long_s_doc_no_emojicon),long_s_doc_no_emojicon[:int(text_l/5)]))
output =>
CPU times: user 837 ms, sys: 4.98 ms, total: 842 msWall time: 841 mssize: 121599 [:(, 888, eihtg, dod, fee, , document, title, :(, catnip, immednatedly, 2nd, levelheading, , ca, n't, be, a, ckunk, , 4, , 123, 456, wo, n't, seven, , shine, , beighty, , :(, 888, eihtg, dod, fee, , document, title, :(, catnip, immednatedly, 2nd, levelheading, , ca, n't, be, a, ckunk, , 4, , 123, 456, wo, n't, seven, , shine, , beighty, , :(, 888, eihtg, dod, fee, ]
The emoji spacy pipeline addition detected the emojicons, 😻 😈, but missed :) and :(.
We developed EMOJI_TO_PHRASEto detect the emojicons, 😻 😈, and emojis, such as :) and :(. and removed them [8,9].
%time text = [token.text if (token.text in EMOJI_TO_PHRASE) == False \ else '' for token in long_s_doc]%time long_s = ' '.join(text)print('size: {:g} {}'.format(len(long_s),long_s[:text_l]))
output =>
CPU times: user 242 ms, sys: 3.76 ms, total: 245 msWall time: 245 msCPU times: user 3.37 ms, sys: 73 μs, total: 3.45 msWall time: 3.46 mssize: 569997 888 eihtg dod fee document title catnip immednatedly 2nd levelheading ca n't be a ckunk 4 123 456 wo n't seven shine beighty 888 eihtg dod fee document title catnip immednatedly 2nd levelheading ca n't be a ckunk 4 123 456 wo n't seven shine beighty 888 eihtg dod fee document title catnip imm
We can translate emojicon into a natural language phrase.
%time text = [token.text if token._.is_emoji == False else token._.emoji_desc for token in long_s_doc]%time long_s = ' '.join(text)print('size: {:g} {}'.format(len(long_s),long_s[:250]))
output =>
CPU times: user 1.07 s, sys: 7.54 ms, total: 1.07 sWall time: 1.07 sCPU times: user 3.78 ms, sys: 0 ns, total: 3.78 msWall time: 3.79 mssize: 794197 :( smiling cat face with heart-eyes smiling face with horns 888 eihtg dod fee document title :( catnip immednatedly 2nd levelheading ca n't be a ckunk 4 123 456 wo n't seven shine beighty
The emoji spaCy pipeline addition detected the emojicons, 😻 😈, but missed :) and :(.
We can translate emojicons into a natural language phrase.
%time text = [token.text if (token.text in EMOJI_TO_PHRASE) == False \ else EMOJI_TO_PHRASE[token.text] for token in long_s_doc]%time long_s = ' '.join(text)print('size: {:g} {}'.format(len(long_s),long_s[:text_l]))
output =>
CPU times: user 251 ms, sys: 5.57 ms, total: 256 msWall time: 255 msCPU times: user 3.54 ms, sys: 91 μs, total: 3.63 msWall time: 3.64 mssize: 904397 FROWNING FACE SMILING CAT FACE WITH HEART-SHAPED EYES SMILING FACE WITH HORNS 888 eihtg dod fee document title FROWNING FACE catnip immednatedly 2nd levelheading ca n't be a ckunk 4 123 456 wo n't seven shine beighty FROWNING FAC
Again. EMOJI_TO_PHRASE detected the emojicons, 😻 😈, and emoji, such as :) and :(. and substituted a phrase.
We will use symspell for spelling correction [14].
SymSpell, based on the Symmetric Delete spelling correction algorithm, just took 0.000033 seconds (edit distance 2) and 0.000180 seconds (edit distance 3) on an old MacBook Pro [14].
%time sym_spell_setup() %time tk = [check_spelling(token.text) for token in long_s_doc[0:99999]]%time long_s = ' '.join(tk)print('size: {:g} {}'.format(len(long_s),long_s[:250]))
output =>
CPU times: user 5.22 s, sys: 132 ms, total: 5.35 sWall time: 5.36 sCPU times: user 25 s, sys: 12.9 ms, total: 25 sWall time: 25.1 sCPU times: user 3.37 ms, sys: 42 μs, total: 3.41 msWall time: 3.42 mssize: 528259 FROWNING FACE SMILING CAT FACE WITH HEART a SHAPED EYES SMILING FACE WITH HORNS 888 eight do fee document title FROWNING FACE catnip immediately and levelheading a not be a chunk a of 123 456 to not seven of shine of eighty
Spell correction was accomplished for immednatedly, ckunk and beight. Correcting misspelled words is our largest computation. It required 30 seconds for 0.8 million characters.
%time token = [token.text if token.is_currency == False else '_CUR_' for token in long_s_doc]%time long_s = ' '.join(token)print('size: {:g} {}'.format(len(long_s),long_s[:text_l]))aa
Note: spacy removes all punctuation including :) emoji and emoticon. You can protect the emoticon with:
%time long_s_doc = [token for token in long_s_doc if token.is_punct == False or token._.is_emoji == True]print('size: {:g} {}'.format(len(long_s_doc),long_s_doc[:50]))
However, replace_currency_symbolsand regex ignores context and replaces any currency symbol. You may have multiple uses $ in your text and thus can not ignore context. In this case, you can use spaCy.
%time tk = [token.text if token.is_currency == False else '_CUR_' for token in long_s_doc]%time long_s = ' '.join(tk)print('size: {:g} {}'.format(len(long_s),long_s[:250]))
output =>
CPU times: user 366 ms, sys: 13.9 ms, total: 380 msWall time: 381 msCPU times: user 9.7 ms, sys: 0 ns, total: 9.7 msWall time: 9.57 mssize: 1.692e+06 😻 👍 🏿 < title > Document Title</title > :( < html><h2>2nd levelheading</h2></html > [email protected] [email protected] a$@ ca n't bc$$ ef$4 5 66 _CUR_ wo nt seven eihtg _CUR_ nine _CUR_ _CUR_ zer$ 😻 👍 🏿 < title > Document Title</title > :( < html><h2>2nd leve
%time tokens = [token for token in long_s_doc if not token.like_email]print('size: {:g} {}'.format(len(tokens),tokens[:int(text_l/3)]))
output =>
CPU times: user 52.7 ms, sys: 3.09 ms, total: 55.8 msWall time: 54.8 mssize: 99999
About 0.06 seconds for 1 million characters.
%time tokens = [token.text for token in long_s_doc if (token.pos_ not in ['SPACE','PUNCT'])]%time text = ' '.join(tokens)print('size: {:g} {}'.format(len(text),text[:text_l]))
NLP models (ex: logistic regression and transformers) and NLP tasks (Sentiment Analysis) continue to be added. Some benefit from stopword removal, and some will not. [2]
Note: We now only use different deep learning language models (transformers) and do not remove stopwords.
%time tokens = [token.text for token in long_s_doc if token.is_stop == False]%time long_s = ' '.join(tokens)print('size: {:g} {}'.format(len(long_s),long_s[:text_l]))
Lemmatization looks beyond word reduction and considers a language’s full vocabulary to apply a morphological analysis to words.
Lemmatization looks at the surrounding text to determine a given the word’s part of speech. It does not categorize phrases.
%time tokens = [token.lemma_ for token in long_s_doc]%time long_s = ' '.join(tokens)print('size: {:g} {}'.format(len(long_s),long_s[:text_l]))
output =>
CPU times: user 366 ms, sys: 13.9 ms, total: 380 msWall time: 381 msCPU times: user 9.7 ms, sys: 0 ns, total: 9.7 msWall time: 9.57 mssize: 1.692e+06 😻 👍 🏿 < title > Document Title</title > :( < html><h2>2nd levelheading</h2></html > [email protected] [email protected] a$@ ca n't bc$$ ef$4 5 66 _CUR_ wo nt seven eihtg _CUR_ nine _CUR_ _CUR_ zer$ 😻 👍 🏿 < title > Document Title</title > :( < html><h2>2nd leve
Note: Spacy does not have stemming. You can add if it is you want. Stemming does not work as well as Lemmazatation because Stemming does not consider context [2] (Why some researcher considers spacy “opinionated”).
Note: If you do not know Stemming, you can still be on the Survivor show. (my opinion)
Whatever the NLP task, you need to clean (pre-process) the data (text) into a corpus (document or set of documents) before it is input into any NLP model.
I adopt a text pre-processing framework that has three major categories of NLP text pre-processing:
Noise Removal
Noise Removal
Transform Unicode characters into text characters.
convert a document image into segmented image parts and text snippets [10];
extract data from a database and transform it into words;
remove markup and metadata in HTML, XML, JSON, .md, etc.;
remove extra whitespaces;
remove emoji or convert emoji into phases;
Remove or convert currency symbol, URLs, email addresses, phone numbers, hashtags, other identifying tokens;
The correct mis-spelling of words (tokens); [7]
Remove remaining unwanted punctuation;
...
2. Tokenization
They are splitting strings of text into smaller pieces, or “tokens.” Paragraphs segment into sentences, and sentences tokenize into words.
3. Normalization
Change all characters to lower case;
Remove English stop words, or whatever language the text is in;
Perform Lemmatization or Stemming.
The tasks listed in Noise Removal and Normalization can move back and forth. The categorical assignment is for explanatory convenience.
Note: We do not remove stop-words anymore. We found that our current NLP models have higher F1 scores when we leave in stop-words.
Note: Stop-word removal is expensive computationally. We found the best way to achieve faster stop-word removal was not to do it.
Note: We saw no significant change in Deep Learning NLP models’ speed with or without stop-word removal.
Note: The Noise Removal and Normalization lists are not exhaustive. These are some of the tasks I have encountered.
The latestu000e NLP Deep Learning models are more accurate than older models. However, Deep Learning models can be impractically slow to train and are still too slow for prediction. We show in a follow-on article how we speed up such production models.
Note: Stemming algorithms drop off the end of the beginning of the word, a list of common prefixes, and suffixes to create a base root word.
Lemmatization uses linguistic knowledge bases to get the correct roots of words. In addition, lemmatization performs morphological analysis of each word, which requires the overhead of creating a linguistic knowledge base for each language.
Note: Stemming is faster than lemmatization.
In practice, lemmatization yields better results than stemming in an NLP Deep Learning model. Stemming generally reduces precision accuracy, and increases recall accuracy because it injects semi-random noise when wrong.
medium.com
Our unique implementations, spaCy, and textacy are our current choice for short text preprocessing production fast use. If you don’t mind the big performance gap, I recommend using it for production purposes over NLTK’s implementation of Stanford’s NER.
In the next blogs, We see how performance changes using multi-processing, multithreading, Nvidia GPUs, and pySpark. Also, I will write about how and why our implementations, such as EMOJI_TO_PHRASEand EMOJI_TO_SENTIMENT_VALUEand or how to add emoji, emoticon, or any Unicode symbol.
Happy Natural Language Processing!
[1] How Much Data Do We Create Every Day? The Mind-Blowing Stats Everyone Should Read.
[2] Industrial-Strength Natural Language Processing; ] Turbo-charge your spaCy NLP pipeline.
corrected the piece3] NLTK 3.5 Documentation.
[4] Textacy: Text (Pre)-processing.
[5] Hugging Face.
[6] Language Models are Few-Shot Learners.
[7] re — Regular expression operations.
[8] Using millions of emoji occurrences to learn any-domain representations for detecting sentiment, emotion, and sarcasm.
[9] How I Built Emojitracker.
[10] Classifying e-commerce products based on images and text.
[11] DART: Open-Domain Structured Data Record to Text Generation.
[12] Adv-BERT: BERT is not robust on misspellings! Generating nature adversarial samples on BERT.
[13] fast.ai .
[14] 1000x faster Spelling Correction. | [
{
"code": null,
"e": 380,
"s": 172,
"text": "Estimates state that 70%–85% of the world’s data is text (unstructured data) [1]. As a result, new deep learning language models (transformers) have caused explosive growth in industry applications [5,6.11]."
},
{
"code": null,
"e": 619,
"s": 380,
"text": "This blog is not an article introducing you to Natural Language Processing. Instead, it assumes you are familiar with noise reduction and normalization of text. It covers text preprocessing up to producing tokens and lemmas from the text."
},
{
"code": null,
"e": 692,
"s": 619,
"text": "We stop at feeding the sequence of tokens into a Natural Language model."
},
{
"code": null,
"e": 813,
"s": 692,
"text": "The feeding of that sequence of tokens into a Natural Language model to accomplish a specific model task is not covered."
},
{
"code": null,
"e": 978,
"s": 813,
"text": "In production-grade Natural Language Processing (NLP), what is covered in this blog is that fast text pre-processing (noise cleaning and normalization) is critical."
},
{
"code": null,
"e": 1182,
"s": 978,
"text": "I discuss packages we use for production-level NLP;I detail the production-level NLP preprocessing text tasks with python code and packages;Finally, I report benchmarks for NLP text pre-processing tasks."
},
{
"code": null,
"e": 1234,
"s": 1182,
"text": "I discuss packages we use for production-level NLP;"
},
{
"code": null,
"e": 1324,
"s": 1234,
"text": "I detail the production-level NLP preprocessing text tasks with python code and packages;"
},
{
"code": null,
"e": 1388,
"s": 1324,
"text": "Finally, I report benchmarks for NLP text pre-processing tasks."
},
{
"code": null,
"e": 1463,
"s": 1388,
"text": "We segment NLP into two major steps (for the convenience of this article):"
},
{
"code": null,
"e": 1810,
"s": 1463,
"text": "Text pre-processing into tokens. We clean (noise removal) and then normalize the text. The goal is to transform the text into a corpus that any NLP model can use. A goal is rarely achieved until the introduction of the transformer [2].A corpus is an input of text preprocessed into a sequence of tokens into NLP models for training or prediction."
},
{
"code": null,
"e": 2046,
"s": 1810,
"text": "Text pre-processing into tokens. We clean (noise removal) and then normalize the text. The goal is to transform the text into a corpus that any NLP model can use. A goal is rarely achieved until the introduction of the transformer [2]."
},
{
"code": null,
"e": 2158,
"s": 2046,
"text": "A corpus is an input of text preprocessed into a sequence of tokens into NLP models for training or prediction."
},
{
"code": null,
"e": 2292,
"s": 2158,
"text": "The rest of this article is devoted to noise removal text and normalization of text into tokens/lemmas (Step 1: text pre-processing)."
},
{
"code": null,
"e": 2380,
"s": 2292,
"text": "Noise removal deletes or transforms things in the text that degrade the NLP task model."
},
{
"code": null,
"e": 2536,
"s": 2380,
"text": "Noise removal is usually an NLP task-dependent. For example, e-mail may or may not be removed if it is a text classification task or a text redaction task."
},
{
"code": null,
"e": 2580,
"s": 2536,
"text": "I show replacement or removal of the noise."
},
{
"code": null,
"e": 2741,
"s": 2580,
"text": "Normalization of the corpus is transforming the text into a common form. The most frequent example is normalization by transforming all characters to lowercase."
},
{
"code": null,
"e": 2882,
"s": 2741,
"text": "In follow-on blogs, we will cover different deep learning language models and Transformers (Steps 2-n) fed by the corpus token/lemma stream."
},
{
"code": null,
"e": 3115,
"s": 2882,
"text": "There are many NLP packages available. We use spaCy [2], textacy [4], Hugging Face transformers [5], and regex [7] in most of our NLP production applications. The following are some of the “factoids” we used in our decision process."
},
{
"code": null,
"e": 3205,
"s": 3115,
"text": "Note: The following “factoids” may be biased. That is why we refer to them as “factoids.”"
},
{
"code": null,
"e": 3214,
"s": 3205,
"text": "NLTK [3]"
},
{
"code": null,
"e": 3341,
"s": 3214,
"text": "NLTK is a string processing library. All the tools take strings as input and return strings or lists of strings as output [3]."
},
{
"code": null,
"e": 3457,
"s": 3341,
"text": "NLTK is a good choice if you want to explore different NLP with a corpus whose length is less than a million words."
},
{
"code": null,
"e": 3543,
"s": 3457,
"text": "NLTK is a bad choice if you want to go into production with your NLP application [3]."
},
{
"code": null,
"e": 3856,
"s": 3543,
"text": "The use of regex is pervasive throughout our text-preprocessing code. Regex is a fast string processor. Regex, in various forms, has been around for over 50 years. Regex support is part of the standard library of Java and Python and is built into the syntax of others, including Perl and ECMAScript (JavaScript);"
},
{
"code": null,
"e": 3988,
"s": 3856,
"text": "spaCy is a moderate choice if you want to research different NLP models with a corpus whose length is greater than a million words."
},
{
"code": null,
"e": 4202,
"s": 3988,
"text": "If you use a selection from spaCy [3], Hugging Face [5], fast.ai [13], and GPT-3 [6], then you are performing SOTA (state-of-the-art) research of different NLP models (my opinion at the time of writing this blog)."
},
{
"code": null,
"e": 4286,
"s": 4202,
"text": "spaCy is a good choice if you want to go into production with your NLP application."
},
{
"code": null,
"e": 4433,
"s": 4286,
"text": "spaCy is an NLP library implemented both in Python and Cython. Because of the Cython, parts of spaCy are faster than if implemented in Python [3];"
},
{
"code": null,
"e": 4493,
"s": 4433,
"text": "spacy is the fastest package we know of for NLP operations;"
},
{
"code": null,
"e": 4569,
"s": 4493,
"text": "spacy is available for operating systems MS Windows, macOS, and Ubuntu [3];"
},
{
"code": null,
"e": 4609,
"s": 4569,
"text": "spaCy runs natively on Nvidia GPUs [3];"
},
{
"code": null,
"e": 4665,
"s": 4609,
"text": "explosion/spaCy has 16,900 stars on Github (7/22/2020);"
},
{
"code": null,
"e": 4724,
"s": 4665,
"text": "spaCy has 138 public repository implementations on GitHub;"
},
{
"code": null,
"e": 4790,
"s": 4724,
"text": "spaCy comes with pre-trained statistical models and word vectors;"
},
{
"code": null,
"e": 4934,
"s": 4790,
"text": "spaCy transforms text into document objects, vocabulary objects, word-token objects, and other useful objects resulting from parsing the text ;"
},
{
"code": null,
"e": 5127,
"s": 4934,
"text": "Doc class has several useful attributes and methods. Significantly, you can create new operations on these objects as well as extend a class with new attributes (adding to the spaCy pipeline);"
},
{
"code": null,
"e": 5174,
"s": 5127,
"text": "spaCy features tokenization for 50+ languages;"
},
{
"code": null,
"e": 5373,
"s": 5174,
"text": "We create long_, a long string with extra whitespace, emoji, email addresses, $ symbols, HTML tags, punctuation, and other text that may or may not be noise for the downstream NLP task and/or model."
},
{
"code": null,
"e": 5871,
"s": 5373,
"text": "MULPIPIER = int(3.8e3)text_l = 300%time long_s = ':( 😻 😈 #google +1 608-444-0000 08-444-0004 608-444-00003 ext. 508 'long_s += ' 888 eihtg DoD Fee https://medium.com/ #hash ## Document Title</title> 'long_s += ':( cat- \\n nip'long_s += ' immed- \\n natedly <html><h2>2nd levelheading</h2></html> . , 'long_s += '# [email protected] [email protected] can\\'t Be a ckunk. $4 $123,456 won\\'t seven 'long_s +=' $Shine $$beighty?$ 'long_s *= MULPIPIERprint('size: {:g} {}'.format(len(long_s),long_s[:text_l]))"
},
{
"code": null,
"e": 5881,
"s": 5871,
"text": "output =>"
},
{
"code": null,
"e": 6258,
"s": 5881,
"text": "CPU times: user 3 μs, sys: 1 μs, total: 4 μsWall time: 8.11 μssize: 1.159e+06 :( 😻 😈 #google +1 608-444-0000 08-444-0004 608-444-00003 ext. 508 888 eihtg DoD Fee https://medium.com/ #hash ## Document Title</title> :( cat- nip immed- natedly <html><h2>2nd levelheading</h2></html> . , # [email protected] [email protected] can't Be a ckunk. $4 $123,456 won't seven $Shine $$beigh"
},
{
"code": null,
"e": 6326,
"s": 6258,
"text": "A string, long_s of 1.159 million characters is created in 8.11 μs."
},
{
"code": null,
"e": 6405,
"s": 6326,
"text": "All benchmarks are run within a Docker container on MacOS Version 14.0 (14.0)."
},
{
"code": null,
"e": 6601,
"s": 6405,
"text": "Model Name: Mac ProProcessor Name: 12-Core Intel Xeon E5Processor Speed: 2.7 GHzTotal Number of Cores: 24L2 Cache (per Core): 256 KBL3 Cache: 30 MBHyper-Threading Technology: EnabledMemory: 64 GB"
},
{
"code": null,
"e": 7042,
"s": 6601,
"text": "Note: Corpus/text pre-processing is dependent on the end-point NLP analysis task. Sentiment Analysis requires different corpus/text pre-processing steps than document redaction. The corpus/text pre-processing steps given here are for a range of NLP analysis tasks. Usually, a subset of the given corpus/text pre-processing steps is needed for each NLP task. Also, some of the required corpus/text pre-processing steps may not be given here."
},
{
"code": null,
"e": 7216,
"s": 7042,
"text": "from textacy.preprocessing.replace import replace_hashtags%time text = replace_hashtags(long_s,replace_with= '_HASH_')print('size: {:g} {}'.format(len(text),text[:text_l])))"
},
{
"code": null,
"e": 7226,
"s": 7216,
"text": "output =>"
},
{
"code": null,
"e": 7607,
"s": 7226,
"text": "CPU times: user 223 ms, sys: 66 μs, total: 223 msWall time: 223 mssize: 1.159e+06 :( 😻 😈 _HASH_ +1 608-444-0000 08-444-0004 608-444-00003 ext. 508 888 eihtg DoD Fee https://medium.com/ _HASH_ ## Document Title</title> :( cat- nip immed- natedly <html><h2>2nd levelheading</h2></html> . , # [email protected] [email protected] can't Be a ckunk. $4 $123,456 won't seven $Shine $$beigh"
},
{
"code": null,
"e": 7815,
"s": 7607,
"text": "Notice that #google and #hash are swapped with_HASH_,and ##and _# are untouched. A million characters were processed in 200 ms. Fast enough for a big corpus of a billion characters (example: web server log)."
},
{
"code": null,
"e": 7982,
"s": 7815,
"text": "from textacy.preprocessing.replace import replace_hashtags%time text = replace_hashtags(long_s,replace_with= '')print('size: {:g} {}'.format(len(text),text[:text_l]))"
},
{
"code": null,
"e": 7992,
"s": 7982,
"text": "output =>"
},
{
"code": null,
"e": 8365,
"s": 7992,
"text": "CPU times: user 219 ms, sys: 0 ns, total: 219 msWall time: 220 mssize: 1.1134e+06 :( 😻 😈 +1 608-444-0000 08-444-0004 608-444-00003 ext. 508 888 eihtg DoD Fee https://medium.com/ ## Document Title</title> :( cat- nip immed- natedly <html><h2>2nd levelheading</h2></html> . , # [email protected] [email protected] can't Be a ckunk. $4 $123,456 won't seven $Shine $$beighty?$"
},
{
"code": null,
"e": 8483,
"s": 8365,
"text": "Notice that #google and #hash are removed and ##,and _# are untouched. A million characters were processed in 200 ms."
},
{
"code": null,
"e": 8667,
"s": 8483,
"text": "from textacy.preprocessing.replace import replace_phone_numbers%time text = replace_phone_numbers(long_s,replace_with= '_PHONE_')print('size: {:g} {}'.format(len(text),text[:text_l]))"
},
{
"code": null,
"e": 8677,
"s": 8667,
"text": "output =>"
},
{
"code": null,
"e": 8826,
"s": 8677,
"text": "CPU times: user 384 ms, sys: 1.59 ms, total: 386 msWall time: 383 mssize: 1.0792e+06 :( 😻 😈 _PHONE_ 08-_PHONE_ 608-444-00003 ext. 508 888 eihtg"
},
{
"code": null,
"e": 8907,
"s": 8826,
"text": "Notice phone number 08-444-0004 and 608-444-00003 ext. 508 were not transformed."
},
{
"code": null,
"e": 9276,
"s": 8907,
"text": "RE_PHONE_NUMBER: Pattern = re.compile( # core components of a phone number r\"(?:^|(?<=[^\\w)]))(\\+?1[ .-]?)?(\\(?\\d{2,3}\\)?[ .-]?)?(\\d{2,3}[ .-]?\\d{2,5})\" # extensions, etc. r\"(\\s?(?:ext\\.?|[#x-])\\s?\\d{2,6})?(?:$|(?=\\W))\", flags=re.UNICODE | re.IGNORECASE)text = RE_PHONE_NUMBER.sub('_PHoNE_', long_s)print('size: {:g} {}'.format(len(text),text[:text_l]))"
},
{
"code": null,
"e": 9286,
"s": 9276,
"text": "output =>"
},
{
"code": null,
"e": 9632,
"s": 9286,
"text": "CPU times: user 353 ms, sys: 0 ns, total: 353 msWall time: 350 mssize: 1.0108e+06 :( 😻 😈 _PHoNE_ _PHoNE_ _PHoNE_ 888 eihtg DoD Fee https://medium.com/ ## Document Title</title> :( cat- nip immed- natedly <html><h2>2nd levelheading</h2></html> . , # [email protected] [email protected] can't Be a ckunk. $4 $123,456 won't seven $Shine $$beighty?$"
},
{
"code": null,
"e": 9756,
"s": 9632,
"text": "Notice phone number 08-444-0004 and 608-444-00003 ext. 508 were transformed. A million characters were processed in 350 ms."
},
{
"code": null,
"e": 9866,
"s": 9756,
"text": "Using the improved RE_PHONE_NUMBER pattern, we put '' in for 'PHoNE' to remove phone numbers from the corpus."
},
{
"code": null,
"e": 9959,
"s": 9866,
"text": "text = RE_PHONE_NUMBER.sub('', long_s)print('size: {:g} {}'.format(len(text),text[:text_l]))"
},
{
"code": null,
"e": 9969,
"s": 9959,
"text": "output =>"
},
{
"code": null,
"e": 10292,
"s": 9969,
"text": "CPU times: user 353 ms, sys: 459 μs, total: 353 msWall time: 351 mssize: 931000 :( 😻 😈 888 eihtg DoD Fee https://medium.com/ ## Document Title</title> :( cat- nip immed- natedly <html><h2>2nd levelheading</h2></html> . , # [email protected] [email protected] can't Be a ckunk. $4 $123,456 won't seven $Shine $$beighty?$"
},
{
"code": null,
"e": 10339,
"s": 10292,
"text": "A million characters were processed in 375 ms."
},
{
"code": null,
"e": 10590,
"s": 10339,
"text": "I admit removing HTML metadata is my favorite. Not because I like the task, but because I screen-scrape frequently. A lot of useful data resides on an IBM mainframe, VAX-780 (huh?), or whatever terminal-emulation that results in an HTML-based report."
},
{
"code": null,
"e": 10799,
"s": 10590,
"text": "These techniques of web scraping of reports generate text that has HTML tags. However, HTML tags are typically considered noise as they are parts of the text with little or no value in the follow-on NLP task."
},
{
"code": null,
"e": 10947,
"s": 10799,
"text": "Remember, we created a test string (long_s) a little over million characters long with some HTML tags. We remove the HTML tags using BeautifulSoup."
},
{
"code": null,
"e": 11097,
"s": 10947,
"text": "from bs4 import BeautifulSoup%time long_s = BeautifulSoup(long_s,'html.parser').get_text()print('size: {:g} {}'.format(len(long_s),long_s[:text_l])))"
},
{
"code": null,
"e": 11107,
"s": 11097,
"text": "output =>"
},
{
"code": null,
"e": 11308,
"s": 11107,
"text": "CPU times: user 954 ms, sys: 17.7 ms, total: 971 msWall time: 971 mssize: 817000 :( 😻 😈 888 eihtg DoD Fee https://medium.com/ ## Document Title :( cat- nip immed- natedly 2nd levelheading"
},
{
"code": null,
"e": 11551,
"s": 11308,
"text": "The result is that BeautifulSoup can remove over 7,000 HTML tags in a million-character corpus in one second. Scaling linearly, a billion-character corpus, about 200 million words, or approximately 2000 books, would require about 200 seconds."
},
{
"code": null,
"e": 11680,
"s": 11551,
"text": "The rate for HTML tag removal byBeautifulSoup is about 0. 1 second per book. An acceptable rate for our production requirements."
},
{
"code": null,
"e": 11781,
"s": 11680,
"text": "I only benchmark BeautifulSoup. If you know of a competitive alternative method, please let me know."
},
{
"code": null,
"e": 11892,
"s": 11781,
"text": "Note: The compute times you get maybe multiples of time longer or shorter if you are using the cloud or Spark."
},
{
"code": null,
"e": 12005,
"s": 11892,
"text": "The currency symbols “[$¢£¤¥ƒ֏؋৲৳૱௹฿៛M元円圆圓ریال\\u20A0-\\u20C0] “ are replaced with _CUR_using the textacy package:"
},
{
"code": null,
"e": 12138,
"s": 12005,
"text": "%time textr = textacy.preprocessing.replace.replace_currency_symbols(long_s)print('size: {:g} {}'.format(len(textr),textr[:text_l]))"
},
{
"code": null,
"e": 12148,
"s": 12138,
"text": "output =>"
},
{
"code": null,
"e": 12469,
"s": 12148,
"text": "CPU times: user 31.2 ms, sys: 1.67 ms, total: 32.9 msWall time: 33.7 mssize: 908200 :( 😻 😈 888 eihtg DoD Fee https://medium.com/ ## Document Title :( cat- nip immed- natedly 2nd levelheading . , # [email protected] [email protected] can't Be a ckunk. _CUR_4 _CUR_123,456 won't seven _CUR_Shine _CUR__CUR_beighty?_CUR_"
},
{
"code": null,
"e": 12628,
"s": 12469,
"text": "Note: The option textacy replace_<something> enables you to specify the replacement text. _CUR_ is the default substitution text for replace_currency_symbols."
},
{
"code": null,
"e": 12712,
"s": 12628,
"text": "You may have the currency symbol $ in your text. In this case, you can use a regex:"
},
{
"code": null,
"e": 12806,
"s": 12712,
"text": "%time text = re.sub('\\$', '_DOL_', long_s)print('size: {:g} {}'.format(len(text),text[:250]))"
},
{
"code": null,
"e": 12816,
"s": 12806,
"text": "output =>"
},
{
"code": null,
"e": 13250,
"s": 12816,
"text": "CPU times: user 8.06 ms, sys: 0 ns, total: 8.06 msWall time: 8.25 mssize: 1.3262e+06 :( 😻 😈 #google +1 608-444-0000 08-444-0004 608-444-00003 ext. 508 888 eihtg DoD Fee https://medium.com/ #hash ## <html><title>Document Title</title></html> :( cat- nip immed- natedly <html><h2>2nd levelheading</h2></html> . , # [email protected] [email protected] can't Be a ckunk. _DOL_4 _DOL_123,456 won't seven _DOL_Shine _DOL__DOL_beighty?_DOL_ :"
},
{
"code": null,
"e": 13377,
"s": 13250,
"text": "Note: All symbol $ in your text will be removed. Don't use it if you have LaTex or any text where multiple symbols $ are used."
},
{
"code": null,
"e": 13541,
"s": 13377,
"text": "from textacy.preprocessing.replace import replace_urls%time text = replace_urls(long_s,replace_with= '_URL_')print('size: {:g} {}'.format(len(text),text[:text_l]))"
},
{
"code": null,
"e": 13551,
"s": 13541,
"text": "output =>"
},
{
"code": null,
"e": 13694,
"s": 13551,
"text": "CPU times: user 649 ms, sys: 112 μs, total: 649 msWall time: 646 mssize: 763800 :( 😻 😈 888 eihtg DoD Fee _URL_ ## Document Title :("
},
{
"code": null,
"e": 13853,
"s": 13694,
"text": "from textacy.preprocessing.replace import replace_urls%time text = replace_urls(long_s,replace_with= '')print('size: {:g} {}'.format(len(text),text[:text_l]))"
},
{
"code": null,
"e": 13863,
"s": 13853,
"text": "output =>"
},
{
"code": null,
"e": 14002,
"s": 13863,
"text": "CPU times: user 633 ms, sys: 1.35 ms, total: 635 msWall time: 630 mssize: 744800 :( 😻 😈 888 eihtg DoD Fee ## Document Title :("
},
{
"code": null,
"e": 14134,
"s": 14002,
"text": "The rate for URL replace, or removal is about 4,000 URLs per 1 million characters per second. Fast enough for 10 books in a corpus."
},
{
"code": null,
"e": 14254,
"s": 14134,
"text": "%time text = textacy.preprocessing.replace.replace_emails(long_s)print('size: {:g} {}'.format(len(text),text[:text_l]))"
},
{
"code": null,
"e": 14264,
"s": 14254,
"text": "output =>"
},
{
"code": null,
"e": 14533,
"s": 14264,
"text": "CPU times: user 406 ms, sys: 125 μs, total: 406 msWall time: 402 mssize: 725800 :( 😻 😈 888 eihtg DoD Fee ## Document Title :( cat- nip immed- natedly 2nd levelheading . , # _EMAIL_ _EMAIL_ can't Be a ckunk. $4 $123,456 won't seven $Shine $$beighty?$"
},
{
"code": null,
"e": 14669,
"s": 14533,
"text": "The rate for email reference replace is about 8,000 emails per 1.7 million characters per second. Fast enough for 17 books in a corpus."
},
{
"code": null,
"e": 14862,
"s": 14669,
"text": "from textacy.preprocessing.replace import replace_emails%time text = textacy.preprocessing.replace.replace_emails(long_s,replace_with= '')print('size: {:g} {}'.format(len(text),text[:text_l]))"
},
{
"code": null,
"e": 14872,
"s": 14862,
"text": "output =>"
},
{
"code": null,
"e": 15128,
"s": 14872,
"text": "CPU times: user 413 ms, sys: 1.68 ms, total: 415 msWall time: 412 mssize: 672600 :( 😻 😈 888 eihtg DoD Fee ## Document Title :( cat- nip immed- natedly 2nd levelheading . , # can't Be a ckunk. $4 $123,456 won't seven $Shine $$beighty?$"
},
{
"code": null,
"e": 15264,
"s": 15128,
"text": "The rate for email reference removal is about 8,000 emails per 1.1 million characters per second. Fast enough for 11 books in a corpus."
},
{
"code": null,
"e": 15443,
"s": 15264,
"text": "from textacy.preprocessing.normalize import normalize_hyphenated_words%time long_s = normalize_hyphenated_words(long_s)print('size: {:g} {}'.format(len(long_s),long_s[:text_l])))"
},
{
"code": null,
"e": 15453,
"s": 15443,
"text": "output =>"
},
{
"code": null,
"e": 15612,
"s": 15453,
"text": "CPU times: user 186 ms, sys: 4.58 ms, total: 191 msWall time: 190 mssize: 642200 :( 😻 😈 888 eihtg DoD Fee ## Document Title :( catnip immednatedly"
},
{
"code": null,
"e": 15781,
"s": 15612,
"text": "Approximately 8,000 hyphenated words, cat — nip and immed- iately (misspelled) were corrected in a corpus of 640,000 characters in 190 ms or about 3 million per second."
},
{
"code": null,
"e": 15908,
"s": 15781,
"text": "### - **all characters to lower case;**%time long_s = long_s.lower()print('size: {:g} {}'.format(len(long_s),long_s[:text_l]))"
},
{
"code": null,
"e": 15918,
"s": 15908,
"text": "output =>"
},
{
"code": null,
"e": 16169,
"s": 15918,
"text": "CPU times: user 4.82 ms, sys: 953 μs, total: 5.77 msWall time: 5.97 mssize: 642200:( 😻 😈 888 eihtg dod fee ## document title :( catnip immednatedly 2nd levelheading . , # can't be a ckunk. $4 $123,456 won't seven $shine $$beighty?$"
},
{
"code": null,
"e": 16380,
"s": 16169,
"text": "I only benchmark the .lower Python function. The rate for lower case transformation by.lower() of a Python string of a million characters is about 6 ms. A rate that far exceeds our production rate requirements."
},
{
"code": null,
"e": 16473,
"s": 16380,
"text": "%time text = re.sub(' +', ' ', long_s)print('size: {:g} {}'.format(len(text),text[:text_l]))"
},
{
"code": null,
"e": 16483,
"s": 16473,
"text": "output =>"
},
{
"code": null,
"e": 16717,
"s": 16483,
"text": "CPU times: user 44.9 ms, sys: 2.89 ms, total: 47.8 msWall time: 47.8 mssize: 570000 :( 😻 😈 888 eihtg dod fee ## document title :( catnip immednatedly 2nd levelheading . , # can't be a ckunk. $4 $123,456 won't seven $shine $$beighty?$"
},
{
"code": null,
"e": 16773,
"s": 16717,
"text": "The rate is about 0.1 seconds for 1 million characters."
},
{
"code": null,
"e": 16932,
"s": 16773,
"text": "from textacy.preprocessing.normalize import normalize_whitespace%time text= normalize_whitespace(long_s)print('size: {:g} {}'.format(len(text),text[:text_l]))"
},
{
"code": null,
"e": 16942,
"s": 16932,
"text": "output =>"
},
{
"code": null,
"e": 17173,
"s": 16942,
"text": "CPU times: user 199 ms, sys: 3.06 ms, total: 203 msWall time: 201 mssize: 569999 :( 😻 😈 888 eihtg dod fee ## document title :( catnip immednatedly 2nd levelheading . , # can't be a ckunk. $4 $123,456 won't seven $shine $$beighty?$"
},
{
"code": null,
"e": 17341,
"s": 17173,
"text": "normalize_whitespce is 5x slower but more general. For safety in production, we use normalize_whitespce.To date, we do not think we had any problems with faster regex."
},
{
"code": null,
"e": 17509,
"s": 17341,
"text": "from textacy.preprocessing.remove import remove_punctuation%time text = remove_punctuation(long_s, marks=',.#$?')print('size: {:g} {}'.format(len(text),text[:text_l]))"
},
{
"code": null,
"e": 17519,
"s": 17509,
"text": "output =>"
},
{
"code": null,
"e": 17749,
"s": 17519,
"text": "CPU times: user 34.5 ms, sys: 4.82 ms, total: 39.3 msWall time: 39.3 mssize: 558599 :( 😻 😈 888 eihtg dod fee document title :( catnip immednatedly 2nd levelheading can't be a ckunk 4 123 456 won't seven shine beighty"
},
{
"code": null,
"e": 18026,
"s": 17749,
"text": "To text pre-process with spaCy, we transform the text into a corpus Doc object. We can then use the sequence of word tokens objects of which a Doc object consists. Each token consists of attributes (discussed above) that we use later in this article to pre-process the corpus."
},
{
"code": null,
"e": 18121,
"s": 18026,
"text": "Our text pre-processing end goal (usually) is to produce tokens that feed into our NLP models."
},
{
"code": null,
"e": 18294,
"s": 18121,
"text": "spaCy reverses the stream of pre-processing text and then transforming text into tokens. spaCy creates a Doc of tokens. You then pre-process the tokens by their attributes."
},
{
"code": null,
"e": 18470,
"s": 18294,
"text": "The result is that parsing text into a Doc object is where the majority of computation lies. As we will see, pre-processing the sequence of tokens by their attributes is fast."
},
{
"code": null,
"e": 18753,
"s": 18470,
"text": "import en_core_web_lgnlp = en_core_web_lg.load()do = nlp.disable_pipes([\"tagger\", \"parser\"])%time emoji = Emoji(nlp)nlp.max_length = len(long_s) + 10%time nlp.add_pipe(emoji, first=True)%time long_s_doc = nlp(long_s)print('size: {:g} {}'.format(len(long_s_doc),long_s_doc[:text_l]))"
},
{
"code": null,
"e": 18763,
"s": 18753,
"text": "output =>"
},
{
"code": null,
"e": 19121,
"s": 18763,
"text": "CPU times: user 303 ms, sys: 22.6 ms, total: 326 msWall time: 326 msCPU times: user 23 μs, sys: 0 ns, total: 23 μsWall time: 26.7 μsCPU times: user 7.22 s, sys: 1.89 s, total: 9.11 sWall time: 9.12 ssize: 129199 :( 😻 😈 888 eihtg dod fee document title :( catnip immednatedly 2nd levelheading can't be a ckunk 4 123 456 won't seven shine beighty"
},
{
"code": null,
"e": 19232,
"s": 19121,
"text": "Creating the token sequence required 14,000 tokens per second. We will quite a speedup when we use NVIDIA GPU."
},
{
"code": null,
"e": 19272,
"s": 19232,
"text": "nlp.pipe_namesoutput =>['emoji', 'ner']"
},
{
"code": null,
"e": 19731,
"s": 19272,
"text": "Note: The tokenizer is a “special” component and isn’t part of the regular pipeline. It also doesn’t show up in nlp.pipe_names. The reason is that there can only be one tokenizer, and while all other pipeline components take a Doc and return it, the tokenizer takes a string of text and turns it into a Doc. You can still customize the tokenizer. You can either create your ownTokenizer class from scratch or even replace it with an entirely custom function."
},
{
"code": null,
"e": 19910,
"s": 19731,
"text": "As we saw earlier, spaCy provides convenience methods for many other pre-processing tasks. It turns — for example, to remove stop words, you can reference the .is_stop attribute."
},
{
"code": null,
"e": 20940,
"s": 19910,
"text": "dir(token[0])output=>'ancestors', 'check_flag', 'children', 'cluster', 'conjuncts', 'dep', 'dep_', 'doc', 'ent_id', 'ent_id_', 'ent_iob', 'ent_iob_', 'ent_kb_id', 'ent_kb_id_', 'ent_type', 'ent_type_', 'get_extension', 'has_extension', 'has_vector', 'head', 'i', 'idx', 'is_alpha', 'is_ancestor', 'is_ascii', 'is_bracket', 'is_currency', 'is_digit', 'is_left_punct', 'is_lower', 'is_oov', 'is_punct', 'is_quote', 'is_right_punct', 'is_sent_end', 'is_sent_start', 'is_space', 'is_stop', 'is_title', 'is_upper', 'lang', 'lang_', 'left_edge', 'lefts', 'lemma', 'lemma_', 'lex_id', 'like_email', 'like_num', 'like_url', 'lower', 'lower_', 'morph', 'n_lefts', 'n_rights', 'nbor', 'norm', 'norm_', 'orth', 'orth_', 'pos', 'pos_', 'prefix', 'prefix_', 'prob', 'rank', 'remove_extension', 'right_edge', 'rights', 'sent', 'sent_start', 'sentiment', 'set_extension', 'shape', 'shape_', 'similarity', 'string', 'subtree', 'suffix', 'suffix_', 'tag', 'tag_', 'tensor', 'text', 'text_with_ws', 'vector', 'vector_norm', 'vocab', 'whitespace_']"
},
{
"code": null,
"e": 20975,
"s": 20940,
"text": "Attributes added by emoji and new."
},
{
"code": null,
"e": 21342,
"s": 20975,
"text": "dir(long_s_doc[0]._)output =>['emoji_desc', 'get', 'has', 'is_emoji', 'set', 'trf_alignment', 'trf_all_attentions', 'trf_all_hidden_states', 'trf_d_all_attentions', 'trf_d_all_hidden_states', 'trf_d_last_hidden_state', 'trf_d_pooler_output', 'trf_end', 'trf_last_hidden_state', 'trf_pooler_output', 'trf_separator', 'trf_start', 'trf_word_pieces', 'trf_word_pieces_'"
},
{
"code": null,
"e": 21493,
"s": 21342,
"text": "I show spaCy performing preprocessing that results in a Python string corpus. Then, the corpus is used to create a new sequence of spaCy tokens (Doc)."
},
{
"code": null,
"e": 21619,
"s": 21493,
"text": "There is a faster way to accomplish spaCy preprocessing with spaCy pipeline extensions [2], which I show in an upcoming blog."
},
{
"code": null,
"e": 21690,
"s": 21619,
"text": "EMOJI Sentiment Score is not a text preprocessor in the classic sense."
},
{
"code": null,
"e": 21770,
"s": 21690,
"text": "However, we find that emoji almost always is the dominating text in a document."
},
{
"code": null,
"e": 21852,
"s": 21770,
"text": "For example, two similar phrases from legal notes e-mail with opposite sentiment."
},
{
"code": null,
"e": 21911,
"s": 21852,
"text": "The client was challenging. :(The client was difficult. :)"
},
{
"code": null,
"e": 21973,
"s": 21911,
"text": "We calculate the only emoji when present in a note or e-mail."
},
{
"code": null,
"e": 22129,
"s": 21973,
"text": "%time scl = [EMOJI_TO_SENTIMENT_VALUE[token.text] for token in long_s_doc if (token.text in EMOJI_TO_SENTIMENT_VALUE)]len(scl), sum(scl), sum(scl)/len(scl)"
},
{
"code": null,
"e": 22139,
"s": 22129,
"text": "output =>"
},
{
"code": null,
"e": 22253,
"s": 22139,
"text": "CPU times: user 179 ms, sys: 0 ns, total: 179 msWall time: 178 ms(15200, 1090.7019922523152, 0.07175671001659968)"
},
{
"code": null,
"e": 22403,
"s": 22253,
"text": "The sentiment was 0.07 (neutral) for 0.5 million characters “note” with 15,200 emojis and emojicons in 178 ms. A fast sentiment analysis calculation!"
},
{
"code": null,
"e": 22456,
"s": 22403,
"text": "You can remove emoji using the spaCy pipeline add-on"
},
{
"code": null,
"e": 22646,
"s": 22456,
"text": "%time long_s_doc_no_emojicon = [token for token in long_s_doc if token._.is_emoji == False]print('size: {:g} {}'.format(len(long_s_doc_no_emojicon),long_s_doc_no_emojicon[:int(text_l/5)]))"
},
{
"code": null,
"e": 22656,
"s": 22646,
"text": "output =>"
},
{
"code": null,
"e": 23136,
"s": 22656,
"text": "CPU times: user 837 ms, sys: 4.98 ms, total: 842 msWall time: 841 mssize: 121599 [:(, 888, eihtg, dod, fee, , document, title, :(, catnip, immednatedly, 2nd, levelheading, , ca, n't, be, a, ckunk, , 4, , 123, 456, wo, n't, seven, , shine, , beighty, , :(, 888, eihtg, dod, fee, , document, title, :(, catnip, immednatedly, 2nd, levelheading, , ca, n't, be, a, ckunk, , 4, , 123, 456, wo, n't, seven, , shine, , beighty, , :(, 888, eihtg, dod, fee, ]"
},
{
"code": null,
"e": 23221,
"s": 23136,
"text": "The emoji spacy pipeline addition detected the emojicons, 😻 😈, but missed :) and :(."
},
{
"code": null,
"e": 23334,
"s": 23221,
"text": "We developed EMOJI_TO_PHRASEto detect the emojicons, 😻 😈, and emojis, such as :) and :(. and removed them [8,9]."
},
{
"code": null,
"e": 23544,
"s": 23334,
"text": "%time text = [token.text if (token.text in EMOJI_TO_PHRASE) == False \\ else '' for token in long_s_doc]%time long_s = ' '.join(text)print('size: {:g} {}'.format(len(long_s),long_s[:text_l]))"
},
{
"code": null,
"e": 23554,
"s": 23544,
"text": "output =>"
},
{
"code": null,
"e": 24055,
"s": 23554,
"text": "CPU times: user 242 ms, sys: 3.76 ms, total: 245 msWall time: 245 msCPU times: user 3.37 ms, sys: 73 μs, total: 3.45 msWall time: 3.46 mssize: 569997 888 eihtg dod fee document title catnip immednatedly 2nd levelheading ca n't be a ckunk 4 123 456 wo n't seven shine beighty 888 eihtg dod fee document title catnip immednatedly 2nd levelheading ca n't be a ckunk 4 123 456 wo n't seven shine beighty 888 eihtg dod fee document title catnip imm"
},
{
"code": null,
"e": 24113,
"s": 24055,
"text": "We can translate emojicon into a natural language phrase."
},
{
"code": null,
"e": 24300,
"s": 24113,
"text": "%time text = [token.text if token._.is_emoji == False else token._.emoji_desc for token in long_s_doc]%time long_s = ' '.join(text)print('size: {:g} {}'.format(len(long_s),long_s[:250]))"
},
{
"code": null,
"e": 24310,
"s": 24300,
"text": "output =>"
},
{
"code": null,
"e": 24666,
"s": 24310,
"text": "CPU times: user 1.07 s, sys: 7.54 ms, total: 1.07 sWall time: 1.07 sCPU times: user 3.78 ms, sys: 0 ns, total: 3.78 msWall time: 3.79 mssize: 794197 :( smiling cat face with heart-eyes smiling face with horns 888 eihtg dod fee document title :( catnip immednatedly 2nd levelheading ca n't be a ckunk 4 123 456 wo n't seven shine beighty"
},
{
"code": null,
"e": 24751,
"s": 24666,
"text": "The emoji spaCy pipeline addition detected the emojicons, 😻 😈, but missed :) and :(."
},
{
"code": null,
"e": 24810,
"s": 24751,
"text": "We can translate emojicons into a natural language phrase."
},
{
"code": null,
"e": 25045,
"s": 24810,
"text": "%time text = [token.text if (token.text in EMOJI_TO_PHRASE) == False \\ else EMOJI_TO_PHRASE[token.text] for token in long_s_doc]%time long_s = ' '.join(text)print('size: {:g} {}'.format(len(long_s),long_s[:text_l]))"
},
{
"code": null,
"e": 25055,
"s": 25045,
"text": "output =>"
},
{
"code": null,
"e": 25456,
"s": 25055,
"text": "CPU times: user 251 ms, sys: 5.57 ms, total: 256 msWall time: 255 msCPU times: user 3.54 ms, sys: 91 μs, total: 3.63 msWall time: 3.64 mssize: 904397 FROWNING FACE SMILING CAT FACE WITH HEART-SHAPED EYES SMILING FACE WITH HORNS 888 eihtg dod fee document title FROWNING FACE catnip immednatedly 2nd levelheading ca n't be a ckunk 4 123 456 wo n't seven shine beighty FROWNING FAC"
},
{
"code": null,
"e": 25564,
"s": 25456,
"text": "Again. EMOJI_TO_PHRASE detected the emojicons, 😻 😈, and emoji, such as :) and :(. and substituted a phrase."
},
{
"code": null,
"e": 25615,
"s": 25564,
"text": "We will use symspell for spelling correction [14]."
},
{
"code": null,
"e": 25798,
"s": 25615,
"text": "SymSpell, based on the Symmetric Delete spelling correction algorithm, just took 0.000033 seconds (edit distance 2) and 0.000180 seconds (edit distance 3) on an old MacBook Pro [14]."
},
{
"code": null,
"e": 25978,
"s": 25798,
"text": "%time sym_spell_setup() %time tk = [check_spelling(token.text) for token in long_s_doc[0:99999]]%time long_s = ' '.join(tk)print('size: {:g} {}'.format(len(long_s),long_s[:250]))"
},
{
"code": null,
"e": 25988,
"s": 25978,
"text": "output =>"
},
{
"code": null,
"e": 26441,
"s": 25988,
"text": "CPU times: user 5.22 s, sys: 132 ms, total: 5.35 sWall time: 5.36 sCPU times: user 25 s, sys: 12.9 ms, total: 25 sWall time: 25.1 sCPU times: user 3.37 ms, sys: 42 μs, total: 3.41 msWall time: 3.42 mssize: 528259 FROWNING FACE SMILING CAT FACE WITH HEART a SHAPED EYES SMILING FACE WITH HORNS 888 eight do fee document title FROWNING FACE catnip immediately and levelheading a not be a chunk a of 123 456 to not seven of shine of eighty"
},
{
"code": null,
"e": 26618,
"s": 26441,
"text": "Spell correction was accomplished for immednatedly, ckunk and beight. Correcting misspelled words is our largest computation. It required 30 seconds for 0.8 million characters."
},
{
"code": null,
"e": 26802,
"s": 26618,
"text": "%time token = [token.text if token.is_currency == False else '_CUR_' for token in long_s_doc]%time long_s = ' '.join(token)print('size: {:g} {}'.format(len(long_s),long_s[:text_l]))aa"
},
{
"code": null,
"e": 26906,
"s": 26802,
"text": "Note: spacy removes all punctuation including :) emoji and emoticon. You can protect the emoticon with:"
},
{
"code": null,
"e": 27075,
"s": 26906,
"text": "%time long_s_doc = [token for token in long_s_doc if token.is_punct == False or token._.is_emoji == True]print('size: {:g} {}'.format(len(long_s_doc),long_s_doc[:50]))"
},
{
"code": null,
"e": 27276,
"s": 27075,
"text": "However, replace_currency_symbolsand regex ignores context and replaces any currency symbol. You may have multiple uses $ in your text and thus can not ignore context. In this case, you can use spaCy."
},
{
"code": null,
"e": 27449,
"s": 27276,
"text": "%time tk = [token.text if token.is_currency == False else '_CUR_' for token in long_s_doc]%time long_s = ' '.join(tk)print('size: {:g} {}'.format(len(long_s),long_s[:250]))"
},
{
"code": null,
"e": 27459,
"s": 27449,
"text": "output =>"
},
{
"code": null,
"e": 27860,
"s": 27459,
"text": "CPU times: user 366 ms, sys: 13.9 ms, total: 380 msWall time: 381 msCPU times: user 9.7 ms, sys: 0 ns, total: 9.7 msWall time: 9.57 mssize: 1.692e+06 😻 👍 🏿 < title > Document Title</title > :( < html><h2>2nd levelheading</h2></html > [email protected] [email protected] a$@ ca n't bc$$ ef$4 5 66 _CUR_ wo nt seven eihtg _CUR_ nine _CUR_ _CUR_ zer$ 😻 👍 🏿 < title > Document Title</title > :( < html><h2>2nd leve"
},
{
"code": null,
"e": 27996,
"s": 27860,
"text": "%time tokens = [token for token in long_s_doc if not token.like_email]print('size: {:g} {}'.format(len(tokens),tokens[:int(text_l/3)]))"
},
{
"code": null,
"e": 28006,
"s": 27996,
"text": "output =>"
},
{
"code": null,
"e": 28089,
"s": 28006,
"text": "CPU times: user 52.7 ms, sys: 3.09 ms, total: 55.8 msWall time: 54.8 mssize: 99999"
},
{
"code": null,
"e": 28134,
"s": 28089,
"text": "About 0.06 seconds for 1 million characters."
},
{
"code": null,
"e": 28310,
"s": 28134,
"text": "%time tokens = [token.text for token in long_s_doc if (token.pos_ not in ['SPACE','PUNCT'])]%time text = ' '.join(tokens)print('size: {:g} {}'.format(len(text),text[:text_l]))"
},
{
"code": null,
"e": 28480,
"s": 28310,
"text": "NLP models (ex: logistic regression and transformers) and NLP tasks (Sentiment Analysis) continue to be added. Some benefit from stopword removal, and some will not. [2]"
},
{
"code": null,
"e": 28586,
"s": 28480,
"text": "Note: We now only use different deep learning language models (transformers) and do not remove stopwords."
},
{
"code": null,
"e": 28753,
"s": 28586,
"text": "%time tokens = [token.text for token in long_s_doc if token.is_stop == False]%time long_s = ' '.join(tokens)print('size: {:g} {}'.format(len(long_s),long_s[:text_l]))"
},
{
"code": null,
"e": 28882,
"s": 28753,
"text": "Lemmatization looks beyond word reduction and considers a language’s full vocabulary to apply a morphological analysis to words."
},
{
"code": null,
"e": 29006,
"s": 28882,
"text": "Lemmatization looks at the surrounding text to determine a given the word’s part of speech. It does not categorize phrases."
},
{
"code": null,
"e": 29149,
"s": 29006,
"text": "%time tokens = [token.lemma_ for token in long_s_doc]%time long_s = ' '.join(tokens)print('size: {:g} {}'.format(len(long_s),long_s[:text_l]))"
},
{
"code": null,
"e": 29159,
"s": 29149,
"text": "output =>"
},
{
"code": null,
"e": 29560,
"s": 29159,
"text": "CPU times: user 366 ms, sys: 13.9 ms, total: 380 msWall time: 381 msCPU times: user 9.7 ms, sys: 0 ns, total: 9.7 msWall time: 9.57 mssize: 1.692e+06 😻 👍 🏿 < title > Document Title</title > :( < html><h2>2nd levelheading</h2></html > [email protected] [email protected] a$@ ca n't bc$$ ef$4 5 66 _CUR_ wo nt seven eihtg _CUR_ nine _CUR_ _CUR_ zer$ 😻 👍 🏿 < title > Document Title</title > :( < html><h2>2nd leve"
},
{
"code": null,
"e": 29775,
"s": 29560,
"text": "Note: Spacy does not have stemming. You can add if it is you want. Stemming does not work as well as Lemmazatation because Stemming does not consider context [2] (Why some researcher considers spacy “opinionated”)."
},
{
"code": null,
"e": 29862,
"s": 29775,
"text": "Note: If you do not know Stemming, you can still be on the Survivor show. (my opinion)"
},
{
"code": null,
"e": 30017,
"s": 29862,
"text": "Whatever the NLP task, you need to clean (pre-process) the data (text) into a corpus (document or set of documents) before it is input into any NLP model."
},
{
"code": null,
"e": 30117,
"s": 30017,
"text": "I adopt a text pre-processing framework that has three major categories of NLP text pre-processing:"
},
{
"code": null,
"e": 30131,
"s": 30117,
"text": "Noise Removal"
},
{
"code": null,
"e": 30145,
"s": 30131,
"text": "Noise Removal"
},
{
"code": null,
"e": 30196,
"s": 30145,
"text": "Transform Unicode characters into text characters."
},
{
"code": null,
"e": 30272,
"s": 30196,
"text": "convert a document image into segmented image parts and text snippets [10];"
},
{
"code": null,
"e": 30330,
"s": 30272,
"text": "extract data from a database and transform it into words;"
},
{
"code": null,
"e": 30388,
"s": 30330,
"text": "remove markup and metadata in HTML, XML, JSON, .md, etc.;"
},
{
"code": null,
"e": 30414,
"s": 30388,
"text": "remove extra whitespaces;"
},
{
"code": null,
"e": 30457,
"s": 30414,
"text": "remove emoji or convert emoji into phases;"
},
{
"code": null,
"e": 30566,
"s": 30457,
"text": "Remove or convert currency symbol, URLs, email addresses, phone numbers, hashtags, other identifying tokens;"
},
{
"code": null,
"e": 30614,
"s": 30566,
"text": "The correct mis-spelling of words (tokens); [7]"
},
{
"code": null,
"e": 30653,
"s": 30614,
"text": "Remove remaining unwanted punctuation;"
},
{
"code": null,
"e": 30657,
"s": 30653,
"text": "..."
},
{
"code": null,
"e": 30673,
"s": 30657,
"text": "2. Tokenization"
},
{
"code": null,
"e": 30812,
"s": 30673,
"text": "They are splitting strings of text into smaller pieces, or “tokens.” Paragraphs segment into sentences, and sentences tokenize into words."
},
{
"code": null,
"e": 30829,
"s": 30812,
"text": "3. Normalization"
},
{
"code": null,
"e": 30866,
"s": 30829,
"text": "Change all characters to lower case;"
},
{
"code": null,
"e": 30930,
"s": 30866,
"text": "Remove English stop words, or whatever language the text is in;"
},
{
"code": null,
"e": 30965,
"s": 30930,
"text": "Perform Lemmatization or Stemming."
},
{
"code": null,
"e": 31101,
"s": 30965,
"text": "The tasks listed in Noise Removal and Normalization can move back and forth. The categorical assignment is for explanatory convenience."
},
{
"code": null,
"e": 31232,
"s": 31101,
"text": "Note: We do not remove stop-words anymore. We found that our current NLP models have higher F1 scores when we leave in stop-words."
},
{
"code": null,
"e": 31362,
"s": 31232,
"text": "Note: Stop-word removal is expensive computationally. We found the best way to achieve faster stop-word removal was not to do it."
},
{
"code": null,
"e": 31467,
"s": 31362,
"text": "Note: We saw no significant change in Deep Learning NLP models’ speed with or without stop-word removal."
},
{
"code": null,
"e": 31583,
"s": 31467,
"text": "Note: The Noise Removal and Normalization lists are not exhaustive. These are some of the tasks I have encountered."
},
{
"code": null,
"e": 31836,
"s": 31583,
"text": "The latestu000e NLP Deep Learning models are more accurate than older models. However, Deep Learning models can be impractically slow to train and are still too slow for prediction. We show in a follow-on article how we speed up such production models."
},
{
"code": null,
"e": 31977,
"s": 31836,
"text": "Note: Stemming algorithms drop off the end of the beginning of the word, a list of common prefixes, and suffixes to create a base root word."
},
{
"code": null,
"e": 32218,
"s": 31977,
"text": "Lemmatization uses linguistic knowledge bases to get the correct roots of words. In addition, lemmatization performs morphological analysis of each word, which requires the overhead of creating a linguistic knowledge base for each language."
},
{
"code": null,
"e": 32263,
"s": 32218,
"text": "Note: Stemming is faster than lemmatization."
},
{
"code": null,
"e": 32483,
"s": 32263,
"text": "In practice, lemmatization yields better results than stemming in an NLP Deep Learning model. Stemming generally reduces precision accuracy, and increases recall accuracy because it injects semi-random noise when wrong."
},
{
"code": null,
"e": 32494,
"s": 32483,
"text": "medium.com"
},
{
"code": null,
"e": 32748,
"s": 32494,
"text": "Our unique implementations, spaCy, and textacy are our current choice for short text preprocessing production fast use. If you don’t mind the big performance gap, I recommend using it for production purposes over NLTK’s implementation of Stanford’s NER."
},
{
"code": null,
"e": 33031,
"s": 32748,
"text": "In the next blogs, We see how performance changes using multi-processing, multithreading, Nvidia GPUs, and pySpark. Also, I will write about how and why our implementations, such as EMOJI_TO_PHRASEand EMOJI_TO_SENTIMENT_VALUEand or how to add emoji, emoticon, or any Unicode symbol."
},
{
"code": null,
"e": 33066,
"s": 33031,
"text": "Happy Natural Language Processing!"
},
{
"code": null,
"e": 33153,
"s": 33066,
"text": "[1] How Much Data Do We Create Every Day? The Mind-Blowing Stats Everyone Should Read."
},
{
"code": null,
"e": 33246,
"s": 33153,
"text": "[2] Industrial-Strength Natural Language Processing; ] Turbo-charge your spaCy NLP pipeline."
},
{
"code": null,
"e": 33292,
"s": 33246,
"text": "corrected the piece3] NLTK 3.5 Documentation."
},
{
"code": null,
"e": 33328,
"s": 33292,
"text": "[4] Textacy: Text (Pre)-processing."
},
{
"code": null,
"e": 33346,
"s": 33328,
"text": "[5] Hugging Face."
},
{
"code": null,
"e": 33389,
"s": 33346,
"text": "[6] Language Models are Few-Shot Learners."
},
{
"code": null,
"e": 33429,
"s": 33389,
"text": "[7] re — Regular expression operations."
},
{
"code": null,
"e": 33552,
"s": 33429,
"text": "[8] Using millions of emoji occurrences to learn any-domain representations for detecting sentiment, emotion, and sarcasm."
},
{
"code": null,
"e": 33582,
"s": 33552,
"text": "[9] How I Built Emojitracker."
},
{
"code": null,
"e": 33645,
"s": 33582,
"text": "[10] Classifying e-commerce products based on images and text."
},
{
"code": null,
"e": 33711,
"s": 33645,
"text": "[11] DART: Open-Domain Structured Data Record to Text Generation."
},
{
"code": null,
"e": 33809,
"s": 33711,
"text": "[12] Adv-BERT: BERT is not robust on misspellings! Generating nature adversarial samples on BERT."
},
{
"code": null,
"e": 33824,
"s": 33809,
"text": "[13] fast.ai ."
}
] |
Matrix Chain Multiplication (A O(N^3) Solution) in C++ | If a chain of matrices is given, we have to find minimum number of correct sequence of matrices to multiply.
We know that the matrix multiplication is associative, so four matrices ABCD, we can multiply A(BCD), (AB)(CD), (ABC)D, A(BC)D, in these sequences. Like these sequences, our task is to find which ordering is efficient to multiply.
In the given input there is an array say arr, which contains arr[] = {1, 2, 3, 4}. It means the matrices are of the order (1 x 2), (2 x 3), (3 x 4).
Input − The orders of the input matrices. {1, 2, 3, 4}. It means the matrices are
{(1 x 2), (2 x 3), (3 x 4)}.
Output − Minimum number of operations need multiply these three matrices. Here the result is 18.
matOrder(array, n)
Input: List of matrices, the number of matrices in the list.
Output: Minimum number of matrix multiplication.
Begin
define table minMul of size n x n, initially fill with all 0s
for length := 2 to n, do
for i:=1 to n-length, do
j := i + length – 1
minMul[i, j] := ∞
for k := i to j-1, do
q := minMul[i, k] + minMul[k+1, j] + array[i-1]*array[k]*array[j]
if q < minMul[i, j], then
minMul[i, j] := q
done
done
done
return minMul[1, n-1]
End
#include<iostream>
using namespace std;
int matOrder(int array[], int n){
int minMul[n][n]; //holds the number of scalar multiplication needed
for (int i=1; i<n; i++)
minMul[i][i] = 0; //for multiplication with 1 matrix, cost is 0
for (int length=2; length<n; length++){ //find the chain length starting from 2
for (int i=1; i<n-length+1; i++){
int j = i+length-1;
minMul[i][j] = INT_MAX; //set to infinity
for (int k=i; k<=j-1; k++){
//store cost per multiplications
int q = minMul[i][k] + minMul[k+1][j] + array[i-1]*array[k]*array[j];
if (q < minMul[i][j])
minMul[i][j] = q;
}
}
}
return minMul[1][n-1];
}
int main(){
int arr[] = {1, 2, 3, 4};
int size = 4;
cout << "Minimum number of matrix multiplications: "<<matOrder(arr, size);
}
Minimum number of matrix multiplications: 18 | [
{
"code": null,
"e": 1171,
"s": 1062,
"text": "If a chain of matrices is given, we have to find minimum number of correct sequence of matrices to multiply."
},
{
"code": null,
"e": 1402,
"s": 1171,
"text": "We know that the matrix multiplication is associative, so four matrices ABCD, we can multiply A(BCD), (AB)(CD), (ABC)D, A(BC)D, in these sequences. Like these sequences, our task is to find which ordering is efficient to multiply."
},
{
"code": null,
"e": 1551,
"s": 1402,
"text": "In the given input there is an array say arr, which contains arr[] = {1, 2, 3, 4}. It means the matrices are of the order (1 x 2), (2 x 3), (3 x 4)."
},
{
"code": null,
"e": 1633,
"s": 1551,
"text": "Input − The orders of the input matrices. {1, 2, 3, 4}. It means the matrices are"
},
{
"code": null,
"e": 1662,
"s": 1633,
"text": "{(1 x 2), (2 x 3), (3 x 4)}."
},
{
"code": null,
"e": 1759,
"s": 1662,
"text": "Output − Minimum number of operations need multiply these three matrices. Here the result is 18."
},
{
"code": null,
"e": 2325,
"s": 1759,
"text": "matOrder(array, n)\nInput: List of matrices, the number of matrices in the list.\nOutput: Minimum number of matrix multiplication.\nBegin\n define table minMul of size n x n, initially fill with all 0s\n for length := 2 to n, do\n for i:=1 to n-length, do\n j := i + length – 1\n minMul[i, j] := ∞\n for k := i to j-1, do\n q := minMul[i, k] + minMul[k+1, j] + array[i-1]*array[k]*array[j]\n if q < minMul[i, j], then\n minMul[i, j] := q\n done\n done\n done\n return minMul[1, n-1]\nEnd"
},
{
"code": null,
"e": 3222,
"s": 2325,
"text": "#include<iostream>\nusing namespace std;\nint matOrder(int array[], int n){\n int minMul[n][n]; //holds the number of scalar multiplication needed\n for (int i=1; i<n; i++)\n minMul[i][i] = 0; //for multiplication with 1 matrix, cost is 0\n for (int length=2; length<n; length++){ //find the chain length starting from 2\n for (int i=1; i<n-length+1; i++){\n int j = i+length-1;\n minMul[i][j] = INT_MAX; //set to infinity\n for (int k=i; k<=j-1; k++){\n //store cost per multiplications\n int q = minMul[i][k] + minMul[k+1][j] + array[i-1]*array[k]*array[j];\n if (q < minMul[i][j])\n minMul[i][j] = q;\n }\n }\n }\n return minMul[1][n-1];\n}\nint main(){\n int arr[] = {1, 2, 3, 4};\n int size = 4;\n cout << \"Minimum number of matrix multiplications: \"<<matOrder(arr, size);\n}"
},
{
"code": null,
"e": 3267,
"s": 3222,
"text": "Minimum number of matrix multiplications: 18"
}
] |
LEFT/RIGHT in 5 languages (VBA/SQL/PYTHON/M query/DAX powerBI) | by Aymen | Towards Data Science | Excel is a powerful spreadsheet used by most people working in data analysis. The increase of volume of data and development user-friendly tools is an opportunity of improvement of Excel reports by mixing them with another tool or language.
As working for a financial reporting department I faced the need to boost our reporting tools. A simple way to start working with a new language is to translate what we use to do in excel, in another language. “How can I pivot this?”, “How can I vlookup that ?”.
In this article I will share with you how you can make LEFT/RIGHT in 5 different languages: VBA, python, SQL, DAX (Power BI), M (Power query). it will simple tips but if you want to get more detailed article don’t forget to follow me!
The Excel LEFT function extracts a given number of characters from the left side of a supplied text string. RIGHT do the same but from the right. The syntax is as follow:
=LEFT (text, [num_chars])
Text: the text from which to extract characters.
num_chars: The number of characters to extract, starting on the left side of text. If you do not specify, by default it is 1.
If we take a practical example where in cell “A1” we have the phrase “This is an example”:
If we want to isolate “This” we put as argument “A1” and 4 characters from LEFT, and if we want to isolate “example” we put “A1” as argument in RIGHT and specify 7 characters.
Visual Basic for Application (VBA) is an implementation of Microsoft Visual Basic integrated into Microsoft Office applications.
Applying LEFT/RIGHT in VBA is so easy that I even hesitated to present it. But let’s enjoy this simplicity. In the cell where we want to apply the formula, we will just apply the formula. Actually we will write the formula in the cell and get the result directly.
Range("C1") = left(Range("A1"), 4)
SQL ( Structured Query Language) or sequel, is a standard language for storing, manipulating and retrieving data in databases. It is one of the common upgrade done by companies that face limits with Excel. Usually, the first reaction is to negotiate some budget in order to store the data into a database and use SQL to “speak” with this database and organise, manipulate the data. The language is also highly appreciable. Close to a natural language, you don’t feel coding when typing simple SQL request.
LEFT/RIGHT in SQL is very close to the Excel formula. In practice, let’s take the table we created for the VLOOKUP in 5 languages. It was a table with items and prices:
CREATE TABLE table1 ( Item varchar(255), Price int );INSERT INTO table1VALUES ('Item1', 4);INSERT INTO table1VALUES ('Item2', 12);INSERT INTO table1VALUES ('Item3', 56);CREATE TABLE table2 ( Item varchar(255), Price int );
Now let’s create 2 columns, one with just “item” isolated using left and one with the item number (just the number) using right.
The general template is:
LEFT(field_name, number of characters to extract from the left)
And applied to our example:
SELECT LEFT(Item,4) AS Product FROM table1;
Same with numbers:
SELECT RIGHT(Item,1) AS Type FROM table1;
Additional tip: In sql we can easily extract the characters in the middle of a set of data using the formula SUBSTRING
SUBSTRING(field_name, starting position, ending position relative to the starting position)
Python is an interpreted, high level language with a generic purpose. It is used in a large range of application, including data analysis. We can present python by saying “For all application its libraries”. And for data, without surprise, we will use the famous Pandas.
In our example we will make the extraction as string (text). Let’s first create a dataframe(df) with our items and prices:
import pandas as pditems = {'Item': ['Item1','Item2','Item3'], 'Price': [4, 12,56]}df = pd.DataFrame(data=items)
Now to get the data we will apply .str[:x] for the left and .str[-x:] for the right. Here the colon x (:x) means from the first character to the number x, and applying a minus x means starting from le last character.
Left = df['Item'].str[:4]Right= df['Item'].str[-1:]
Left will return only “Item” and Right will return the number.
Additional tip: As we explained in SQL, we can with python also isolate the middle of the data we want to extract using the same .str[x:y]. It means from x to y, but be careful, here x is not counted (for example .str[4:6] means character fifth and sixth);
M is the powerful language behind the tool power query. Even if you are working on the query editor, every single step will be written in M. M stands for Data Mashup or Data Modeling. I highly recommend to have a look at this language, we can do so much more than just using the graphical interface.
To extract the left side or right side of a text in M we just have to create a simple expression. The example we will used will be the one used in VLOOKUP in 5 languages.
Once your table is updated, you can use the graphical interface and clic on add column:
Then during the customisation of the the column, just apply the formula text.start to simulate left, or text.end to simulate right. In the aguments you will put the column name and the number of character:
Text.Start([Item], 4)Text.End([Item], 1)
So here text.start will return “Item” and text.end will return only the number.
DAX stands for Data Analysis Expressions. More than a language, it is a library of functions and operators that can be used to build formulas in Power BI and Power Pivot.
This part will be really short as the model is exactly the same as the Excel formula. You have in DAX 2 formulas, LEFT and RIGHT with exactly the same arguments :
LEFT(<text>, <num_chars>)RIGHT(<text>, <num_chars>)
This article is a part of a set of articles where I share my way of doing an Excel feature in other languages. For sure, when you decide to move from Excel to programming, your approach of data analysis will totally change and you will learn that there are tons of way to get to your solution. If you have another manner to do this or even know how to do it with other languages, feel free to share them in the comments or by contacting me in my social networks! I will be pleased to read your thoughts! | [
{
"code": null,
"e": 288,
"s": 47,
"text": "Excel is a powerful spreadsheet used by most people working in data analysis. The increase of volume of data and development user-friendly tools is an opportunity of improvement of Excel reports by mixing them with another tool or language."
},
{
"code": null,
"e": 551,
"s": 288,
"text": "As working for a financial reporting department I faced the need to boost our reporting tools. A simple way to start working with a new language is to translate what we use to do in excel, in another language. “How can I pivot this?”, “How can I vlookup that ?”."
},
{
"code": null,
"e": 786,
"s": 551,
"text": "In this article I will share with you how you can make LEFT/RIGHT in 5 different languages: VBA, python, SQL, DAX (Power BI), M (Power query). it will simple tips but if you want to get more detailed article don’t forget to follow me!"
},
{
"code": null,
"e": 957,
"s": 786,
"text": "The Excel LEFT function extracts a given number of characters from the left side of a supplied text string. RIGHT do the same but from the right. The syntax is as follow:"
},
{
"code": null,
"e": 983,
"s": 957,
"text": "=LEFT (text, [num_chars])"
},
{
"code": null,
"e": 1032,
"s": 983,
"text": "Text: the text from which to extract characters."
},
{
"code": null,
"e": 1158,
"s": 1032,
"text": "num_chars: The number of characters to extract, starting on the left side of text. If you do not specify, by default it is 1."
},
{
"code": null,
"e": 1249,
"s": 1158,
"text": "If we take a practical example where in cell “A1” we have the phrase “This is an example”:"
},
{
"code": null,
"e": 1425,
"s": 1249,
"text": "If we want to isolate “This” we put as argument “A1” and 4 characters from LEFT, and if we want to isolate “example” we put “A1” as argument in RIGHT and specify 7 characters."
},
{
"code": null,
"e": 1554,
"s": 1425,
"text": "Visual Basic for Application (VBA) is an implementation of Microsoft Visual Basic integrated into Microsoft Office applications."
},
{
"code": null,
"e": 1818,
"s": 1554,
"text": "Applying LEFT/RIGHT in VBA is so easy that I even hesitated to present it. But let’s enjoy this simplicity. In the cell where we want to apply the formula, we will just apply the formula. Actually we will write the formula in the cell and get the result directly."
},
{
"code": null,
"e": 1853,
"s": 1818,
"text": "Range(\"C1\") = left(Range(\"A1\"), 4)"
},
{
"code": null,
"e": 2359,
"s": 1853,
"text": "SQL ( Structured Query Language) or sequel, is a standard language for storing, manipulating and retrieving data in databases. It is one of the common upgrade done by companies that face limits with Excel. Usually, the first reaction is to negotiate some budget in order to store the data into a database and use SQL to “speak” with this database and organise, manipulate the data. The language is also highly appreciable. Close to a natural language, you don’t feel coding when typing simple SQL request."
},
{
"code": null,
"e": 2528,
"s": 2359,
"text": "LEFT/RIGHT in SQL is very close to the Excel formula. In practice, let’s take the table we created for the VLOOKUP in 5 languages. It was a table with items and prices:"
},
{
"code": null,
"e": 2767,
"s": 2528,
"text": "CREATE TABLE table1 ( Item varchar(255), Price int );INSERT INTO table1VALUES ('Item1', 4);INSERT INTO table1VALUES ('Item2', 12);INSERT INTO table1VALUES ('Item3', 56);CREATE TABLE table2 ( Item varchar(255), Price int );"
},
{
"code": null,
"e": 2896,
"s": 2767,
"text": "Now let’s create 2 columns, one with just “item” isolated using left and one with the item number (just the number) using right."
},
{
"code": null,
"e": 2921,
"s": 2896,
"text": "The general template is:"
},
{
"code": null,
"e": 2985,
"s": 2921,
"text": "LEFT(field_name, number of characters to extract from the left)"
},
{
"code": null,
"e": 3013,
"s": 2985,
"text": "And applied to our example:"
},
{
"code": null,
"e": 3057,
"s": 3013,
"text": "SELECT LEFT(Item,4) AS Product FROM table1;"
},
{
"code": null,
"e": 3076,
"s": 3057,
"text": "Same with numbers:"
},
{
"code": null,
"e": 3118,
"s": 3076,
"text": "SELECT RIGHT(Item,1) AS Type FROM table1;"
},
{
"code": null,
"e": 3237,
"s": 3118,
"text": "Additional tip: In sql we can easily extract the characters in the middle of a set of data using the formula SUBSTRING"
},
{
"code": null,
"e": 3329,
"s": 3237,
"text": "SUBSTRING(field_name, starting position, ending position relative to the starting position)"
},
{
"code": null,
"e": 3600,
"s": 3329,
"text": "Python is an interpreted, high level language with a generic purpose. It is used in a large range of application, including data analysis. We can present python by saying “For all application its libraries”. And for data, without surprise, we will use the famous Pandas."
},
{
"code": null,
"e": 3723,
"s": 3600,
"text": "In our example we will make the extraction as string (text). Let’s first create a dataframe(df) with our items and prices:"
},
{
"code": null,
"e": 3836,
"s": 3723,
"text": "import pandas as pditems = {'Item': ['Item1','Item2','Item3'], 'Price': [4, 12,56]}df = pd.DataFrame(data=items)"
},
{
"code": null,
"e": 4053,
"s": 3836,
"text": "Now to get the data we will apply .str[:x] for the left and .str[-x:] for the right. Here the colon x (:x) means from the first character to the number x, and applying a minus x means starting from le last character."
},
{
"code": null,
"e": 4105,
"s": 4053,
"text": "Left = df['Item'].str[:4]Right= df['Item'].str[-1:]"
},
{
"code": null,
"e": 4168,
"s": 4105,
"text": "Left will return only “Item” and Right will return the number."
},
{
"code": null,
"e": 4425,
"s": 4168,
"text": "Additional tip: As we explained in SQL, we can with python also isolate the middle of the data we want to extract using the same .str[x:y]. It means from x to y, but be careful, here x is not counted (for example .str[4:6] means character fifth and sixth);"
},
{
"code": null,
"e": 4725,
"s": 4425,
"text": "M is the powerful language behind the tool power query. Even if you are working on the query editor, every single step will be written in M. M stands for Data Mashup or Data Modeling. I highly recommend to have a look at this language, we can do so much more than just using the graphical interface."
},
{
"code": null,
"e": 4896,
"s": 4725,
"text": "To extract the left side or right side of a text in M we just have to create a simple expression. The example we will used will be the one used in VLOOKUP in 5 languages."
},
{
"code": null,
"e": 4984,
"s": 4896,
"text": "Once your table is updated, you can use the graphical interface and clic on add column:"
},
{
"code": null,
"e": 5190,
"s": 4984,
"text": "Then during the customisation of the the column, just apply the formula text.start to simulate left, or text.end to simulate right. In the aguments you will put the column name and the number of character:"
},
{
"code": null,
"e": 5231,
"s": 5190,
"text": "Text.Start([Item], 4)Text.End([Item], 1)"
},
{
"code": null,
"e": 5311,
"s": 5231,
"text": "So here text.start will return “Item” and text.end will return only the number."
},
{
"code": null,
"e": 5482,
"s": 5311,
"text": "DAX stands for Data Analysis Expressions. More than a language, it is a library of functions and operators that can be used to build formulas in Power BI and Power Pivot."
},
{
"code": null,
"e": 5645,
"s": 5482,
"text": "This part will be really short as the model is exactly the same as the Excel formula. You have in DAX 2 formulas, LEFT and RIGHT with exactly the same arguments :"
},
{
"code": null,
"e": 5697,
"s": 5645,
"text": "LEFT(<text>, <num_chars>)RIGHT(<text>, <num_chars>)"
}
] |
Armstrong Numbers | Practice | GeeksforGeeks | For a given 3 digit number, find whether it is armstrong number or not. An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. Return "Yes" if it is a armstrong number else return "No".
NOTE: 371 is an Armstrong number since 33 + 73 + 13 = 371
Example 1:
Input: N = 153
Output: "Yes"
Explanation: 153 is an Armstrong number
since 13 + 53 + 33 = 153.
Hence answer is "Yes".
Example 2:
Input: N = 370
Output: "Yes"
Explanation: 370 is an Armstrong number
since 33 + 73 + 03 = 370.
Hence answer is "Yes".
Your Task:
You dont need to read input or print anything. Complete the function armstrongNumber() which takes n as input parameter and returns "Yes" if it is a armstrong number else returns "No"..
Expected Time Complexity: O(1)
Expected Auxiliary Space: O(1)
Constraints:
100 ≤ n <1000
0
aishnamdev13in 4 hours
//Java Solution
class Solution { static String armstrongNumber(int n){ int temp = n; int arm = 0; while(n!=0) { int rem = n%10; arm += Math.pow(rem,3); n = n/10; } if(arm == temp) { return "Yes"; } else { return "No"; } }}
0
mayank180919992 days ago
string armstrongNumber(int n){
// code here
int digit;
int sum=0;
int val=n;
while(n!=0){
digit=n%10;
sum+=pow(digit,3);
n=n/10;
}
if(sum==val){
return "Yes";
}
return "No";
}
0
gfgcode10104 days ago
class Solution { static String armstrongNumber(int n){ // code here int temp = n; int r,sum = 0; while(n>0){ r = n%10; n = n/10; sum = sum + (r*r*r); } if(temp==sum){ return "Yes"; } else{ return "No"; } }}
0
selibrshaman5 days ago
java passed cases: 33/33if (Math.pow((n%1000-n%100)/100, 3)+Math.pow((n%100-n%10)/10, 3)+Math.pow(n%10, 3)==n) return "Yes"; else return "No";
0
navhayer991 week ago
class Solution { static String armstrongNumber(int n){ // code here int rem, result=0; int temp=n;
while(temp!=0){ rem=temp%10; result+=Math.pow(rem,n); temp/=10; } if(result==n) return "Yes"; else return "No"; } }
0
rsbly7300951 week ago
class Solution{
armstrongNumber(n){
let sum = 0;
for(let item of n.toString()){
sum += item*item*item;
}
if(sum == n){
return "Yes";
}
else return "No";
}
}
0
abhisri19971 week ago
armstrongNumber(n){
const unitArr = n.toString().match(/[0-9]/g);
let sum = 0;
unitArr.forEach(val => {
sum += Number(val) ** 3;
})
return sum === n ? "Yes" : "No";
}
Easiest way to achieve this without any mathematical converting of hundred, thousands, unit places.
0
convertedengineer2 weeks ago
int sum=0;
int originaln=n;
while(n>0){
int lastDigit=n%10;
sum+=pow(lastDigit,3);
n=n/10;
}
if(sum==originaln){
return "Yes";
}
else{
return "No";
}
+1
nallalasumanthreddy3 weeks ago
UPVOTE PYTHON SOLUTION
class Solution:
def armstrongNumber (ob, n):
a=0
for i in str(n):
a+=int(i)**3
if a==n:
return ("Yes")
else:
return ("No")
0
nyapparel17723 weeks ago
static boolean checkIfArmStrong(int n) { int res=0; // get how many digits int inputToCount = n; int len=0; int inputNum = n; int currentDigit=0; while(inputToCount > 0) { inputToCount /=10; len++; } for(int i=1; i<=len; i++) { currentDigit = inputNum%10; res += Math.pow(currentDigit, 3); inputNum = inputNum/10; } return (res == n) ? true : false;}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 565,
"s": 238,
"text": "For a given 3 digit number, find whether it is armstrong number or not. An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. Return \"Yes\" if it is a armstrong number else return \"No\".\nNOTE: 371 is an Armstrong number since 33 + 73 + 13 = 371\n\nExample 1:"
},
{
"code": null,
"e": 684,
"s": 565,
"text": "Input: N = 153\nOutput: \"Yes\"\nExplanation: 153 is an Armstrong number\nsince 13 + 53 + 33 = 153.\nHence answer is \"Yes\".\n"
},
{
"code": null,
"e": 695,
"s": 684,
"text": "Example 2:"
},
{
"code": null,
"e": 813,
"s": 695,
"text": "Input: N = 370\nOutput: \"Yes\"\nExplanation: 370 is an Armstrong number\nsince 33 + 73 + 03 = 370.\nHence answer is \"Yes\"."
},
{
"code": null,
"e": 1104,
"s": 813,
"text": "\nYour Task: \nYou dont need to read input or print anything. Complete the function armstrongNumber() which takes n as input parameter and returns \"Yes\" if it is a armstrong number else returns \"No\"..\n\nExpected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)\n\nConstraints:\n100 ≤ n <1000"
},
{
"code": null,
"e": 1106,
"s": 1104,
"text": "0"
},
{
"code": null,
"e": 1129,
"s": 1106,
"text": "aishnamdev13in 4 hours"
},
{
"code": null,
"e": 1145,
"s": 1129,
"text": "//Java Solution"
},
{
"code": null,
"e": 1419,
"s": 1145,
"text": "class Solution { static String armstrongNumber(int n){ int temp = n; int arm = 0; while(n!=0) { int rem = n%10; arm += Math.pow(rem,3); n = n/10; } if(arm == temp) { return \"Yes\"; } else { return \"No\"; } }}"
},
{
"code": null,
"e": 1421,
"s": 1419,
"text": "0"
},
{
"code": null,
"e": 1446,
"s": 1421,
"text": "mayank180919992 days ago"
},
{
"code": null,
"e": 1747,
"s": 1446,
"text": " string armstrongNumber(int n){\n // code here\n int digit;\n int sum=0;\n int val=n;\n while(n!=0){\n digit=n%10;\n sum+=pow(digit,3);\n n=n/10;\n }\n if(sum==val){\n return \"Yes\"; \n }\n return \"No\"; \n }"
},
{
"code": null,
"e": 1749,
"s": 1747,
"text": "0"
},
{
"code": null,
"e": 1771,
"s": 1749,
"text": "gfgcode10104 days ago"
},
{
"code": null,
"e": 2112,
"s": 1771,
"text": "class Solution { static String armstrongNumber(int n){ // code here int temp = n; int r,sum = 0; while(n>0){ r = n%10; n = n/10; sum = sum + (r*r*r); } if(temp==sum){ return \"Yes\"; } else{ return \"No\"; } }}"
},
{
"code": null,
"e": 2114,
"s": 2112,
"text": "0"
},
{
"code": null,
"e": 2137,
"s": 2114,
"text": "selibrshaman5 days ago"
},
{
"code": null,
"e": 2286,
"s": 2137,
"text": "java passed cases: 33/33if (Math.pow((n%1000-n%100)/100, 3)+Math.pow((n%100-n%10)/10, 3)+Math.pow(n%10, 3)==n) return \"Yes\"; else return \"No\";"
},
{
"code": null,
"e": 2288,
"s": 2286,
"text": "0"
},
{
"code": null,
"e": 2309,
"s": 2288,
"text": "navhayer991 week ago"
},
{
"code": null,
"e": 2428,
"s": 2309,
"text": "class Solution { static String armstrongNumber(int n){ // code here int rem, result=0; int temp=n;"
},
{
"code": null,
"e": 2663,
"s": 2428,
"text": " while(temp!=0){ rem=temp%10; result+=Math.pow(rem,n); temp/=10; } if(result==n) return \"Yes\"; else return \"No\"; } }"
},
{
"code": null,
"e": 2665,
"s": 2663,
"text": "0"
},
{
"code": null,
"e": 2687,
"s": 2665,
"text": "rsbly7300951 week ago"
},
{
"code": null,
"e": 2951,
"s": 2687,
"text": "class Solution{\n \n armstrongNumber(n){\n let sum = 0;\n for(let item of n.toString()){\n sum += item*item*item;\n \n } \n \n if(sum == n){\n return \"Yes\";\n }\n else return \"No\";\n }\n}"
},
{
"code": null,
"e": 2953,
"s": 2951,
"text": "0"
},
{
"code": null,
"e": 2975,
"s": 2953,
"text": "abhisri19971 week ago"
},
{
"code": null,
"e": 3207,
"s": 2975,
"text": "armstrongNumber(n){\n const unitArr = n.toString().match(/[0-9]/g);\n let sum = 0;\n unitArr.forEach(val => {\n sum += Number(val) ** 3;\n })\n \n return sum === n ? \"Yes\" : \"No\";\n }"
},
{
"code": null,
"e": 3307,
"s": 3207,
"text": "Easiest way to achieve this without any mathematical converting of hundred, thousands, unit places."
},
{
"code": null,
"e": 3309,
"s": 3307,
"text": "0"
},
{
"code": null,
"e": 3338,
"s": 3309,
"text": "convertedengineer2 weeks ago"
},
{
"code": null,
"e": 3604,
"s": 3338,
"text": "int sum=0;\n int originaln=n;\n while(n>0){\n int lastDigit=n%10;\n sum+=pow(lastDigit,3);\n n=n/10;\n }\n if(sum==originaln){\n return \"Yes\";\n }\n else{\n return \"No\";\n }"
},
{
"code": null,
"e": 3607,
"s": 3604,
"text": "+1"
},
{
"code": null,
"e": 3638,
"s": 3607,
"text": "nallalasumanthreddy3 weeks ago"
},
{
"code": null,
"e": 3661,
"s": 3638,
"text": "UPVOTE PYTHON SOLUTION"
},
{
"code": null,
"e": 3856,
"s": 3661,
"text": "class Solution:\n def armstrongNumber (ob, n):\n a=0\n for i in str(n):\n a+=int(i)**3\n if a==n:\n return (\"Yes\")\n else:\n return (\"No\")"
},
{
"code": null,
"e": 3858,
"s": 3856,
"text": "0"
},
{
"code": null,
"e": 3883,
"s": 3858,
"text": "nyapparel17723 weeks ago"
},
{
"code": null,
"e": 4240,
"s": 3883,
"text": "static boolean checkIfArmStrong(int n) { int res=0; // get how many digits int inputToCount = n; int len=0; int inputNum = n; int currentDigit=0; while(inputToCount > 0) { inputToCount /=10; len++; } for(int i=1; i<=len; i++) { currentDigit = inputNum%10; res += Math.pow(currentDigit, 3); inputNum = inputNum/10; } return (res == n) ? true : false;}"
},
{
"code": null,
"e": 4386,
"s": 4240,
"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": 4422,
"s": 4386,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4432,
"s": 4422,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4442,
"s": 4432,
"text": "\nContest\n"
},
{
"code": null,
"e": 4505,
"s": 4442,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4653,
"s": 4505,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 4861,
"s": 4653,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 4967,
"s": 4861,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Learning Process of a Deep Neural Network | by Jordi TORRES.AI | Towards Data Science | This is the updated version of the fifth post (post 3, post 4) in the series that I wrote two years ago. In it I will present an intuitive vision of the main components of the learning process of a neural network using as a example Keras, that has become the TensorFlow's high-level API for building and training deep learning models.
Finally, we will put into practice some of the concepts presented here with an interactive tool called TensorFlow Playground.
A neural network is made up of neurons connected to each other; at the same time, each connection of our neural network is associated with a weight that dictates the importance of this relationship in the neuron when multiplied by the input value.
Each neuron has an activation function that defines the output of the neuron. The activation function is used to introduce non-linearity in the modeling capabilities of the network. We have several options for activation functions that we will present in this post.
Following the previous simplified representation, we could represent the model presented in the previous post that classify MNIST digits as:
Training our neural network, that is, learning the values of our parameters (weights wij and bj biases) is the most genuine part of Deep Learning and we can see this learning process in a neural network as an iterative process of “going and return” by the layers of neurons. The “going” is a forwardpropagation of the information and the “return” is a backpropagation of the information.
The first phase forwardpropagation occurs when the network is exposed to the training data and these cross the entire neural network for their predictions (labels) to be calculated. That is, passing the input data through the network in such a way that all the neurons apply their transformation to the information they receive from the neurons of the previous layer and sending it to the neurons of the next layer. When the data has crossed all the layers, and all its neurons have made their calculations, the final layer will be reached with a result of label prediction for those input examples.
Next, we will use a loss function to estimate the loss (or error) and to compare and measure how good/bad our prediction result was in relation to the correct result (remember that we are in a supervised learning environment and we have the label that tells us the expected value). Ideally, we want our cost to be zero, that is, without divergence between estimated and expected value. Therefore, as the model is being trained, the weights of the interconnections of the neurons will gradually be adjusted until good predictions are obtained.
Once the loss has been calculated, this information is propagated backwards. Hence, its name: backpropagation. Starting from the output layer, that loss information propagates to all the neurons in the hidden layer that contribute directly to the output. However, the neurons of the hidden layer only receive a fraction of the total signal of the loss, based on the relative contribution that each neuron has contributed to the original output. This process is repeated, layer by layer, until all the neurons in the network have received a loss signal that describes their relative contribution to the total loss.
Visually, we can summarize what we have explained with this visual scheme of the stages (based in the previous visual represeentation of our neural network):
Now that we have spread this information back, we can adjust the weights of connections between neurons. What we are doing is making the loss as close as possible to zero the next time we go back to using the network for a prediction. For this, we will use a technique called gradient descent. This technique changes the weights in small increments with the help of the calculation of the derivative (or gradient) of the loss function, which allows us to see in which direction “to descend” towards the global minimum; this is done in general in batches of data in the successive iterations (epochs) of all the dataset that we pass to the network in each iteration.
To recap, the learning algorithm consists of:
Start with values (often random) for the network parameters (wij weights and bj biases).Take a set of examples of input data and pass them through the network to obtain their prediction.Compare these predictions obtained with the values of expected labels and calculate the loss with them.Perform the backpropagation in order to propagate this loss to each and every one of the parameters that make up the model of the neural network.Use this propagated information to update the parameters of the neural network with the gradient descent in a way that the total loss is reduced and a better model is obtained.Continue iterating in the previous steps until we consider that we have a good model.
Start with values (often random) for the network parameters (wij weights and bj biases).
Take a set of examples of input data and pass them through the network to obtain their prediction.
Compare these predictions obtained with the values of expected labels and calculate the loss with them.
Perform the backpropagation in order to propagate this loss to each and every one of the parameters that make up the model of the neural network.
Use this propagated information to update the parameters of the neural network with the gradient descent in a way that the total loss is reduced and a better model is obtained.
Continue iterating in the previous steps until we consider that we have a good model.
Below we present in more detail each of the elements that we have highlighted in this section.
Remember that we use the activation functions to propagate the output of a neuron forward. This output is received by the neurons of the next layer to which this neuron is connected (up to the output layer included). As we have said, the activation function serves to introduce non-linearity in the modeling capabilities of the network. Below we will list the most used nowadays; all of them can be used in a layer of Keras (we can find more information on their website).
The linear activation function is basically the identity function in which, in practical terms, it means that the signal does not change.
The sigmoid function has already been introduced in a previous post. Its interest lies in the fact that it allows a reduction in extreme or atypical values in valid data without eliminating them: it converts independent variables of almost infinite range into simple probabilities between 0 and 1. Most of its output will be very close to the extremes of 0 or 1.
Without going into detail, we can summarize that the tanh represents the relationship between the hyperbolic sine and the hyperbolic cosine: tanh(x)=sinh(x)/cosh(x). Unlike the sigmoid function, the normalized range of tanh is between -1 and 1, which is the input that goes well with some neural networks. The advantage of tanh is that negative numbers can be dealt with more easily.
The softmax activation function was also presented in a previous post to generalize the logistic regression, insofar as instead of classifying in binary it can contain multiple decision limits. As we have seen, the softmax activation function will often be found in the output layer of a neural network and return the probability distribution over mutually exclusive output classes.
The activation function rectified linear unit (ReLU) is a very interesting transformation that activates a single node if the input is above a certain threshold. The default and more usual behavior is that, as long as the input has a value below zero, the output will be zero but, when the input rises above, the output is a linear relationship with the input variable of the form f(x)=x. The ReLU activation function has proven to work in many different situations and is currently widely used.
In summary, we can consider backpropagation as a method to alter the parameters (weights and biases) of the neural network in the right direction. It starts by calculating the loss term first, and then the parameters of the neural network are adjusted in reverse order with an optimization algorithm taking into account this calculated loss.
Remember that in Keras the compile() method allows us to define how we want the components that are involved in the learning process to be:
model.compile(loss=’categorical_crossentropy’, optimizer=’sgd’, metrics=[‘accuracy’])
Specifically, in this example, three arguments are passed to the method: an optimizer, a loss function, and a list of metrics. In classification problems like our example, accuracy is used as a metric. Let’s go a little deeper into these arguments.
A loss function is one of the parameters required to quantify how close a particular neural network is to the ideal weight during the training process.
In the Keras manual page, we can find all types of loss functions available. Some have their concrete hyperparameters that must be indicated; in the example of the previous post, when we use categorical_crossentropy as a function of loss, our output must be in a categorical format. The choice of the best function of loss resides in understanding what type of error is or is not acceptable for the problem in particular.
The optimizer is another of the arguments required in the compile() method. Keras currently has different optimizers that can be used: SGD, RMSprop, Adagrad, Adadelta, Adam, Adamax, Nadam. You can find more detail about each of them in the Keras documentation.
In general, we can see the learning process as a global optimization problem where the parameters (weights and biases) must be adjusted in such a way that the loss function presented above is minimized. In most cases, these parameters cannot be solved analytically, but in general they can be approached well with optimizing algorithms, such as those mentioned above.
We will explain one of the concrete optimizers so that you understand the overall operation of the optimizers. Specifically, the gradient descent, the basis of many optimizers and one of the most common optimization algorithms in Machine Learning and Deep Learning.
Gradient descent uses the first derivative (gradient) of the loss function when updating the parameters. Remember that the gradient gives us the slope of a function at that point. Without being able to go into detail, the process consists in chaining the derivatives of the loss of each hidden layer from the derivatives of the loss of its upper layer, incorporating its activation function in the calculation (that’s why the activation functions must be derivable). In each of the iterations, once all the neurons have the value of the gradient of the loss function that corresponds to them, the values of the parameters are updated in the opposite direction to that indicated by the gradient. The gradient, in fact, always points in the direction in which the value of the loss function increases. Therefore, if the negative of the gradient is used, we can get the direction in which we tend to reduce the loss function.
Let’s see the process in a visual way assuming only one dimension: suppose that this line represents the values that the loss function takes for each possible parameter value and that the negative of the gradient is depicted by the arrow in the initial point:
To determine the next value for the parameter, the gradient descent algorithm modifies the value of the initial weight to go in the opposite way to the gradient (since it points in the direction in which the loss grows and we want to reduce it), adding a proportional amount to this. The magnitude of this change is determined by the value of the gradient and by a learning rate hyperparameter that we can specify (which we will present shortly). Therefore, conceptually, it is as if we follow the slope downhill until we reach a local minimum:
The gradient descent algorithm repeats this process getting closer and closer to the minimum until the value of the parameter reaches a point beyond which the loss function cannot decrease:
In the previous sections we have seen how the values of the parameters are adjusted but not in what frequency:
After each entry example?
After each round of the whole set of training examples (epoch)?
After a sample of examples of the training set?
In the first case we speak of online learning, when the gradient is estimated from the observed loss for each example of the training; it is also when we talk about Stochastic Gradient Descent (SGD). The second is known as batch learning and is called Batch Gradient Descent. The literature indicates that, usually, better results can be obtained with online learning, but there are reasons that justify the use of batch learning because many optimization techniques only work with it.
But if the data is well distributed, a small subset of them should give us a pretty good approximation of the gradient. We may not get the best estimate, but it is faster and, given the fact that we are iterating, this approach is very useful. For this reason, the third aforementioned option known as mini-batch is often used. This option is usually as good as the online, but fewer calculations are required to update the parameters of the neural network. In addition, the simultaneous calculation of the gradient for many input examples can be done using matrix operations that are implemented very efficiently with GPU, as we have seen in a previous post.
That’s why, in reality, many applications use the stochastic gradient descent (SGD) with a mini-bach of several examples. To use all the data, what is done is to partition the data in several batches. Then we take the first batch, go through the network, calculate the gradient of its loss and update the parameters of the neural network; this would follow successively until the last batch. Now, in a single pass through all the input data, only a number of steps have been made equal to the number of batches.
SGD is very easy to implement in Keras. In the compile() method it is indicated that the optimizer is SGD (value sgd in the argument), and then all that must be done is to specify the batch size in the training process with the fit() method as follows :
model.fit(X_train, y_train, epochs=5, batch_size=100)
In this code example that uses the fit() method, we are dividing our data into batches of 100 with the batch_size argument. With the number of epochs we are indicating how many times we carry out this process on all the data. Later in this post, when we have already presented the usual optimizer parameters, we will return to these two arguments.
If the reader at the end of the previous post has executed a model with the hyperparameters that we use there, I assume that the model’s accuracy will have exceeded 90%. Are these results good? I think they are fantastic, because it means that the reader has already programmed and executed his first neural network with Keras. Congratulations!
Another thing is that there are other models that improve accuracy. And this depends on having a great knowledge and a lot of practice to handle well with the many hyperparameters that we can change. For example, with a simple change of the activation function of the first layer, passing from a sigmoid to a relu like the one shown below:
model.add(Dense(10, activation=’relu’, input_shape=(784,)))
We can get 2% more accuracy with more or less the same calculation time.
It is also possible to increase the number of epochs, add more neurons in a layer or add more layers. However, in these cases, the gains in accuracy have the side effect of increasing the execution time of the learning process. For example, if we add 512 nodes to the intermediate layer instead of 10 nodes:
model.add(Dense(512, activation=’relu’, input_shape=(784,)))
We can check with the summary() method that the number of parameters increases (it is a fully connected) and the execution time is significantly higher, even reducing the number of epochs. With this model, the accuracy reaches 94%. And if we increase to 20 epochs, a 96% accuracy is achieved.
In short, an immense world of possibilities will be seen in more detail in the following section, where the reader can realize that finding the best architecture with the best parameters and hyperparameters of activation functions requires some expertise and experience given the multiple possibilities that we have.
So far, for simplicity, we have not paid explicit attention to differentiating between parameters and hyperparameters, but I think the time has come. In general, we consider a parameter of the model as a configuration variable that is internal to the model and whose value can be estimated from the data. In contrast, by hyperparameter we refer to configuration variables that are external to the model itself and whose value in general cannot be estimated from the data, and are specified by the programmer to adjust the learning algorithms.
When I say that Deep Learning is more an art than a science, I mean that it takes a lot of experience and intuition to find the optimal values of these hyperparameters, which must be specified before starting the training process so that the models train better and more quickly. Given the introductory nature of the book we will not go into detail about all of them, but we have hyperparameters that are worth mentioning briefly, both at the structure and topology level of the neural network (number of layers, number of neurons, their activation functions, etc.) and at the learning algorithm level (learning rate, momentum, epochs, batch size, etc.).
Next, we will introduce some of them and the rest will appear in a futuro post as we go into convolutional neural network.
As we have already done, epochs tells us the number of times all the training data have passed through the neural network in the training process. A good clue is to increase the number of epochs until the accuracy metric with the validation data starts to decrease, even when the accuracy of the training data continues to increase (this is when we detect a potential overfitting).
As we have said before, we can partition the training data in mini batches to pass them through the network. In Keras, the batch_size is the argument that indicates the size of these batches that will be used in the fit() method in an iteration of the training to update the gradient. The optimal size will depend on many factors, including the memory capacity of the computer that we use to do the calculations.
The gradient vector has a direction and a magnitude. Gradient descent algorithms multiply the magnitude of the gradient by a scalar known as learning rate (also sometimes called step size) to determine the next point.
In a more formal way, the backpropagation algorithm computes how the error changes with respect to each weight:
In order to update each weight of the network using a simple update rule:
Where α is the learning rate.
For example, if the magnitude of the gradient is 1.5 and the learning rate is 0.01, then the gradient descent algorithm will select the next point at 0.015 from the previous point.
The proper value of this hyperparameter is very dependent on the problem in question, but in general, if this is too big, huge steps are being made, which could be good to go faster in the learning process. But in this case, we may skip the minimum and make it difficult for the learning process to stop because, when searching for the next point, it perpetually bounces randomly at the bottom of the “well”. Visually we can see in this figure the effect that can occur, where the minimum value is never reached (indicated with a small arrow in the drawing):
Contrarily, if the learning rate is small, small advances will be made, having a better chance of reaching a local minimum, but this can cause the learning process to be very slow. In general, a good rule is to decrease the learning rate if our learning model does not work. If we know that the gradient of the loss function is small, then it is safe to test that it compensates the gradient with the learning rate.
But the best learning rate in general is one that decreases as the model approaches a solution. To achieve this effect, we have another hyperparameter, the learning rate decay, which is used to decrease the learning rate as epochs go by to allow learning to advance faster at the beginning with larger learning rates. As progress is made, smaller and smaller adjustments are made to facilitate the convergence of the training process to the minimum of the loss function.
In the visual example with which we have explained the descent gradient algorithm, to minimize the loss function we have the guarantee of finding the global minimum because there is no local minimum in which the optimization process can be stuck. However, in reality, the real cases are more complex and, visually, it is as if we could find several local minimums and the loss function had a form like the one in the following figure:
In this case, the optimizer can easily get stuck at a local minimum and the algorithm may think that the global minimum has been reached, leading to suboptimal results. The reason is that the moment we get stuck, the gradient is zero and we can no longer get out of the local minimum strictly following the path of the gradient.
One way to solve this situation could be to restart the process from different random positions and, in this way, increase the probability of reaching the global minimum.
To avoid this situation, another solution that is generally used involves the momentum hyperparameter. In an intuitive way, we can see it as if, to move forward, it will take the weighted average of the previous steps to obtain a bit of impetus and overcome the “bumps” as a way of not getting stuck in local minima. If we consider that the average of the previous ones was better, perhaps it will allow us to make the jump.
But using the average has proved to be a very drastic solution because, perhaps in gradients of previous steps, it is much less relevant than just in the previous one. That is why we have chosen to weight the previous gradients, and the momentum is a constant between 0 and 1 that is used for this weighting. It has been shown that algorithms that use momentum work better in practice.
One variant is the Nesterov momentum, which is a slightly different version of the momentum update that has recently gained popularity and which basically slows down the gradient when it is close to the solution.
The initialization of the parameters’ weight is not exactly a hyperparameter, but it is as important as any of them and that is why we make a brief paragraph in this section. It is advisable to initialize the weights with small random values to break the symmetry between different neurons, if two neurons have exactly the same weights they will always have the same gradient; that supposes that both have the same values in the subsequent iterations, so they will not be able to learn different characteristics.
Initializing the parameters randomly following a standard normal distribution is correct, but it can lead to possible problems of vanishing gradients (when the values of a gradient are too small and the model stops learning or takes too long due to that) or exploding gradients (when the algorithm assigns an exaggeratedly high importance to the weights).
In general, heuristics can be used taking into account the type of activation functions that our network has. It is outside the introductory level of this book to go into these details but, if the reader wants to go deeper, I suggest that you visit the CS231n course website of Andrej Karpathy in Stanford, where you will obtain very valuable knowledge in this area exposed in a very didactic way.
How can we specify these hyperparameters? Recall that the optimizer is one of the arguments that are required in the compile() method of the model. So far we have called them by their name (with a simple strings that identifies them), but Keras also allows to pass an instance of the optimizer class as an argument with the specification of some hyperparameters.
For example, the stochastic gradient descent optimizer allows the use of the momentum, learning rate decay and Nesterov momentum hyperparameters:
keras.optimizers.SGD(lr=0.01, momentum=0.0, decay=0.0, nesterov=False)
The values indicated in the arguments of the previous method are those taken by default and whose range can be:
lr: float >= 0. (learning rate)
momentum: float >= 0
decay: float >= 0 (learning rate decay).
nesterov: boolean (which indicates whether or not to use Nesterov momentum).
As we have said, there are several optimizers in Keras that the reader can explore on their documentation page.
TensorFlow Playground is an interactive visualization web application written in JavaScript that allows us to simulate simple neural networks that run in our browser and see the results in real time:
With this tool we can experiment with different hyperparameters and see their behavior. In fact, the flexibility provided by the hyperparameters in neural networks is one of its virtues and at the same time one of its drawbacks for those who start on the subject: there are many of them to adjust!
To begin to understand how the tool works we can use the first example of perceptron presented in a previous post, a simple classification problem.
To start with this example, we chose the dataset indicated in the “DATA” section shown in the previous figure, and then click on the “Play” button. Now we can see how TensorFlow Playground solves this particular problem. The line between the blue and orange area begins to move slowly. You can press the “Reset” button and re-test it several times to see how the line moves with different initial values.
In this case, the application tries to find the best values of the parameters that allow classifying these points correctly. If the cursor is put over the arcs, the reader will see that the value that has been assigned to each parameter appears (and it even allows us to edit it):
Remember that this weight dictates the importance of this relationship in the neuron when multiplying it by the input value.
After this first contact, we will present a little the tool that will allow us to understand how a neural network behaves. In the upper part of the menu, we basically find hyperparameters, some of which we already commented in the previous section: Epoch, Learning rate, Activation, Regularization rate, and Problem type. All of them are drop-down menus in which we can choose the value of these hyperparameters.
In the “Problem type” tab, the platform allows us to specify two types of problems: Regression (continuous problem) and Classification. In total, there are four types of data that we can choose for classification and two types for regression:
The blue and orange dots form the dataset. The orange points have the value -1 and the blue points the value +1. On the left side, below the data type, there are different parameters that we can modify to tune our input data.
Using the tab “Ratio of training to test data” we can control the percentage of data that is assigned to the training set (if we modify it we see how the points that appear in the “OUTPUT” on the right side of the screen are changed interactively). The noise level of the data can also be defined and controlled by the “Noise” field; the data pattern becomes more irregular as the noise increases. As we can experience, when the noise is zero, the problem data are clearly distinguished in their regions. However, when reaching more than 50, we can see that the blue dots and the orange dots are mixed, so it is very difficult to classify them.
With “Batch size”, as its name suggests, we can determine the amount of data that will be used for each training batch.
Then, in the next column, we can make the selection of features. I propose that we use “X1” and “X2” among the many available to us: “X1” is a value on the horizontal axis, and “X2” is the value on the vertical axis.
The topology of the neuronal network can be defined in the following column. We can have up to six hidden layers (by adding hidden layers, by clicking on the “+” sign) and we can have up to eight neurons per hidden layer (by clicking on the “+” sign of the corresponding layer):
Finally, remember that when training the neural network we want to minimize the “Training loss” and then compare that with the test data the “Test loss” is also minimized. The changes of both metrics in each epoch are shown interactively in the upper right part of the screen, in a small graph where, if the loss is reduced, the curve goes downwards. The loss test is painted in black, and the training loss is painted in gray.
Classification with a single neuron
Now that we know a bit more about this tool, let’s return to the first classification example that separates the data into two groups (clusters).
I propose that we modify some parameters to practice with the tool before moving forward. For example, we can modify some parameters with a learning rate of 0.03 and a ReLU activation function (the regularization is not going to be used since it is outside the scope of this book).
We maintain the problem as classification, and I propose that we put the “ratio of training-to-test” to 50% of the data and that we also keep the “noise” parameter to zero to facilitate the visualization of the solution (although I suggest that later you practice with it on your own). We can leave the “batch size” at 10.
And, as before, we will use “X1” and “X2” for the input. I suggest starting with a single hidden layer with a single neuron. We can achieve this by using the “-” or “+” buttons:
In the upper right, we see that the initial values of the “Test loss” and “Training loss” are high (the reader can get different values since the initial values are generated in a random way). But after pressing the “play” button, it can be seen that both the “Training loss” and the “Test loss” converge at very low ratios and remain the same. Moreover, in this case, both lines, black and gray, perfectly overlap.
Classification with more than one neuron
Let’s choose another set of starting data like the one in the attached figure:
We now want to separate the two datasets: the orange ones must be classified in one group and the blue ones in another. But the problem is that in this case they will have a circular shape where the orange points will be in the outer circle and the blue points will be inside. Now, these points cannot be separated with a single line as before. If we train with a hidden layer that has a single neuron as the model of the previous classification, the classification will fail in this case.
I suggest that we test with multiple neurons in the hidden layer. For example, try two neurons: you will see that you have not tuned enough yet. I propose that you then try with three. You will see that, in the end, you can get a much better training and test loss:
Let’s go for another of the datasets on the left, that where the data is divided into four different square zones. Now, this problem cannot be solved with the previous network, but I propose that you try it:
As can be seen, we are not able to get a good classification (although in some cases it could happen that with only 3 neurons it works since the initialization is random, but if you do several tests you will see that it is not achieved in general). However, if we have 5 neurons as in the following figure, the reader can see how this neural network gets a good classification for this case:
Classification with several layers
Now we will try to classify the dataset with the most complex pattern that we have in this tool. The swirling structure of the orange and blue data points is a challenging problem. If we rely on the previous network, we see that not even having 8 neurons, the maximum that the tool leaves us, we get a good classification result:
If the reader has tried it, in this case I suppose that you will get a few good values for the test loss. The time has come to put more layers; I assure you that, if you use all the layers the tool allows, you will get it:
But you will see that, as it is obvious, the process of learning the parameters takes a long time.
Actually, with fewer layers or neurons you can get good results; I challenge you to play a little on your own, also changing for example the activation functions to get a simpler model. You can also consider testing any other parameter.
This tool only considers dense neural networks; later we will see that the convolutional neural networks (and the recurrent neural networks) present more complex dilemmas. But only with these dense networks can we see that one of the most difficult hyperparameters to adjust is to decide how many layers the model has and how many neurons each of these layers has.
Using very few neurons in the hidden layers will result in what is called underfitting, a lack of fit of the model because there are very few neurons in the hidden layers to properly detect the signals in a complicated dataset.
On the other hand, using too many neurons in the hidden layers can cause several problems. First, it can produce overfitting, which occurs when the neural network has so much information processing capacity that the limited amount of information contained in the training set is not enough to train all the neurons in the hidden layers. But on the other hand, a large number of neurons in the hidden layers can increase the time needed to train the network to the point that it is impossible to properly train the neural network in the necessary time.
Obviously, we must reach a compromise between too many and very few neurons in the hidden layers and that is why I have already commented that we are facing a challenge that requires more art than science.
I hope that this post have been helpful and you will use them at work or in college. You can reed the next one about Convolutional Neural Networks here. | [
{
"code": null,
"e": 507,
"s": 172,
"text": "This is the updated version of the fifth post (post 3, post 4) in the series that I wrote two years ago. In it I will present an intuitive vision of the main components of the learning process of a neural network using as a example Keras, that has become the TensorFlow's high-level API for building and training deep learning models."
},
{
"code": null,
"e": 633,
"s": 507,
"text": "Finally, we will put into practice some of the concepts presented here with an interactive tool called TensorFlow Playground."
},
{
"code": null,
"e": 881,
"s": 633,
"text": "A neural network is made up of neurons connected to each other; at the same time, each connection of our neural network is associated with a weight that dictates the importance of this relationship in the neuron when multiplied by the input value."
},
{
"code": null,
"e": 1147,
"s": 881,
"text": "Each neuron has an activation function that defines the output of the neuron. The activation function is used to introduce non-linearity in the modeling capabilities of the network. We have several options for activation functions that we will present in this post."
},
{
"code": null,
"e": 1288,
"s": 1147,
"text": "Following the previous simplified representation, we could represent the model presented in the previous post that classify MNIST digits as:"
},
{
"code": null,
"e": 1676,
"s": 1288,
"text": "Training our neural network, that is, learning the values of our parameters (weights wij and bj biases) is the most genuine part of Deep Learning and we can see this learning process in a neural network as an iterative process of “going and return” by the layers of neurons. The “going” is a forwardpropagation of the information and the “return” is a backpropagation of the information."
},
{
"code": null,
"e": 2276,
"s": 1676,
"text": "The first phase forwardpropagation occurs when the network is exposed to the training data and these cross the entire neural network for their predictions (labels) to be calculated. That is, passing the input data through the network in such a way that all the neurons apply their transformation to the information they receive from the neurons of the previous layer and sending it to the neurons of the next layer. When the data has crossed all the layers, and all its neurons have made their calculations, the final layer will be reached with a result of label prediction for those input examples."
},
{
"code": null,
"e": 2819,
"s": 2276,
"text": "Next, we will use a loss function to estimate the loss (or error) and to compare and measure how good/bad our prediction result was in relation to the correct result (remember that we are in a supervised learning environment and we have the label that tells us the expected value). Ideally, we want our cost to be zero, that is, without divergence between estimated and expected value. Therefore, as the model is being trained, the weights of the interconnections of the neurons will gradually be adjusted until good predictions are obtained."
},
{
"code": null,
"e": 3433,
"s": 2819,
"text": "Once the loss has been calculated, this information is propagated backwards. Hence, its name: backpropagation. Starting from the output layer, that loss information propagates to all the neurons in the hidden layer that contribute directly to the output. However, the neurons of the hidden layer only receive a fraction of the total signal of the loss, based on the relative contribution that each neuron has contributed to the original output. This process is repeated, layer by layer, until all the neurons in the network have received a loss signal that describes their relative contribution to the total loss."
},
{
"code": null,
"e": 3591,
"s": 3433,
"text": "Visually, we can summarize what we have explained with this visual scheme of the stages (based in the previous visual represeentation of our neural network):"
},
{
"code": null,
"e": 4257,
"s": 3591,
"text": "Now that we have spread this information back, we can adjust the weights of connections between neurons. What we are doing is making the loss as close as possible to zero the next time we go back to using the network for a prediction. For this, we will use a technique called gradient descent. This technique changes the weights in small increments with the help of the calculation of the derivative (or gradient) of the loss function, which allows us to see in which direction “to descend” towards the global minimum; this is done in general in batches of data in the successive iterations (epochs) of all the dataset that we pass to the network in each iteration."
},
{
"code": null,
"e": 4303,
"s": 4257,
"text": "To recap, the learning algorithm consists of:"
},
{
"code": null,
"e": 4999,
"s": 4303,
"text": "Start with values (often random) for the network parameters (wij weights and bj biases).Take a set of examples of input data and pass them through the network to obtain their prediction.Compare these predictions obtained with the values of expected labels and calculate the loss with them.Perform the backpropagation in order to propagate this loss to each and every one of the parameters that make up the model of the neural network.Use this propagated information to update the parameters of the neural network with the gradient descent in a way that the total loss is reduced and a better model is obtained.Continue iterating in the previous steps until we consider that we have a good model."
},
{
"code": null,
"e": 5088,
"s": 4999,
"text": "Start with values (often random) for the network parameters (wij weights and bj biases)."
},
{
"code": null,
"e": 5187,
"s": 5088,
"text": "Take a set of examples of input data and pass them through the network to obtain their prediction."
},
{
"code": null,
"e": 5291,
"s": 5187,
"text": "Compare these predictions obtained with the values of expected labels and calculate the loss with them."
},
{
"code": null,
"e": 5437,
"s": 5291,
"text": "Perform the backpropagation in order to propagate this loss to each and every one of the parameters that make up the model of the neural network."
},
{
"code": null,
"e": 5614,
"s": 5437,
"text": "Use this propagated information to update the parameters of the neural network with the gradient descent in a way that the total loss is reduced and a better model is obtained."
},
{
"code": null,
"e": 5700,
"s": 5614,
"text": "Continue iterating in the previous steps until we consider that we have a good model."
},
{
"code": null,
"e": 5795,
"s": 5700,
"text": "Below we present in more detail each of the elements that we have highlighted in this section."
},
{
"code": null,
"e": 6268,
"s": 5795,
"text": "Remember that we use the activation functions to propagate the output of a neuron forward. This output is received by the neurons of the next layer to which this neuron is connected (up to the output layer included). As we have said, the activation function serves to introduce non-linearity in the modeling capabilities of the network. Below we will list the most used nowadays; all of them can be used in a layer of Keras (we can find more information on their website)."
},
{
"code": null,
"e": 6406,
"s": 6268,
"text": "The linear activation function is basically the identity function in which, in practical terms, it means that the signal does not change."
},
{
"code": null,
"e": 6769,
"s": 6406,
"text": "The sigmoid function has already been introduced in a previous post. Its interest lies in the fact that it allows a reduction in extreme or atypical values in valid data without eliminating them: it converts independent variables of almost infinite range into simple probabilities between 0 and 1. Most of its output will be very close to the extremes of 0 or 1."
},
{
"code": null,
"e": 7153,
"s": 6769,
"text": "Without going into detail, we can summarize that the tanh represents the relationship between the hyperbolic sine and the hyperbolic cosine: tanh(x)=sinh(x)/cosh(x). Unlike the sigmoid function, the normalized range of tanh is between -1 and 1, which is the input that goes well with some neural networks. The advantage of tanh is that negative numbers can be dealt with more easily."
},
{
"code": null,
"e": 7536,
"s": 7153,
"text": "The softmax activation function was also presented in a previous post to generalize the logistic regression, insofar as instead of classifying in binary it can contain multiple decision limits. As we have seen, the softmax activation function will often be found in the output layer of a neural network and return the probability distribution over mutually exclusive output classes."
},
{
"code": null,
"e": 8032,
"s": 7536,
"text": "The activation function rectified linear unit (ReLU) is a very interesting transformation that activates a single node if the input is above a certain threshold. The default and more usual behavior is that, as long as the input has a value below zero, the output will be zero but, when the input rises above, the output is a linear relationship with the input variable of the form f(x)=x. The ReLU activation function has proven to work in many different situations and is currently widely used."
},
{
"code": null,
"e": 8374,
"s": 8032,
"text": "In summary, we can consider backpropagation as a method to alter the parameters (weights and biases) of the neural network in the right direction. It starts by calculating the loss term first, and then the parameters of the neural network are adjusted in reverse order with an optimization algorithm taking into account this calculated loss."
},
{
"code": null,
"e": 8514,
"s": 8374,
"text": "Remember that in Keras the compile() method allows us to define how we want the components that are involved in the learning process to be:"
},
{
"code": null,
"e": 8626,
"s": 8514,
"text": "model.compile(loss=’categorical_crossentropy’, optimizer=’sgd’, metrics=[‘accuracy’])"
},
{
"code": null,
"e": 8875,
"s": 8626,
"text": "Specifically, in this example, three arguments are passed to the method: an optimizer, a loss function, and a list of metrics. In classification problems like our example, accuracy is used as a metric. Let’s go a little deeper into these arguments."
},
{
"code": null,
"e": 9027,
"s": 8875,
"text": "A loss function is one of the parameters required to quantify how close a particular neural network is to the ideal weight during the training process."
},
{
"code": null,
"e": 9449,
"s": 9027,
"text": "In the Keras manual page, we can find all types of loss functions available. Some have their concrete hyperparameters that must be indicated; in the example of the previous post, when we use categorical_crossentropy as a function of loss, our output must be in a categorical format. The choice of the best function of loss resides in understanding what type of error is or is not acceptable for the problem in particular."
},
{
"code": null,
"e": 9710,
"s": 9449,
"text": "The optimizer is another of the arguments required in the compile() method. Keras currently has different optimizers that can be used: SGD, RMSprop, Adagrad, Adadelta, Adam, Adamax, Nadam. You can find more detail about each of them in the Keras documentation."
},
{
"code": null,
"e": 10078,
"s": 9710,
"text": "In general, we can see the learning process as a global optimization problem where the parameters (weights and biases) must be adjusted in such a way that the loss function presented above is minimized. In most cases, these parameters cannot be solved analytically, but in general they can be approached well with optimizing algorithms, such as those mentioned above."
},
{
"code": null,
"e": 10344,
"s": 10078,
"text": "We will explain one of the concrete optimizers so that you understand the overall operation of the optimizers. Specifically, the gradient descent, the basis of many optimizers and one of the most common optimization algorithms in Machine Learning and Deep Learning."
},
{
"code": null,
"e": 11267,
"s": 10344,
"text": "Gradient descent uses the first derivative (gradient) of the loss function when updating the parameters. Remember that the gradient gives us the slope of a function at that point. Without being able to go into detail, the process consists in chaining the derivatives of the loss of each hidden layer from the derivatives of the loss of its upper layer, incorporating its activation function in the calculation (that’s why the activation functions must be derivable). In each of the iterations, once all the neurons have the value of the gradient of the loss function that corresponds to them, the values of the parameters are updated in the opposite direction to that indicated by the gradient. The gradient, in fact, always points in the direction in which the value of the loss function increases. Therefore, if the negative of the gradient is used, we can get the direction in which we tend to reduce the loss function."
},
{
"code": null,
"e": 11527,
"s": 11267,
"text": "Let’s see the process in a visual way assuming only one dimension: suppose that this line represents the values that the loss function takes for each possible parameter value and that the negative of the gradient is depicted by the arrow in the initial point:"
},
{
"code": null,
"e": 12072,
"s": 11527,
"text": "To determine the next value for the parameter, the gradient descent algorithm modifies the value of the initial weight to go in the opposite way to the gradient (since it points in the direction in which the loss grows and we want to reduce it), adding a proportional amount to this. The magnitude of this change is determined by the value of the gradient and by a learning rate hyperparameter that we can specify (which we will present shortly). Therefore, conceptually, it is as if we follow the slope downhill until we reach a local minimum:"
},
{
"code": null,
"e": 12262,
"s": 12072,
"text": "The gradient descent algorithm repeats this process getting closer and closer to the minimum until the value of the parameter reaches a point beyond which the loss function cannot decrease:"
},
{
"code": null,
"e": 12373,
"s": 12262,
"text": "In the previous sections we have seen how the values of the parameters are adjusted but not in what frequency:"
},
{
"code": null,
"e": 12399,
"s": 12373,
"text": "After each entry example?"
},
{
"code": null,
"e": 12463,
"s": 12399,
"text": "After each round of the whole set of training examples (epoch)?"
},
{
"code": null,
"e": 12511,
"s": 12463,
"text": "After a sample of examples of the training set?"
},
{
"code": null,
"e": 12997,
"s": 12511,
"text": "In the first case we speak of online learning, when the gradient is estimated from the observed loss for each example of the training; it is also when we talk about Stochastic Gradient Descent (SGD). The second is known as batch learning and is called Batch Gradient Descent. The literature indicates that, usually, better results can be obtained with online learning, but there are reasons that justify the use of batch learning because many optimization techniques only work with it."
},
{
"code": null,
"e": 13657,
"s": 12997,
"text": "But if the data is well distributed, a small subset of them should give us a pretty good approximation of the gradient. We may not get the best estimate, but it is faster and, given the fact that we are iterating, this approach is very useful. For this reason, the third aforementioned option known as mini-batch is often used. This option is usually as good as the online, but fewer calculations are required to update the parameters of the neural network. In addition, the simultaneous calculation of the gradient for many input examples can be done using matrix operations that are implemented very efficiently with GPU, as we have seen in a previous post."
},
{
"code": null,
"e": 14169,
"s": 13657,
"text": "That’s why, in reality, many applications use the stochastic gradient descent (SGD) with a mini-bach of several examples. To use all the data, what is done is to partition the data in several batches. Then we take the first batch, go through the network, calculate the gradient of its loss and update the parameters of the neural network; this would follow successively until the last batch. Now, in a single pass through all the input data, only a number of steps have been made equal to the number of batches."
},
{
"code": null,
"e": 14423,
"s": 14169,
"text": "SGD is very easy to implement in Keras. In the compile() method it is indicated that the optimizer is SGD (value sgd in the argument), and then all that must be done is to specify the batch size in the training process with the fit() method as follows :"
},
{
"code": null,
"e": 14477,
"s": 14423,
"text": "model.fit(X_train, y_train, epochs=5, batch_size=100)"
},
{
"code": null,
"e": 14825,
"s": 14477,
"text": "In this code example that uses the fit() method, we are dividing our data into batches of 100 with the batch_size argument. With the number of epochs we are indicating how many times we carry out this process on all the data. Later in this post, when we have already presented the usual optimizer parameters, we will return to these two arguments."
},
{
"code": null,
"e": 15170,
"s": 14825,
"text": "If the reader at the end of the previous post has executed a model with the hyperparameters that we use there, I assume that the model’s accuracy will have exceeded 90%. Are these results good? I think they are fantastic, because it means that the reader has already programmed and executed his first neural network with Keras. Congratulations!"
},
{
"code": null,
"e": 15510,
"s": 15170,
"text": "Another thing is that there are other models that improve accuracy. And this depends on having a great knowledge and a lot of practice to handle well with the many hyperparameters that we can change. For example, with a simple change of the activation function of the first layer, passing from a sigmoid to a relu like the one shown below:"
},
{
"code": null,
"e": 15570,
"s": 15510,
"text": "model.add(Dense(10, activation=’relu’, input_shape=(784,)))"
},
{
"code": null,
"e": 15643,
"s": 15570,
"text": "We can get 2% more accuracy with more or less the same calculation time."
},
{
"code": null,
"e": 15951,
"s": 15643,
"text": "It is also possible to increase the number of epochs, add more neurons in a layer or add more layers. However, in these cases, the gains in accuracy have the side effect of increasing the execution time of the learning process. For example, if we add 512 nodes to the intermediate layer instead of 10 nodes:"
},
{
"code": null,
"e": 16012,
"s": 15951,
"text": "model.add(Dense(512, activation=’relu’, input_shape=(784,)))"
},
{
"code": null,
"e": 16305,
"s": 16012,
"text": "We can check with the summary() method that the number of parameters increases (it is a fully connected) and the execution time is significantly higher, even reducing the number of epochs. With this model, the accuracy reaches 94%. And if we increase to 20 epochs, a 96% accuracy is achieved."
},
{
"code": null,
"e": 16622,
"s": 16305,
"text": "In short, an immense world of possibilities will be seen in more detail in the following section, where the reader can realize that finding the best architecture with the best parameters and hyperparameters of activation functions requires some expertise and experience given the multiple possibilities that we have."
},
{
"code": null,
"e": 17165,
"s": 16622,
"text": "So far, for simplicity, we have not paid explicit attention to differentiating between parameters and hyperparameters, but I think the time has come. In general, we consider a parameter of the model as a configuration variable that is internal to the model and whose value can be estimated from the data. In contrast, by hyperparameter we refer to configuration variables that are external to the model itself and whose value in general cannot be estimated from the data, and are specified by the programmer to adjust the learning algorithms."
},
{
"code": null,
"e": 17820,
"s": 17165,
"text": "When I say that Deep Learning is more an art than a science, I mean that it takes a lot of experience and intuition to find the optimal values of these hyperparameters, which must be specified before starting the training process so that the models train better and more quickly. Given the introductory nature of the book we will not go into detail about all of them, but we have hyperparameters that are worth mentioning briefly, both at the structure and topology level of the neural network (number of layers, number of neurons, their activation functions, etc.) and at the learning algorithm level (learning rate, momentum, epochs, batch size, etc.)."
},
{
"code": null,
"e": 17943,
"s": 17820,
"text": "Next, we will introduce some of them and the rest will appear in a futuro post as we go into convolutional neural network."
},
{
"code": null,
"e": 18325,
"s": 17943,
"text": "As we have already done, epochs tells us the number of times all the training data have passed through the neural network in the training process. A good clue is to increase the number of epochs until the accuracy metric with the validation data starts to decrease, even when the accuracy of the training data continues to increase (this is when we detect a potential overfitting)."
},
{
"code": null,
"e": 18738,
"s": 18325,
"text": "As we have said before, we can partition the training data in mini batches to pass them through the network. In Keras, the batch_size is the argument that indicates the size of these batches that will be used in the fit() method in an iteration of the training to update the gradient. The optimal size will depend on many factors, including the memory capacity of the computer that we use to do the calculations."
},
{
"code": null,
"e": 18956,
"s": 18738,
"text": "The gradient vector has a direction and a magnitude. Gradient descent algorithms multiply the magnitude of the gradient by a scalar known as learning rate (also sometimes called step size) to determine the next point."
},
{
"code": null,
"e": 19068,
"s": 18956,
"text": "In a more formal way, the backpropagation algorithm computes how the error changes with respect to each weight:"
},
{
"code": null,
"e": 19142,
"s": 19068,
"text": "In order to update each weight of the network using a simple update rule:"
},
{
"code": null,
"e": 19172,
"s": 19142,
"text": "Where α is the learning rate."
},
{
"code": null,
"e": 19353,
"s": 19172,
"text": "For example, if the magnitude of the gradient is 1.5 and the learning rate is 0.01, then the gradient descent algorithm will select the next point at 0.015 from the previous point."
},
{
"code": null,
"e": 19912,
"s": 19353,
"text": "The proper value of this hyperparameter is very dependent on the problem in question, but in general, if this is too big, huge steps are being made, which could be good to go faster in the learning process. But in this case, we may skip the minimum and make it difficult for the learning process to stop because, when searching for the next point, it perpetually bounces randomly at the bottom of the “well”. Visually we can see in this figure the effect that can occur, where the minimum value is never reached (indicated with a small arrow in the drawing):"
},
{
"code": null,
"e": 20328,
"s": 19912,
"text": "Contrarily, if the learning rate is small, small advances will be made, having a better chance of reaching a local minimum, but this can cause the learning process to be very slow. In general, a good rule is to decrease the learning rate if our learning model does not work. If we know that the gradient of the loss function is small, then it is safe to test that it compensates the gradient with the learning rate."
},
{
"code": null,
"e": 20799,
"s": 20328,
"text": "But the best learning rate in general is one that decreases as the model approaches a solution. To achieve this effect, we have another hyperparameter, the learning rate decay, which is used to decrease the learning rate as epochs go by to allow learning to advance faster at the beginning with larger learning rates. As progress is made, smaller and smaller adjustments are made to facilitate the convergence of the training process to the minimum of the loss function."
},
{
"code": null,
"e": 21234,
"s": 20799,
"text": "In the visual example with which we have explained the descent gradient algorithm, to minimize the loss function we have the guarantee of finding the global minimum because there is no local minimum in which the optimization process can be stuck. However, in reality, the real cases are more complex and, visually, it is as if we could find several local minimums and the loss function had a form like the one in the following figure:"
},
{
"code": null,
"e": 21563,
"s": 21234,
"text": "In this case, the optimizer can easily get stuck at a local minimum and the algorithm may think that the global minimum has been reached, leading to suboptimal results. The reason is that the moment we get stuck, the gradient is zero and we can no longer get out of the local minimum strictly following the path of the gradient."
},
{
"code": null,
"e": 21734,
"s": 21563,
"text": "One way to solve this situation could be to restart the process from different random positions and, in this way, increase the probability of reaching the global minimum."
},
{
"code": null,
"e": 22159,
"s": 21734,
"text": "To avoid this situation, another solution that is generally used involves the momentum hyperparameter. In an intuitive way, we can see it as if, to move forward, it will take the weighted average of the previous steps to obtain a bit of impetus and overcome the “bumps” as a way of not getting stuck in local minima. If we consider that the average of the previous ones was better, perhaps it will allow us to make the jump."
},
{
"code": null,
"e": 22545,
"s": 22159,
"text": "But using the average has proved to be a very drastic solution because, perhaps in gradients of previous steps, it is much less relevant than just in the previous one. That is why we have chosen to weight the previous gradients, and the momentum is a constant between 0 and 1 that is used for this weighting. It has been shown that algorithms that use momentum work better in practice."
},
{
"code": null,
"e": 22758,
"s": 22545,
"text": "One variant is the Nesterov momentum, which is a slightly different version of the momentum update that has recently gained popularity and which basically slows down the gradient when it is close to the solution."
},
{
"code": null,
"e": 23271,
"s": 22758,
"text": "The initialization of the parameters’ weight is not exactly a hyperparameter, but it is as important as any of them and that is why we make a brief paragraph in this section. It is advisable to initialize the weights with small random values to break the symmetry between different neurons, if two neurons have exactly the same weights they will always have the same gradient; that supposes that both have the same values in the subsequent iterations, so they will not be able to learn different characteristics."
},
{
"code": null,
"e": 23627,
"s": 23271,
"text": "Initializing the parameters randomly following a standard normal distribution is correct, but it can lead to possible problems of vanishing gradients (when the values of a gradient are too small and the model stops learning or takes too long due to that) or exploding gradients (when the algorithm assigns an exaggeratedly high importance to the weights)."
},
{
"code": null,
"e": 24025,
"s": 23627,
"text": "In general, heuristics can be used taking into account the type of activation functions that our network has. It is outside the introductory level of this book to go into these details but, if the reader wants to go deeper, I suggest that you visit the CS231n course website of Andrej Karpathy in Stanford, where you will obtain very valuable knowledge in this area exposed in a very didactic way."
},
{
"code": null,
"e": 24388,
"s": 24025,
"text": "How can we specify these hyperparameters? Recall that the optimizer is one of the arguments that are required in the compile() method of the model. So far we have called them by their name (with a simple strings that identifies them), but Keras also allows to pass an instance of the optimizer class as an argument with the specification of some hyperparameters."
},
{
"code": null,
"e": 24534,
"s": 24388,
"text": "For example, the stochastic gradient descent optimizer allows the use of the momentum, learning rate decay and Nesterov momentum hyperparameters:"
},
{
"code": null,
"e": 24631,
"s": 24534,
"text": "keras.optimizers.SGD(lr=0.01, momentum=0.0, decay=0.0, nesterov=False)"
},
{
"code": null,
"e": 24743,
"s": 24631,
"text": "The values indicated in the arguments of the previous method are those taken by default and whose range can be:"
},
{
"code": null,
"e": 24775,
"s": 24743,
"text": "lr: float >= 0. (learning rate)"
},
{
"code": null,
"e": 24796,
"s": 24775,
"text": "momentum: float >= 0"
},
{
"code": null,
"e": 24837,
"s": 24796,
"text": "decay: float >= 0 (learning rate decay)."
},
{
"code": null,
"e": 24914,
"s": 24837,
"text": "nesterov: boolean (which indicates whether or not to use Nesterov momentum)."
},
{
"code": null,
"e": 25026,
"s": 24914,
"text": "As we have said, there are several optimizers in Keras that the reader can explore on their documentation page."
},
{
"code": null,
"e": 25226,
"s": 25026,
"text": "TensorFlow Playground is an interactive visualization web application written in JavaScript that allows us to simulate simple neural networks that run in our browser and see the results in real time:"
},
{
"code": null,
"e": 25524,
"s": 25226,
"text": "With this tool we can experiment with different hyperparameters and see their behavior. In fact, the flexibility provided by the hyperparameters in neural networks is one of its virtues and at the same time one of its drawbacks for those who start on the subject: there are many of them to adjust!"
},
{
"code": null,
"e": 25672,
"s": 25524,
"text": "To begin to understand how the tool works we can use the first example of perceptron presented in a previous post, a simple classification problem."
},
{
"code": null,
"e": 26077,
"s": 25672,
"text": "To start with this example, we chose the dataset indicated in the “DATA” section shown in the previous figure, and then click on the “Play” button. Now we can see how TensorFlow Playground solves this particular problem. The line between the blue and orange area begins to move slowly. You can press the “Reset” button and re-test it several times to see how the line moves with different initial values."
},
{
"code": null,
"e": 26358,
"s": 26077,
"text": "In this case, the application tries to find the best values of the parameters that allow classifying these points correctly. If the cursor is put over the arcs, the reader will see that the value that has been assigned to each parameter appears (and it even allows us to edit it):"
},
{
"code": null,
"e": 26483,
"s": 26358,
"text": "Remember that this weight dictates the importance of this relationship in the neuron when multiplying it by the input value."
},
{
"code": null,
"e": 26896,
"s": 26483,
"text": "After this first contact, we will present a little the tool that will allow us to understand how a neural network behaves. In the upper part of the menu, we basically find hyperparameters, some of which we already commented in the previous section: Epoch, Learning rate, Activation, Regularization rate, and Problem type. All of them are drop-down menus in which we can choose the value of these hyperparameters."
},
{
"code": null,
"e": 27139,
"s": 26896,
"text": "In the “Problem type” tab, the platform allows us to specify two types of problems: Regression (continuous problem) and Classification. In total, there are four types of data that we can choose for classification and two types for regression:"
},
{
"code": null,
"e": 27365,
"s": 27139,
"text": "The blue and orange dots form the dataset. The orange points have the value -1 and the blue points the value +1. On the left side, below the data type, there are different parameters that we can modify to tune our input data."
},
{
"code": null,
"e": 28010,
"s": 27365,
"text": "Using the tab “Ratio of training to test data” we can control the percentage of data that is assigned to the training set (if we modify it we see how the points that appear in the “OUTPUT” on the right side of the screen are changed interactively). The noise level of the data can also be defined and controlled by the “Noise” field; the data pattern becomes more irregular as the noise increases. As we can experience, when the noise is zero, the problem data are clearly distinguished in their regions. However, when reaching more than 50, we can see that the blue dots and the orange dots are mixed, so it is very difficult to classify them."
},
{
"code": null,
"e": 28130,
"s": 28010,
"text": "With “Batch size”, as its name suggests, we can determine the amount of data that will be used for each training batch."
},
{
"code": null,
"e": 28347,
"s": 28130,
"text": "Then, in the next column, we can make the selection of features. I propose that we use “X1” and “X2” among the many available to us: “X1” is a value on the horizontal axis, and “X2” is the value on the vertical axis."
},
{
"code": null,
"e": 28626,
"s": 28347,
"text": "The topology of the neuronal network can be defined in the following column. We can have up to six hidden layers (by adding hidden layers, by clicking on the “+” sign) and we can have up to eight neurons per hidden layer (by clicking on the “+” sign of the corresponding layer):"
},
{
"code": null,
"e": 29054,
"s": 28626,
"text": "Finally, remember that when training the neural network we want to minimize the “Training loss” and then compare that with the test data the “Test loss” is also minimized. The changes of both metrics in each epoch are shown interactively in the upper right part of the screen, in a small graph where, if the loss is reduced, the curve goes downwards. The loss test is painted in black, and the training loss is painted in gray."
},
{
"code": null,
"e": 29090,
"s": 29054,
"text": "Classification with a single neuron"
},
{
"code": null,
"e": 29236,
"s": 29090,
"text": "Now that we know a bit more about this tool, let’s return to the first classification example that separates the data into two groups (clusters)."
},
{
"code": null,
"e": 29518,
"s": 29236,
"text": "I propose that we modify some parameters to practice with the tool before moving forward. For example, we can modify some parameters with a learning rate of 0.03 and a ReLU activation function (the regularization is not going to be used since it is outside the scope of this book)."
},
{
"code": null,
"e": 29841,
"s": 29518,
"text": "We maintain the problem as classification, and I propose that we put the “ratio of training-to-test” to 50% of the data and that we also keep the “noise” parameter to zero to facilitate the visualization of the solution (although I suggest that later you practice with it on your own). We can leave the “batch size” at 10."
},
{
"code": null,
"e": 30019,
"s": 29841,
"text": "And, as before, we will use “X1” and “X2” for the input. I suggest starting with a single hidden layer with a single neuron. We can achieve this by using the “-” or “+” buttons:"
},
{
"code": null,
"e": 30435,
"s": 30019,
"text": "In the upper right, we see that the initial values of the “Test loss” and “Training loss” are high (the reader can get different values since the initial values are generated in a random way). But after pressing the “play” button, it can be seen that both the “Training loss” and the “Test loss” converge at very low ratios and remain the same. Moreover, in this case, both lines, black and gray, perfectly overlap."
},
{
"code": null,
"e": 30476,
"s": 30435,
"text": "Classification with more than one neuron"
},
{
"code": null,
"e": 30555,
"s": 30476,
"text": "Let’s choose another set of starting data like the one in the attached figure:"
},
{
"code": null,
"e": 31045,
"s": 30555,
"text": "We now want to separate the two datasets: the orange ones must be classified in one group and the blue ones in another. But the problem is that in this case they will have a circular shape where the orange points will be in the outer circle and the blue points will be inside. Now, these points cannot be separated with a single line as before. If we train with a hidden layer that has a single neuron as the model of the previous classification, the classification will fail in this case."
},
{
"code": null,
"e": 31311,
"s": 31045,
"text": "I suggest that we test with multiple neurons in the hidden layer. For example, try two neurons: you will see that you have not tuned enough yet. I propose that you then try with three. You will see that, in the end, you can get a much better training and test loss:"
},
{
"code": null,
"e": 31519,
"s": 31311,
"text": "Let’s go for another of the datasets on the left, that where the data is divided into four different square zones. Now, this problem cannot be solved with the previous network, but I propose that you try it:"
},
{
"code": null,
"e": 31911,
"s": 31519,
"text": "As can be seen, we are not able to get a good classification (although in some cases it could happen that with only 3 neurons it works since the initialization is random, but if you do several tests you will see that it is not achieved in general). However, if we have 5 neurons as in the following figure, the reader can see how this neural network gets a good classification for this case:"
},
{
"code": null,
"e": 31946,
"s": 31911,
"text": "Classification with several layers"
},
{
"code": null,
"e": 32276,
"s": 31946,
"text": "Now we will try to classify the dataset with the most complex pattern that we have in this tool. The swirling structure of the orange and blue data points is a challenging problem. If we rely on the previous network, we see that not even having 8 neurons, the maximum that the tool leaves us, we get a good classification result:"
},
{
"code": null,
"e": 32499,
"s": 32276,
"text": "If the reader has tried it, in this case I suppose that you will get a few good values for the test loss. The time has come to put more layers; I assure you that, if you use all the layers the tool allows, you will get it:"
},
{
"code": null,
"e": 32598,
"s": 32499,
"text": "But you will see that, as it is obvious, the process of learning the parameters takes a long time."
},
{
"code": null,
"e": 32835,
"s": 32598,
"text": "Actually, with fewer layers or neurons you can get good results; I challenge you to play a little on your own, also changing for example the activation functions to get a simpler model. You can also consider testing any other parameter."
},
{
"code": null,
"e": 33200,
"s": 32835,
"text": "This tool only considers dense neural networks; later we will see that the convolutional neural networks (and the recurrent neural networks) present more complex dilemmas. But only with these dense networks can we see that one of the most difficult hyperparameters to adjust is to decide how many layers the model has and how many neurons each of these layers has."
},
{
"code": null,
"e": 33428,
"s": 33200,
"text": "Using very few neurons in the hidden layers will result in what is called underfitting, a lack of fit of the model because there are very few neurons in the hidden layers to properly detect the signals in a complicated dataset."
},
{
"code": null,
"e": 33980,
"s": 33428,
"text": "On the other hand, using too many neurons in the hidden layers can cause several problems. First, it can produce overfitting, which occurs when the neural network has so much information processing capacity that the limited amount of information contained in the training set is not enough to train all the neurons in the hidden layers. But on the other hand, a large number of neurons in the hidden layers can increase the time needed to train the network to the point that it is impossible to properly train the neural network in the necessary time."
},
{
"code": null,
"e": 34186,
"s": 33980,
"text": "Obviously, we must reach a compromise between too many and very few neurons in the hidden layers and that is why I have already commented that we are facing a challenge that requires more art than science."
}
] |
Tryit Editor v3.7 | CSS Grid Item
Tryit: A five items grid layout | [
{
"code": null,
"e": 23,
"s": 9,
"text": "CSS Grid Item"
}
] |
Scraping Reddit with PRAW. Recently I was trying to get started on... | by McGuckian Shane | Towards Data Science | Recently I was trying to get started on a project that would use Natural Language Processing to classify which subreddit a given post came from. For instance, this model should be able to predict whether or not a post came from the r/Python subreddit or the r/Rlanguage subreddit. The first step in this process was to collect a number of posts from each subreddit. In the past I’ve used the BeautifulSoup and requests python libraries to get this done. Some of my colleagues had mentioned that API wrappers can be exceedingly useful and simplify a large part of the process. This is how I stumbled upon The Python Reddit API Wrapper (PRAW).
One of the most helpful articles I found was Felippe Rodrigues’ “How to Scrape Reddit with Python.” He does a great job of walking through the basics and getting set up. Definitely check it out if you’re interested in doing something similar. I used this article as a jumping off point for my own project. Below I’ll walk you through how to get setup using PRAW and how to scrape post titles, content, and other metadata. You can find the complete code on my personal Github.
The first step required to start using PRAW is to create an application through reddit. If you go to this link you should find a button near the bottom labeled “create app” or “create another app.” You’ll have to give your script a name and fill out a description. Once that’s done, make sure to select the “script” option and then make sure to put the following into the redirect uri box: http://localhost:8080. This is suggested by the PRAW docs, but is apparently necessary because Reddit requires a redirect uri even if our application doesn’t use it. If successful, you should be provided with two strings of seemingly random characters. You can find the first, your “personal use script,” near the top left corner directly under where it says “personal use script.” This one should be 14 characters long. The next thing you’ll need is the “secret”. While it may sound like something out of a fantasy novel it should be represented as a 27 character string listed just below the “personal use script”. With these two things we can finally begin our journey of scraping posts from Reddit!
Now you need to open your favorite editor or IDE. I used PyCharm for this project but Atom or Sublime would work just fine. The first thing we need to create is a praw.ini file. This will allow us to utilize the PRAW Reddit instance in the future, and it means that we can leave our personal use script and secret out of our primary script if you decide to publish it.
You can refer to the docs regarding praw.ini files, but do make sure that file is in fact called “praw.ini” and that it’s located in the same directory as the one your scraping script will be in. It is possible to define multiple credentials in this file, but today we’ll only be using one so we’ll stick with the [DEFAULT] site.
[DEFAULT]; this is your 14 character personal use scriptclient_id=51IfSlyxtyOUy3; this is your 27 character secretclient_secret=NToU1zG5d0LJq9fo3ryUtOigM5h; this is the name you gave your applicationuser_agent=subreddit scraper; this is username for the reddit account the app was created withusername=fake_username; password for the accountpassword=fake_password
Make sure to fill in each of these fields with your information. The fields above were filled in using randomly generated and fake values. It will not work if you don’t replace these fields with your own information.
Now we can begin writing the actual scraping script. The first step is to import the necessary libraries and instantiate the Reddit instance using the credentials we defined in the praw.ini file.
from os.path import isfileimport prawimport pandas as pdfrom time import sleep# Get credentials from DEFAULT instance in praw.inireddit = praw.Reddit()
I decided to create to a class that would allow me to specify the particular subreddit I was interested in, the method of sorting, number of posts, and whether or not the results should be written to a file. Here’s what the __init__ method looks like:
class SubredditScraper: def __init__(self, sub, sort='new', lim=900, mode='w'): self.sub = sub self.sort = sort self.lim = lim self.mode = mode print( f'SubredditScraper instance created with values ' f'sub = {sub}, sort = {sort}, lim = {lim}, mode = {mode}')
I included a few print statements to get a feel for the script’s progress since it can take a little while to run when working with hundreds of posts. Next, we’ll set the sorting method for our subreddit instance.
def set_sort(self): if self.sort == 'new': return self.sort, reddit.subreddit(self.sub).new(limit=self.lim) elif self.sort == 'top': return self.sort, reddit.subreddit(self.sub).top(limit=self.lim) elif self.sort == 'hot': return self.sort, reddit.subreddit(self.sub).hot(limit=self.lim) else: self.sort = 'hot' print('Sort method was not recognized, defaulting to hot.') return self.sort, reddit.subreddit(self.sub).hot(limit=self.lim)
This method will set the subreddit and sorting parameters of the Reddit instance to the values we specify when instantiating our class. This will return a tuple that we’ll unpack in the next method. If the sorting method is not new, top, or hot it will default to hot.
Finally, we can begin collecting posts and other information from the specified subreddit:
def get_posts(self): """Get unique posts from a specified subreddit.""" sub_dict = { 'selftext': [], 'title': [], 'id': [], 'sorted_by': [], 'num_comments': [], 'score': [], 'ups': [], 'downs': []} csv = f'{self.sub}_posts.csv' # Attempt to specify a sorting method. sort, subreddit = self.set_sort() # Set csv_loaded to True if csv exists since you can't # evaluate the truth value of a DataFrame. df, csv_loaded = (pd.read_csv(csv), 1) if isfile(csv) else ('', 0) print(f'csv = {csv}') print(f'After set_sort(), sort = {sort} and sub = {self.sub}') print(f'csv_loaded = {csv_loaded}') print(f'Collecting information from r/{self.sub}.')
Here we’re creating a placeholder dictionary with each of attributes we’ll be collecting from each of the posts for this subreddit. Then we’re setting up the .csv file for future use, and we’re unpacking the tuple returned by the set_sort method. The last piece of setup is to see if we’ve previously collected posts for this subreddit. If so, we’ll load that .csv file into a data frame and set the boolean variable csv_loaded to 1. If not, df will be an empty string and csv_loaded will be set to 0.
This brings us to the real meat of the scraping. We’ll use a for loop to look at each post and collect the attributes we’re interested in.
for post in subreddit: # Check if post.id is in df and set to True if df is empty. # This way new posts are still added to dictionary when df = '' unique_id = post.id not in tuple(df.id) if csv_loaded else True # Save any unique posts to sub_dict. if unique_id: sub_dict['selftext'].append(post.selftext) sub_dict['title'].append(post.title) sub_dict['id'].append(post.id) sub_dict['sorted_by'].append(sort) sub_dict['num_comments'].append(post.num_comments) sub_dict['score'].append(post.score) sub_dict['ups'].append(post.ups) sub_dict['downs'].append(post.downs) sleep(0.1)
If you plan to use this script multiple times to collect a large number of posts we’ll need to check whether or not each post is unique or if we’ve previously added it to our .csv file. This is where our boolean variable csv_loaded will come in handy. We’ll check if the id attribute of our post is in the “id” column of our data frame (df). If this is the first time we’ve collected posts for this subreddit, unique_id will be set to True for every post. Then we’ll append each of the post’s attributes that we’re interested in to our placeholder dictionary. Finally, and possibly most importantly we’ll sleep for a tenth of a second after every post. This serves as a kind of artificial rate limiter. If we don’t do this we’ll eventually hit the API’s request limit (1000). There are several ways to get around this limit, one of which is to request a refresh token, but this should work fine for the time being.
Next we’ll save our results to a .csv or modify the existing one depending on whether or not we’ve scraped this subreddit before:
new_df = pd.DataFrame(sub_dict)# Add new_df to df if df exists then save it to a csv.if 'DataFrame' in str(type(df)) and self.mode == 'w': pd.concat([df, new_df], axis=0, sort=0).to_csv(csv, index=False) print( f'{len(new_df)} new posts collected and added to {csv}')elif self.mode == 'w': new_df.to_csv(csv, index=False) print(f'{len(new_df)} posts collected and saved to {csv}')else: print( f'{len(new_df)} posts were collected but they were not ' f'added to {csv} because mode was set to "{self.mode}"')
Here we’re using pandas concat method in order to add our new results to the existing .csv we loaded into the df data frame if it exists and mode was set to “w” when our class was instantiated. If there wasn’t an existing .csv file for this subreddit we’ll write our results to .csv, and if the mode wasn’t set to “w” we’ll print out the number of posts we found instead of writing them to a file.
That’s all that we need to round out our SubredditScraper class. The last thing left to do is instantiate our new class.
if __name__ == '__main__': SubredditScraper( 'python', lim=997, mode='w', sort='new').get_posts()
If you’re not familiar with the use of if __name__ == '__main__': I suggest checking out Corey Schafer’s video on this topic here. With that, you should be able to run this script, collect almost 1000 posts from the python subreddit, and save those posts and some of their metadata to a .csv file. I hope this was helpful! Don’t forget you can find the complete code for this project here. | [
{
"code": null,
"e": 814,
"s": 172,
"text": "Recently I was trying to get started on a project that would use Natural Language Processing to classify which subreddit a given post came from. For instance, this model should be able to predict whether or not a post came from the r/Python subreddit or the r/Rlanguage subreddit. The first step in this process was to collect a number of posts from each subreddit. In the past I’ve used the BeautifulSoup and requests python libraries to get this done. Some of my colleagues had mentioned that API wrappers can be exceedingly useful and simplify a large part of the process. This is how I stumbled upon The Python Reddit API Wrapper (PRAW)."
},
{
"code": null,
"e": 1290,
"s": 814,
"text": "One of the most helpful articles I found was Felippe Rodrigues’ “How to Scrape Reddit with Python.” He does a great job of walking through the basics and getting set up. Definitely check it out if you’re interested in doing something similar. I used this article as a jumping off point for my own project. Below I’ll walk you through how to get setup using PRAW and how to scrape post titles, content, and other metadata. You can find the complete code on my personal Github."
},
{
"code": null,
"e": 2383,
"s": 1290,
"text": "The first step required to start using PRAW is to create an application through reddit. If you go to this link you should find a button near the bottom labeled “create app” or “create another app.” You’ll have to give your script a name and fill out a description. Once that’s done, make sure to select the “script” option and then make sure to put the following into the redirect uri box: http://localhost:8080. This is suggested by the PRAW docs, but is apparently necessary because Reddit requires a redirect uri even if our application doesn’t use it. If successful, you should be provided with two strings of seemingly random characters. You can find the first, your “personal use script,” near the top left corner directly under where it says “personal use script.” This one should be 14 characters long. The next thing you’ll need is the “secret”. While it may sound like something out of a fantasy novel it should be represented as a 27 character string listed just below the “personal use script”. With these two things we can finally begin our journey of scraping posts from Reddit!"
},
{
"code": null,
"e": 2752,
"s": 2383,
"text": "Now you need to open your favorite editor or IDE. I used PyCharm for this project but Atom or Sublime would work just fine. The first thing we need to create is a praw.ini file. This will allow us to utilize the PRAW Reddit instance in the future, and it means that we can leave our personal use script and secret out of our primary script if you decide to publish it."
},
{
"code": null,
"e": 3082,
"s": 2752,
"text": "You can refer to the docs regarding praw.ini files, but do make sure that file is in fact called “praw.ini” and that it’s located in the same directory as the one your scraping script will be in. It is possible to define multiple credentials in this file, but today we’ll only be using one so we’ll stick with the [DEFAULT] site."
},
{
"code": null,
"e": 3446,
"s": 3082,
"text": "[DEFAULT]; this is your 14 character personal use scriptclient_id=51IfSlyxtyOUy3; this is your 27 character secretclient_secret=NToU1zG5d0LJq9fo3ryUtOigM5h; this is the name you gave your applicationuser_agent=subreddit scraper; this is username for the reddit account the app was created withusername=fake_username; password for the accountpassword=fake_password"
},
{
"code": null,
"e": 3663,
"s": 3446,
"text": "Make sure to fill in each of these fields with your information. The fields above were filled in using randomly generated and fake values. It will not work if you don’t replace these fields with your own information."
},
{
"code": null,
"e": 3859,
"s": 3663,
"text": "Now we can begin writing the actual scraping script. The first step is to import the necessary libraries and instantiate the Reddit instance using the credentials we defined in the praw.ini file."
},
{
"code": null,
"e": 4011,
"s": 3859,
"text": "from os.path import isfileimport prawimport pandas as pdfrom time import sleep# Get credentials from DEFAULT instance in praw.inireddit = praw.Reddit()"
},
{
"code": null,
"e": 4263,
"s": 4011,
"text": "I decided to create to a class that would allow me to specify the particular subreddit I was interested in, the method of sorting, number of posts, and whether or not the results should be written to a file. Here’s what the __init__ method looks like:"
},
{
"code": null,
"e": 4583,
"s": 4263,
"text": "class SubredditScraper: def __init__(self, sub, sort='new', lim=900, mode='w'): self.sub = sub self.sort = sort self.lim = lim self.mode = mode print( f'SubredditScraper instance created with values ' f'sub = {sub}, sort = {sort}, lim = {lim}, mode = {mode}')"
},
{
"code": null,
"e": 4797,
"s": 4583,
"text": "I included a few print statements to get a feel for the script’s progress since it can take a little while to run when working with hundreds of posts. Next, we’ll set the sorting method for our subreddit instance."
},
{
"code": null,
"e": 5288,
"s": 4797,
"text": "def set_sort(self): if self.sort == 'new': return self.sort, reddit.subreddit(self.sub).new(limit=self.lim) elif self.sort == 'top': return self.sort, reddit.subreddit(self.sub).top(limit=self.lim) elif self.sort == 'hot': return self.sort, reddit.subreddit(self.sub).hot(limit=self.lim) else: self.sort = 'hot' print('Sort method was not recognized, defaulting to hot.') return self.sort, reddit.subreddit(self.sub).hot(limit=self.lim)"
},
{
"code": null,
"e": 5557,
"s": 5288,
"text": "This method will set the subreddit and sorting parameters of the Reddit instance to the values we specify when instantiating our class. This will return a tuple that we’ll unpack in the next method. If the sorting method is not new, top, or hot it will default to hot."
},
{
"code": null,
"e": 5648,
"s": 5557,
"text": "Finally, we can begin collecting posts and other information from the specified subreddit:"
},
{
"code": null,
"e": 6338,
"s": 5648,
"text": "def get_posts(self): \"\"\"Get unique posts from a specified subreddit.\"\"\" sub_dict = { 'selftext': [], 'title': [], 'id': [], 'sorted_by': [], 'num_comments': [], 'score': [], 'ups': [], 'downs': []} csv = f'{self.sub}_posts.csv' # Attempt to specify a sorting method. sort, subreddit = self.set_sort() # Set csv_loaded to True if csv exists since you can't # evaluate the truth value of a DataFrame. df, csv_loaded = (pd.read_csv(csv), 1) if isfile(csv) else ('', 0) print(f'csv = {csv}') print(f'After set_sort(), sort = {sort} and sub = {self.sub}') print(f'csv_loaded = {csv_loaded}') print(f'Collecting information from r/{self.sub}.')"
},
{
"code": null,
"e": 6840,
"s": 6338,
"text": "Here we’re creating a placeholder dictionary with each of attributes we’ll be collecting from each of the posts for this subreddit. Then we’re setting up the .csv file for future use, and we’re unpacking the tuple returned by the set_sort method. The last piece of setup is to see if we’ve previously collected posts for this subreddit. If so, we’ll load that .csv file into a data frame and set the boolean variable csv_loaded to 1. If not, df will be an empty string and csv_loaded will be set to 0."
},
{
"code": null,
"e": 6979,
"s": 6840,
"text": "This brings us to the real meat of the scraping. We’ll use a for loop to look at each post and collect the attributes we’re interested in."
},
{
"code": null,
"e": 7630,
"s": 6979,
"text": "for post in subreddit: # Check if post.id is in df and set to True if df is empty. # This way new posts are still added to dictionary when df = '' unique_id = post.id not in tuple(df.id) if csv_loaded else True # Save any unique posts to sub_dict. if unique_id: sub_dict['selftext'].append(post.selftext) sub_dict['title'].append(post.title) sub_dict['id'].append(post.id) sub_dict['sorted_by'].append(sort) sub_dict['num_comments'].append(post.num_comments) sub_dict['score'].append(post.score) sub_dict['ups'].append(post.ups) sub_dict['downs'].append(post.downs) sleep(0.1)"
},
{
"code": null,
"e": 8545,
"s": 7630,
"text": "If you plan to use this script multiple times to collect a large number of posts we’ll need to check whether or not each post is unique or if we’ve previously added it to our .csv file. This is where our boolean variable csv_loaded will come in handy. We’ll check if the id attribute of our post is in the “id” column of our data frame (df). If this is the first time we’ve collected posts for this subreddit, unique_id will be set to True for every post. Then we’ll append each of the post’s attributes that we’re interested in to our placeholder dictionary. Finally, and possibly most importantly we’ll sleep for a tenth of a second after every post. This serves as a kind of artificial rate limiter. If we don’t do this we’ll eventually hit the API’s request limit (1000). There are several ways to get around this limit, one of which is to request a refresh token, but this should work fine for the time being."
},
{
"code": null,
"e": 8675,
"s": 8545,
"text": "Next we’ll save our results to a .csv or modify the existing one depending on whether or not we’ve scraped this subreddit before:"
},
{
"code": null,
"e": 9218,
"s": 8675,
"text": "new_df = pd.DataFrame(sub_dict)# Add new_df to df if df exists then save it to a csv.if 'DataFrame' in str(type(df)) and self.mode == 'w': pd.concat([df, new_df], axis=0, sort=0).to_csv(csv, index=False) print( f'{len(new_df)} new posts collected and added to {csv}')elif self.mode == 'w': new_df.to_csv(csv, index=False) print(f'{len(new_df)} posts collected and saved to {csv}')else: print( f'{len(new_df)} posts were collected but they were not ' f'added to {csv} because mode was set to \"{self.mode}\"')"
},
{
"code": null,
"e": 9616,
"s": 9218,
"text": "Here we’re using pandas concat method in order to add our new results to the existing .csv we loaded into the df data frame if it exists and mode was set to “w” when our class was instantiated. If there wasn’t an existing .csv file for this subreddit we’ll write our results to .csv, and if the mode wasn’t set to “w” we’ll print out the number of posts we found instead of writing them to a file."
},
{
"code": null,
"e": 9737,
"s": 9616,
"text": "That’s all that we need to round out our SubredditScraper class. The last thing left to do is instantiate our new class."
},
{
"code": null,
"e": 9869,
"s": 9737,
"text": "if __name__ == '__main__': SubredditScraper( 'python', lim=997, mode='w', sort='new').get_posts()"
}
] |
C Program to check the type of character entered | Write a program to find out that a given character is upper case, lower case, number or special character.
If an entered character is capital letter then, it displays the upper case.
Example: Input =H
Output: upper case letter
If an entered character is small letter then, it displays the lower case letter.
Example: Input= g
Output: lower case letter
If an entered character is number then, it displays the digit.
Example: Input=3
Output: digit
If an entered character is a special character then, it displays the special character.
Example: Input= &
Output: special character
Refer an algorithm given below to find out that a given character is upper case, lower case, number or special character.
Step 1 − Read input character from console at runtime.
Step 2 − Compute ASCII value of the character.
Step 3 − If the ASCII value of the character is in the range of 65 and 90, Then, print "Upper Case letter".
Step 4 − If the ASCII value of the character is in the range of 97 and 122, Then, print "Lower Case letter".
Step 5 − If the ASCII value of the character is in the range of 48 and 57, Then, print "Number".
Step 6 − Else, print "Symbol".
Following is the C program to find out that a given character is upper case, lower case, number or special character −
Live Demo
#include<stdio.h>
int main(){
char ch;
printf("enter a character:");
scanf("%c",&ch);
if(ch >= 65 && ch <= 90)
printf("Upper Case Letter");
else if(ch >= 97 && ch <= 122)
printf("Lower Case letter");
else if(ch >= 48 && ch <= 57)
printf("Number");
else
printf("Symbol");
return 0;
}
When the above program is executed, it produces the following output −
Run 1:
enter a single character:45
Number
Run 2:
enter a character:#
Symbol
Run 3:
enter a character:M
Upper Case Letter | [
{
"code": null,
"e": 1169,
"s": 1062,
"text": "Write a program to find out that a given character is upper case, lower case, number or special character."
},
{
"code": null,
"e": 1245,
"s": 1169,
"text": "If an entered character is capital letter then, it displays the upper case."
},
{
"code": null,
"e": 1289,
"s": 1245,
"text": "Example: Input =H\nOutput: upper case letter"
},
{
"code": null,
"e": 1370,
"s": 1289,
"text": "If an entered character is small letter then, it displays the lower case letter."
},
{
"code": null,
"e": 1414,
"s": 1370,
"text": "Example: Input= g\nOutput: lower case letter"
},
{
"code": null,
"e": 1477,
"s": 1414,
"text": "If an entered character is number then, it displays the digit."
},
{
"code": null,
"e": 1508,
"s": 1477,
"text": "Example: Input=3\nOutput: digit"
},
{
"code": null,
"e": 1596,
"s": 1508,
"text": "If an entered character is a special character then, it displays the special character."
},
{
"code": null,
"e": 1640,
"s": 1596,
"text": "Example: Input= &\nOutput: special character"
},
{
"code": null,
"e": 1762,
"s": 1640,
"text": "Refer an algorithm given below to find out that a given character is upper case, lower case, number or special character."
},
{
"code": null,
"e": 1817,
"s": 1762,
"text": "Step 1 − Read input character from console at runtime."
},
{
"code": null,
"e": 1864,
"s": 1817,
"text": "Step 2 − Compute ASCII value of the character."
},
{
"code": null,
"e": 1972,
"s": 1864,
"text": "Step 3 − If the ASCII value of the character is in the range of 65 and 90, Then, print \"Upper Case letter\"."
},
{
"code": null,
"e": 2081,
"s": 1972,
"text": "Step 4 − If the ASCII value of the character is in the range of 97 and 122, Then, print \"Lower Case letter\"."
},
{
"code": null,
"e": 2178,
"s": 2081,
"text": "Step 5 − If the ASCII value of the character is in the range of 48 and 57, Then, print \"Number\"."
},
{
"code": null,
"e": 2209,
"s": 2178,
"text": "Step 6 − Else, print \"Symbol\"."
},
{
"code": null,
"e": 2328,
"s": 2209,
"text": "Following is the C program to find out that a given character is upper case, lower case, number or special character −"
},
{
"code": null,
"e": 2339,
"s": 2328,
"text": " Live Demo"
},
{
"code": null,
"e": 2670,
"s": 2339,
"text": "#include<stdio.h>\nint main(){\n char ch;\n printf(\"enter a character:\");\n scanf(\"%c\",&ch);\n if(ch >= 65 && ch <= 90)\n printf(\"Upper Case Letter\");\n else if(ch >= 97 && ch <= 122)\n printf(\"Lower Case letter\");\n else if(ch >= 48 && ch <= 57)\n printf(\"Number\");\n else\n printf(\"Symbol\");\n return 0;\n}"
},
{
"code": null,
"e": 2741,
"s": 2670,
"text": "When the above program is executed, it produces the following output −"
},
{
"code": null,
"e": 2862,
"s": 2741,
"text": "Run 1:\nenter a single character:45\nNumber\nRun 2:\nenter a character:#\nSymbol\nRun 3:\nenter a character:M\nUpper Case Letter"
}
] |
How to get days, months and years between two Java LocalDate? | Set the two Java dates:
LocalDate date1 = LocalDate.of(2019, 3, 25);
LocalDate date2 = LocalDate.of(2019, 4, 29);
Now, get the difference between two dates with Period class between() method:
Period p = Period.between(date1, date2);
Now, get the years, month and days:
p.getYears()
p.getMonths()
p.getDays()
import java.time.LocalDate;
import java.time.Period;
public class Demo {
public static void main(String[] args) {
LocalDate date1 = LocalDate.of(2019, 3, 25);
LocalDate date2 = LocalDate.of(2019, 4, 29);
System.out.println("Date 1 = "+date1);
System.out.println("Date 2 = "+date2);
Period p = Period.between(date1, date2);
System.out.println("Period = "+p);
System.out.println("Years (Difference) = "+p.getYears());
System.out.println("Month (Difference) = "+p.getMonths());
System.out.println("Days (Difference) = "+p.getDays());
}
}
Date 1 = 2019-03-25
Date 2 = 2019-04-29
Period = P1M4D
Years (Difference) = 0
Month (Difference) = 1
Days (Difference) = 4 | [
{
"code": null,
"e": 1086,
"s": 1062,
"text": "Set the two Java dates:"
},
{
"code": null,
"e": 1176,
"s": 1086,
"text": "LocalDate date1 = LocalDate.of(2019, 3, 25);\nLocalDate date2 = LocalDate.of(2019, 4, 29);"
},
{
"code": null,
"e": 1254,
"s": 1176,
"text": "Now, get the difference between two dates with Period class between() method:"
},
{
"code": null,
"e": 1295,
"s": 1254,
"text": "Period p = Period.between(date1, date2);"
},
{
"code": null,
"e": 1331,
"s": 1295,
"text": "Now, get the years, month and days:"
},
{
"code": null,
"e": 1370,
"s": 1331,
"text": "p.getYears()\np.getMonths()\np.getDays()"
},
{
"code": null,
"e": 1965,
"s": 1370,
"text": "import java.time.LocalDate;\nimport java.time.Period;\npublic class Demo {\n public static void main(String[] args) {\n LocalDate date1 = LocalDate.of(2019, 3, 25);\n LocalDate date2 = LocalDate.of(2019, 4, 29);\n System.out.println(\"Date 1 = \"+date1);\n System.out.println(\"Date 2 = \"+date2);\n Period p = Period.between(date1, date2);\n System.out.println(\"Period = \"+p);\n System.out.println(\"Years (Difference) = \"+p.getYears());\n System.out.println(\"Month (Difference) = \"+p.getMonths());\n System.out.println(\"Days (Difference) = \"+p.getDays());\n }\n}"
},
{
"code": null,
"e": 2088,
"s": 1965,
"text": "Date 1 = 2019-03-25\nDate 2 = 2019-04-29\nPeriod = P1M4D\nYears (Difference) = 0\nMonth (Difference) = 1\nDays (Difference) = 4"
}
] |
Deleting records in MySQL using Nodejs | After insertion, we need to delete records as well. The records should can be deleted based upon an identifier from the database table. You can delete records from table using "DELETE FROM" statement.
We can delete the records from MySql DB in two ways −
Static Deletion - In this type of deletion, we give a prefixed filter value to delete
Static Deletion - In this type of deletion, we give a prefixed filter value to delete
Dynamic Deletion – In this type of deletion, we ask for an input before deletion and then delete upon its basis.
Dynamic Deletion – In this type of deletion, we ask for an input before deletion and then delete upon its basis.
Before proceeding, please check the following steps are already executed −
mkdir mysql-test
mkdir mysql-test
cd mysql-test
cd mysql-test
npm init -y
npm init -y
npm install mysql
npm install mysql
The above steps are for installing the Node - mysql dependecy in the project folder.
Following are the examples on how to delete records from MySql using Nodejs.
For deleting records from the MySQL table, create an app.js file.
For deleting records from the MySQL table, create an app.js file.
Now copy-paste the below snippet in the file
Now copy-paste the below snippet in the file
Run the code using the following command
Run the code using the following command
>> node app.js
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
//Delete the records with address="Delhi"
var sql = "DELETE FROM student WHERE address = 'Delhi'; "
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Record deleted = ", results.affectedRows);
console.log(result);
});
});
Record deleted = 1
OkPacket {
fieldCount: 0,
affectedRows: 1, // No of Records Deleted
insertId: 0,
serverStatus: 34,
warningCount: 0,
message: '',
protocol41: true,
changedRows: 0
}
The following example will take address field as the input and only delete the records which match the filter.
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
// Delete the desired record from table
let sql = `DELETE FROM student WHERE address = ?`;
// delete a row with address=Delhi
con.query(sql, 'Dehi', (err, result, fields) => {
if (err) throw err;
console.log("Record deleted = ", results.affectedRows);
console.log(result);
});
});
OkPacket {
fieldCount: 0,
affectedRows: 3, // 3 Rows deleted for address=Delhi
insertId: 0,
serverStatus: 34,
warningCount: 0,
message: '',
protocol41: true,
changedRows: 0
} | [
{
"code": null,
"e": 1263,
"s": 1062,
"text": "After insertion, we need to delete records as well. The records should can be deleted based upon an identifier from the database table. You can delete records from table using \"DELETE FROM\" statement."
},
{
"code": null,
"e": 1317,
"s": 1263,
"text": "We can delete the records from MySql DB in two ways −"
},
{
"code": null,
"e": 1403,
"s": 1317,
"text": "Static Deletion - In this type of deletion, we give a prefixed filter value to delete"
},
{
"code": null,
"e": 1489,
"s": 1403,
"text": "Static Deletion - In this type of deletion, we give a prefixed filter value to delete"
},
{
"code": null,
"e": 1602,
"s": 1489,
"text": "Dynamic Deletion – In this type of deletion, we ask for an input before deletion and then delete upon its basis."
},
{
"code": null,
"e": 1715,
"s": 1602,
"text": "Dynamic Deletion – In this type of deletion, we ask for an input before deletion and then delete upon its basis."
},
{
"code": null,
"e": 1790,
"s": 1715,
"text": "Before proceeding, please check the following steps are already executed −"
},
{
"code": null,
"e": 1807,
"s": 1790,
"text": "mkdir mysql-test"
},
{
"code": null,
"e": 1824,
"s": 1807,
"text": "mkdir mysql-test"
},
{
"code": null,
"e": 1838,
"s": 1824,
"text": "cd mysql-test"
},
{
"code": null,
"e": 1852,
"s": 1838,
"text": "cd mysql-test"
},
{
"code": null,
"e": 1864,
"s": 1852,
"text": "npm init -y"
},
{
"code": null,
"e": 1876,
"s": 1864,
"text": "npm init -y"
},
{
"code": null,
"e": 1894,
"s": 1876,
"text": "npm install mysql"
},
{
"code": null,
"e": 1912,
"s": 1894,
"text": "npm install mysql"
},
{
"code": null,
"e": 1997,
"s": 1912,
"text": "The above steps are for installing the Node - mysql dependecy in the project folder."
},
{
"code": null,
"e": 2074,
"s": 1997,
"text": "Following are the examples on how to delete records from MySql using Nodejs."
},
{
"code": null,
"e": 2140,
"s": 2074,
"text": "For deleting records from the MySQL table, create an app.js file."
},
{
"code": null,
"e": 2206,
"s": 2140,
"text": "For deleting records from the MySQL table, create an app.js file."
},
{
"code": null,
"e": 2251,
"s": 2206,
"text": "Now copy-paste the below snippet in the file"
},
{
"code": null,
"e": 2296,
"s": 2251,
"text": "Now copy-paste the below snippet in the file"
},
{
"code": null,
"e": 2337,
"s": 2296,
"text": "Run the code using the following command"
},
{
"code": null,
"e": 2378,
"s": 2337,
"text": "Run the code using the following command"
},
{
"code": null,
"e": 2396,
"s": 2378,
"text": " >> node app.js"
},
{
"code": null,
"e": 2889,
"s": 2396,
"text": "var mysql = require('mysql');\nvar con = mysql.createConnection({\n host: \"localhost\",\n user: \"yourusername\",\n password: \"yourpassword\",\n database: \"mydb\"\n});\n\ncon.connect(function(err) {\n if (err) throw err;\n\n //Delete the records with address=\"Delhi\"\n var sql = \"DELETE FROM student WHERE address = 'Delhi'; \"\n con.query(sql, function (err, result) {\n if (err) throw err;\n console.log(\"Record deleted = \", results.affectedRows);\n console.log(result);\n });\n});"
},
{
"code": null,
"e": 3096,
"s": 2889,
"text": "Record deleted = 1\nOkPacket {\n fieldCount: 0,\n affectedRows: 1, // No of Records Deleted\n insertId: 0,\n serverStatus: 34,\n warningCount: 0,\n message: '',\n protocol41: true,\n changedRows: 0\n}"
},
{
"code": null,
"e": 3207,
"s": 3096,
"text": "The following example will take address field as the input and only delete the records which match the filter."
},
{
"code": null,
"e": 3730,
"s": 3207,
"text": "var mysql = require('mysql');\nvar con = mysql.createConnection({\n host: \"localhost\",\n user: \"yourusername\",\n password: \"yourpassword\",\n database: \"mydb\"\n});\n\ncon.connect(function(err) {\n if (err) throw err;\n\n// Delete the desired record from table\nlet sql = `DELETE FROM student WHERE address = ?`;\n// delete a row with address=Delhi\n con.query(sql, 'Dehi', (err, result, fields) => {\n if (err) throw err;\n console.log(\"Record deleted = \", results.affectedRows);\n console.log(result);\n });\n});"
},
{
"code": null,
"e": 3929,
"s": 3730,
"text": "OkPacket {\n fieldCount: 0,\n affectedRows: 3, // 3 Rows deleted for address=Delhi\n insertId: 0,\n serverStatus: 34,\n warningCount: 0,\n message: '',\n protocol41: true,\n changedRows: 0\n}"
}
] |
XSLT <key> | <xsl:key> tag element specifies a named name-value pair assigned to a specific element in an XML document. This key is used with the key() function in XPath expressions to access the assigned elements in an XML document.
Following is the syntax declaration of <xsl:key> element.
<xsl:key
name = QName
match = Pattern
use = Expression >
</xsl:key>
Name
Name of the key to be used.
Match
Patterns used to identify a node that holds this key.
Use
XPath expression to identify the value of the nodes of xml document.
This example creates a table of <student> element with its attribute rollno and its child <firstname>, <lastname>, <nickname>, and <marks> by iterating over each student. It checks key as firstname to be one of the student's name and then prints the student details.
students.xml
<?xml version = "1.0"?>
<?xml-stylesheet type = "text/xsl" href = "students.xsl"?>
<class>
<student rollno = "393">
<firstname>Dinkar</firstname>
<lastname>Kad</lastname>
<nickname>Dinkar</nickname>
<marks>85</marks>
</student>
<student rollno = "493">
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>Vinni</nickname>
<marks>95</marks>
</student>
<student rollno = "593">
<firstname>Jasvir</firstname>
<lastname>Singh</lastname>
<nickname>Jazz</nickname>
<marks>90</marks>
</student>
</class>
students.xsl
<xsl:stylesheet version = "1.0"
xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">
<xsl:key name = "firstname-search" match = "student" use = "firstname"/>
<xsl:template match = "/">
<html>
<body>
<h2>Students</h2>
<table border = "1">
<tr bgcolor = "#9acd32">
<th>Roll No</th>
<th>First Name</th>
<th>Last Name</th>
<th>Nick Name</th>
<th>Marks</th>
</tr>
<xsl:for-each select = "key('firstname-search', 'Dinkar')">
<tr>
<td><xsl:value-of select = "@rollno"/></td>
<td><xsl:value-of select = "firstname"/></td>
<td><xsl:value-of select = "lastname"/></td>
<td><xsl:value-of select = "nickname"/></td>
<td><xsl:value-of select = "marks"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1980,
"s": 1759,
"text": "<xsl:key> tag element specifies a named name-value pair assigned to a specific element in an XML document. This key is used with the key() function in XPath expressions to access the assigned elements in an XML document."
},
{
"code": null,
"e": 2038,
"s": 1980,
"text": "Following is the syntax declaration of <xsl:key> element."
},
{
"code": null,
"e": 2120,
"s": 2038,
"text": "<xsl:key \n name = QName \n match = Pattern \n use = Expression > \n</xsl:key>\n"
},
{
"code": null,
"e": 2125,
"s": 2120,
"text": "Name"
},
{
"code": null,
"e": 2153,
"s": 2125,
"text": "Name of the key to be used."
},
{
"code": null,
"e": 2159,
"s": 2153,
"text": "Match"
},
{
"code": null,
"e": 2213,
"s": 2159,
"text": "Patterns used to identify a node that holds this key."
},
{
"code": null,
"e": 2217,
"s": 2213,
"text": "Use"
},
{
"code": null,
"e": 2286,
"s": 2217,
"text": "XPath expression to identify the value of the nodes of xml document."
},
{
"code": null,
"e": 2553,
"s": 2286,
"text": "This example creates a table of <student> element with its attribute rollno and its child <firstname>, <lastname>, <nickname>, and <marks> by iterating over each student. It checks key as firstname to be one of the student's name and then prints the student details."
},
{
"code": null,
"e": 2566,
"s": 2553,
"text": "students.xml"
},
{
"code": null,
"e": 3189,
"s": 2566,
"text": "<?xml version = \"1.0\"?> \n<?xml-stylesheet type = \"text/xsl\" href = \"students.xsl\"?> \n<class> \n <student rollno = \"393\"> \n <firstname>Dinkar</firstname> \n <lastname>Kad</lastname> \n <nickname>Dinkar</nickname> \n <marks>85</marks> \n </student> \n <student rollno = \"493\"> \n <firstname>Vaneet</firstname> \n <lastname>Gupta</lastname> \n <nickname>Vinni</nickname> \n <marks>95</marks> \n </student> \n <student rollno = \"593\"> \n <firstname>Jasvir</firstname> \n <lastname>Singh</lastname> \n <nickname>Jazz</nickname> \n <marks>90</marks> \n </student> \n</class>"
},
{
"code": null,
"e": 3202,
"s": 3189,
"text": "students.xsl"
},
{
"code": null,
"e": 4342,
"s": 3202,
"text": "<xsl:stylesheet version = \"1.0\" \n xmlns:xsl = \"http://www.w3.org/1999/XSL/Transform\">\n <xsl:key name = \"firstname-search\" match = \"student\" use = \"firstname\"/> \n <xsl:template match = \"/\"> \n <html> \n <body> \n <h2>Students</h2> \n <table border = \"1\"> \n <tr bgcolor = \"#9acd32\"> \n <th>Roll No</th> \n <th>First Name</th> \n <th>Last Name</th> \n <th>Nick Name</th> \n <th>Marks</th> \n </tr> \n\t\t\t\t\t\n <xsl:for-each select = \"key('firstname-search', 'Dinkar')\"> \n\t\t\t\t\n <tr> \n <td><xsl:value-of select = \"@rollno\"/></td> \n <td><xsl:value-of select = \"firstname\"/></td> \n <td><xsl:value-of select = \"lastname\"/></td> \n <td><xsl:value-of select = \"nickname\"/></td> \n <td><xsl:value-of select = \"marks\"/></td> \n </tr> \n\t\t\t\t\t\n </xsl:for-each> \n </table> \n </body> \n </html> \n </xsl:template> \n</xsl:stylesheet>"
},
{
"code": null,
"e": 4349,
"s": 4342,
"text": " Print"
},
{
"code": null,
"e": 4360,
"s": 4349,
"text": " Add Notes"
}
] |
What is the Java equivalent to MySQL's smallint? | The short is equivalent to MySQL’s small int. The Java short takes 2 bytes that has the range -32768 to 32767 while MySQL smallint also take 2 bytes with same range.
Here is the demo code of short in Java −
public class SmallIntAsShortDemo {
public static void main(String[] args) {
short value = 32767;
System.out.println(value);
value = -32768;
System.out.println(value);
// value = 32768;
// System.out.println(value);
}
}
The snapshot is as follows −
This will produce the following output −
32767
-32768
Here is the snapshot of the output we ran in EclipseIDE −
The MySQL smallint takes 2 bytes with same range. | [
{
"code": null,
"e": 1228,
"s": 1062,
"text": "The short is equivalent to MySQL’s small int. The Java short takes 2 bytes that has the range -32768 to 32767 while MySQL smallint also take 2 bytes with same range."
},
{
"code": null,
"e": 1269,
"s": 1228,
"text": "Here is the demo code of short in Java −"
},
{
"code": null,
"e": 1530,
"s": 1269,
"text": "public class SmallIntAsShortDemo {\n public static void main(String[] args) {\n short value = 32767;\n System.out.println(value);\n value = -32768;\n System.out.println(value);\n // value = 32768;\n // System.out.println(value);\n }\n}"
},
{
"code": null,
"e": 1559,
"s": 1530,
"text": "The snapshot is as follows −"
},
{
"code": null,
"e": 1600,
"s": 1559,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1613,
"s": 1600,
"text": "32767\n-32768"
},
{
"code": null,
"e": 1671,
"s": 1613,
"text": "Here is the snapshot of the output we ran in EclipseIDE −"
},
{
"code": null,
"e": 1721,
"s": 1671,
"text": "The MySQL smallint takes 2 bytes with same range."
}
] |
How can I convert a Python Named tuple to a dictionary? | Namedtuple class is defined in the collections module. It returns a new tuple subclass. The new subclass is used to create tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable. The constructor takes type name and field list as arguments. For example, a student namedtuple is declared as follows −
>>> from collections import namedtuple
>>> student=namedtuple("student","name, age, marks")
The object of this namedtuple class is declared as −
>>> s1=student("Raam",21,45)
This class has _asdict() method which returns orderdict() object
>>> d=s1._asdict()
>>> d
OrderedDict([('name', 'Raam'), ('age', 21), ('marks', 45)])
To obtain regular dictionary object use dict() function
>>> dct=dict(d)
>>> dct
{'name': 'Raam', 'age': 21, 'marks': 45}
Good | [
{
"code": null,
"e": 1413,
"s": 1062,
"text": "Namedtuple class is defined in the collections module. It returns a new tuple subclass. The new subclass is used to create tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable. The constructor takes type name and field list as arguments. For example, a student namedtuple is declared as follows −"
},
{
"code": null,
"e": 1505,
"s": 1413,
"text": ">>> from collections import namedtuple\n>>> student=namedtuple(\"student\",\"name, age, marks\")"
},
{
"code": null,
"e": 1558,
"s": 1505,
"text": "The object of this namedtuple class is declared as −"
},
{
"code": null,
"e": 1587,
"s": 1558,
"text": ">>> s1=student(\"Raam\",21,45)"
},
{
"code": null,
"e": 1652,
"s": 1587,
"text": "This class has _asdict() method which returns orderdict() object"
},
{
"code": null,
"e": 1737,
"s": 1652,
"text": ">>> d=s1._asdict()\n>>> d\nOrderedDict([('name', 'Raam'), ('age', 21), ('marks', 45)])"
},
{
"code": null,
"e": 1793,
"s": 1737,
"text": "To obtain regular dictionary object use dict() function"
},
{
"code": null,
"e": 1858,
"s": 1793,
"text": ">>> dct=dict(d)\n>>> dct\n{'name': 'Raam', 'age': 21, 'marks': 45}"
},
{
"code": null,
"e": 1863,
"s": 1858,
"text": "Good"
}
] |
Apache Storm in Twitter | Here in this chapter, we will discuss a real-time application of Apache Storm. We will see how Storm is used in Twitter.
Twitter is an online social networking service that provides a platform to send and receive user tweets. Registered users can read and post tweets, but unregistered users can only read tweets. Hashtag is used to categorize tweets by keyword by appending # before the relevant keyword. Now let us take a real-time scenario of finding the most used hashtag per topic.
The purpose of spout is to get the tweets submitted by people as soon as possible. Twitter provides “Twitter Streaming API”, a web service based tool to retrieve the tweets submitted by people in real time. Twitter Streaming API can be accessed in any programming language.
twitter4j is an open source, unofficial Java library, which provides a Java based module to easily access the Twitter Streaming API. twitter4j provides a listener-based framework to access the tweets. To access the Twitter Streaming API, we need to sign in for Twitter developer account and should get the following OAuth authentication details.
Customerkey
CustomerSecret
AccessToken
AccessTookenSecret
Storm provides a twitter spout, TwitterSampleSpout, in its starter kit. We will be using it to retrieve the tweets. The spout needs OAuth authentication details and at least a keyword. The spout will emit real-time tweets based on keywords. The complete program code is given below.
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import twitter4j.FilterQuery;
import twitter4j.StallWarning;
import twitter4j.Status;
import twitter4j.StatusDeletionNotice;
import twitter4j.StatusListener;
import twitter4j.TwitterStream;
import twitter4j.TwitterStreamFactory;
import twitter4j.auth.AccessToken;
import twitter4j.conf.ConfigurationBuilder;
import backtype.storm.Config;
import backtype.storm.spout.SpoutOutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichSpout;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Values;
import backtype.storm.utils.Utils;
@SuppressWarnings("serial")
public class TwitterSampleSpout extends BaseRichSpout {
SpoutOutputCollector _collector;
LinkedBlockingQueue<Status> queue = null;
TwitterStream _twitterStream;
String consumerKey;
String consumerSecret;
String accessToken;
String accessTokenSecret;
String[] keyWords;
public TwitterSampleSpout(String consumerKey, String consumerSecret,
String accessToken, String accessTokenSecret, String[] keyWords) {
this.consumerKey = consumerKey;
this.consumerSecret = consumerSecret;
this.accessToken = accessToken;
this.accessTokenSecret = accessTokenSecret;
this.keyWords = keyWords;
}
public TwitterSampleSpout() {
// TODO Auto-generated constructor stub
}
@Override
public void open(Map conf, TopologyContext context,
SpoutOutputCollector collector) {
queue = new LinkedBlockingQueue<Status>(1000);
_collector = collector;
StatusListener listener = new StatusListener() {
@Override
public void onStatus(Status status) {
queue.offer(status);
}
@Override
public void onDeletionNotice(StatusDeletionNotice sdn) {}
@Override
public void onTrackLimitationNotice(int i) {}
@Override
public void onScrubGeo(long l, long l1) {}
@Override
public void onException(Exception ex) {}
@Override
public void onStallWarning(StallWarning arg0) {
// TODO Auto-generated method stub
}
};
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(consumerKey)
.setOAuthConsumerSecret(consumerSecret)
.setOAuthAccessToken(accessToken)
.setOAuthAccessTokenSecret(accessTokenSecret);
_twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
_twitterStream.addListener(listener);
if (keyWords.length == 0) {
_twitterStream.sample();
}else {
FilterQuery query = new FilterQuery().track(keyWords);
_twitterStream.filter(query);
}
}
@Override
public void nextTuple() {
Status ret = queue.poll();
if (ret == null) {
Utils.sleep(50);
} else {
_collector.emit(new Values(ret));
}
}
@Override
public void close() {
_twitterStream.shutdown();
}
@Override
public Map<String, Object> getComponentConfiguration() {
Config ret = new Config();
ret.setMaxTaskParallelism(1);
return ret;
}
@Override
public void ack(Object id) {}
@Override
public void fail(Object id) {}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("tweet"));
}
}
The tweet emitted by spout will be forwarded to HashtagReaderBolt, which will process the tweet and emit all the available hashtags. HashtagReaderBolt uses getHashTagEntities method provided by twitter4j. getHashTagEntities reads the tweet and returns the list of hashtag. The complete program code is as follows −
import java.util.HashMap;
import java.util.Map;
import twitter4j.*;
import twitter4j.conf.*;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Values;
import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.IRichBolt;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.tuple.Tuple;
public class HashtagReaderBolt implements IRichBolt {
private OutputCollector collector;
@Override
public void prepare(Map conf, TopologyContext context, OutputCollector collector) {
this.collector = collector;
}
@Override
public void execute(Tuple tuple) {
Status tweet = (Status) tuple.getValueByField("tweet");
for(HashtagEntity hashtage : tweet.getHashtagEntities()) {
System.out.println("Hashtag: " + hashtage.getText());
this.collector.emit(new Values(hashtage.getText()));
}
}
@Override
public void cleanup() {}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("hashtag"));
}
@Override
public Map<String, Object> getComponentConfiguration() {
return null;
}
}
The emitted hashtag will be forwarded to HashtagCounterBolt. This bolt will process all the hashtags and save each and every hashtag and its count in memory using Java Map object. The complete program code is given below.
import java.util.HashMap;
import java.util.Map;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Values;
import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.IRichBolt;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.tuple.Tuple;
public class HashtagCounterBolt implements IRichBolt {
Map<String, Integer> counterMap;
private OutputCollector collector;
@Override
public void prepare(Map conf, TopologyContext context, OutputCollector collector) {
this.counterMap = new HashMap<String, Integer>();
this.collector = collector;
}
@Override
public void execute(Tuple tuple) {
String key = tuple.getString(0);
if(!counterMap.containsKey(key)){
counterMap.put(key, 1);
}else{
Integer c = counterMap.get(key) + 1;
counterMap.put(key, c);
}
collector.ack(tuple);
}
@Override
public void cleanup() {
for(Map.Entry<String, Integer> entry:counterMap.entrySet()){
System.out.println("Result: " + entry.getKey()+" : " + entry.getValue());
}
}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("hashtag"));
}
@Override
public Map<String, Object> getComponentConfiguration() {
return null;
}
}
Submitting a topology is the main application. Twitter topology consists of TwitterSampleSpout, HashtagReaderBolt, and HashtagCounterBolt. The following program code shows how to submit a topology.
import java.util.*;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Values;
import backtype.storm.Config;
import backtype.storm.LocalCluster;
import backtype.storm.topology.TopologyBuilder;
public class TwitterHashtagStorm {
public static void main(String[] args) throws Exception{
String consumerKey = args[0];
String consumerSecret = args[1];
String accessToken = args[2];
String accessTokenSecret = args[3];
String[] arguments = args.clone();
String[] keyWords = Arrays.copyOfRange(arguments, 4, arguments.length);
Config config = new Config();
config.setDebug(true);
TopologyBuilder builder = new TopologyBuilder();
builder.setSpout("twitter-spout", new TwitterSampleSpout(consumerKey,
consumerSecret, accessToken, accessTokenSecret, keyWords));
builder.setBolt("twitter-hashtag-reader-bolt", new HashtagReaderBolt())
.shuffleGrouping("twitter-spout");
builder.setBolt("twitter-hashtag-counter-bolt", new HashtagCounterBolt())
.fieldsGrouping("twitter-hashtag-reader-bolt", new Fields("hashtag"));
LocalCluster cluster = new LocalCluster();
cluster.submitTopology("TwitterHashtagStorm", config,
builder.createTopology());
Thread.sleep(10000);
cluster.shutdown();
}
}
The complete application has four Java codes. They are as follows −
TwitterSampleSpout.java
HashtagReaderBolt.java
HashtagCounterBolt.java
TwitterHashtagStorm.java
You can compile the application using the following command −
javac -cp “/path/to/storm/apache-storm-0.9.5/lib/*”:”/path/to/twitter4j/lib/*” *.java
Execute the application using the following commands −
javac -cp “/path/to/storm/apache-storm-0.9.5/lib/*”:”/path/to/twitter4j/lib/*”:.
TwitterHashtagStorm <customerkey> <customersecret> <accesstoken> <accesstokensecret>
<keyword1> <keyword2> ... <keywordN>
The application will print the current available hashtag and its count. The output should be similar to the following −
Result: jazztastic : 1
Result: foodie : 1
Result: Redskins : 1
Result: Recipe : 1
Result: cook : 1
Result: android : 1
Result: food : 2
Result: NoToxicHorseMeat : 1
Result: Purrs4Peace : 1
Result: livemusic : 1
Result: VIPremium : 1
Result: Frome : 1
Result: SundayRoast : 1
Result: Millennials : 1
Result: HealthWithKier : 1
Result: LPs30DaysofGratitude : 1
Result: cooking : 1
Result: gameinsight : 1
Result: Countryfile : 1
Result: androidgames : 1
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2048,
"s": 1927,
"text": "Here in this chapter, we will discuss a real-time application of Apache Storm. We will see how Storm is used in Twitter."
},
{
"code": null,
"e": 2414,
"s": 2048,
"text": "Twitter is an online social networking service that provides a platform to send and receive user tweets. Registered users can read and post tweets, but unregistered users can only read tweets. Hashtag is used to categorize tweets by keyword by appending # before the relevant keyword. Now let us take a real-time scenario of finding the most used hashtag per topic."
},
{
"code": null,
"e": 2688,
"s": 2414,
"text": "The purpose of spout is to get the tweets submitted by people as soon as possible. Twitter provides “Twitter Streaming API”, a web service based tool to retrieve the tweets submitted by people in real time. Twitter Streaming API can be accessed in any programming language."
},
{
"code": null,
"e": 3034,
"s": 2688,
"text": "twitter4j is an open source, unofficial Java library, which provides a Java based module to easily access the Twitter Streaming API. twitter4j provides a listener-based framework to access the tweets. To access the Twitter Streaming API, we need to sign in for Twitter developer account and should get the following OAuth authentication details."
},
{
"code": null,
"e": 3046,
"s": 3034,
"text": "Customerkey"
},
{
"code": null,
"e": 3061,
"s": 3046,
"text": "CustomerSecret"
},
{
"code": null,
"e": 3073,
"s": 3061,
"text": "AccessToken"
},
{
"code": null,
"e": 3092,
"s": 3073,
"text": "AccessTookenSecret"
},
{
"code": null,
"e": 3375,
"s": 3092,
"text": "Storm provides a twitter spout, TwitterSampleSpout, in its starter kit. We will be using it to retrieve the tweets. The spout needs OAuth authentication details and at least a keyword. The spout will emit real-time tweets based on keywords. The complete program code is given below."
},
{
"code": null,
"e": 7123,
"s": 3375,
"text": "import java.util.Map;\nimport java.util.concurrent.LinkedBlockingQueue;\n\nimport twitter4j.FilterQuery;\nimport twitter4j.StallWarning;\nimport twitter4j.Status;\nimport twitter4j.StatusDeletionNotice;\nimport twitter4j.StatusListener;\n\nimport twitter4j.TwitterStream;\nimport twitter4j.TwitterStreamFactory;\nimport twitter4j.auth.AccessToken;\nimport twitter4j.conf.ConfigurationBuilder;\n\nimport backtype.storm.Config;\nimport backtype.storm.spout.SpoutOutputCollector;\n\nimport backtype.storm.task.TopologyContext;\nimport backtype.storm.topology.OutputFieldsDeclarer;\nimport backtype.storm.topology.base.BaseRichSpout;\nimport backtype.storm.tuple.Fields;\nimport backtype.storm.tuple.Values;\n\nimport backtype.storm.utils.Utils;\n\n@SuppressWarnings(\"serial\")\npublic class TwitterSampleSpout extends BaseRichSpout {\n SpoutOutputCollector _collector;\n LinkedBlockingQueue<Status> queue = null;\n TwitterStream _twitterStream;\n\t\t\n String consumerKey;\n String consumerSecret;\n String accessToken;\n String accessTokenSecret;\n String[] keyWords;\n\t\t\n public TwitterSampleSpout(String consumerKey, String consumerSecret,\n String accessToken, String accessTokenSecret, String[] keyWords) {\n this.consumerKey = consumerKey;\n this.consumerSecret = consumerSecret;\n this.accessToken = accessToken;\n this.accessTokenSecret = accessTokenSecret;\n this.keyWords = keyWords;\n }\n\t\t\n public TwitterSampleSpout() {\n // TODO Auto-generated constructor stub\n }\n\t\t\n @Override\n public void open(Map conf, TopologyContext context,\n SpoutOutputCollector collector) {\n queue = new LinkedBlockingQueue<Status>(1000);\n _collector = collector;\n StatusListener listener = new StatusListener() {\n @Override\n public void onStatus(Status status) {\n queue.offer(status);\n }\n\t\t\t\t\t\n @Override\n public void onDeletionNotice(StatusDeletionNotice sdn) {}\n\t\t\t\t\t\n @Override\n public void onTrackLimitationNotice(int i) {}\n\t\t\t\t\t\n @Override\n public void onScrubGeo(long l, long l1) {}\n\t\t\t\t\t\n @Override\n public void onException(Exception ex) {}\n\t\t\t\t\t\n @Override\n public void onStallWarning(StallWarning arg0) {\n // TODO Auto-generated method stub\n }\n };\n\t\t\t\t\n ConfigurationBuilder cb = new ConfigurationBuilder();\n\t\t\t\t\n cb.setDebugEnabled(true)\n .setOAuthConsumerKey(consumerKey)\n .setOAuthConsumerSecret(consumerSecret)\n .setOAuthAccessToken(accessToken)\n .setOAuthAccessTokenSecret(accessTokenSecret);\n\t\t\t\t\t\n _twitterStream = new TwitterStreamFactory(cb.build()).getInstance();\n _twitterStream.addListener(listener);\n\t\t\t\t\n if (keyWords.length == 0) {\n _twitterStream.sample();\n }else {\n FilterQuery query = new FilterQuery().track(keyWords);\n _twitterStream.filter(query);\n }\n }\n\t\t\t\n @Override\n public void nextTuple() {\n Status ret = queue.poll();\n\t\t\t\t\n if (ret == null) {\n Utils.sleep(50);\n } else {\n _collector.emit(new Values(ret));\n }\n }\n\t\t\t\n @Override\n public void close() {\n _twitterStream.shutdown();\n }\n\t\t\t\n @Override\n public Map<String, Object> getComponentConfiguration() {\n Config ret = new Config();\n ret.setMaxTaskParallelism(1);\n return ret;\n }\n\t\t\t\n @Override\n public void ack(Object id) {}\n\t\t\t\n @Override\n public void fail(Object id) {}\n\t\t\t\n @Override\n public void declareOutputFields(OutputFieldsDeclarer declarer) {\n declarer.declare(new Fields(\"tweet\"));\n }\n}"
},
{
"code": null,
"e": 7438,
"s": 7123,
"text": "The tweet emitted by spout will be forwarded to HashtagReaderBolt, which will process the tweet and emit all the available hashtags. HashtagReaderBolt uses getHashTagEntities method provided by twitter4j. getHashTagEntities reads the tweet and returns the list of hashtag. The complete program code is as follows −"
},
{
"code": null,
"e": 8653,
"s": 7438,
"text": "import java.util.HashMap;\nimport java.util.Map;\n\nimport twitter4j.*;\nimport twitter4j.conf.*;\n\nimport backtype.storm.tuple.Fields;\nimport backtype.storm.tuple.Values;\n\nimport backtype.storm.task.OutputCollector;\nimport backtype.storm.task.TopologyContext;\nimport backtype.storm.topology.IRichBolt;\nimport backtype.storm.topology.OutputFieldsDeclarer;\nimport backtype.storm.tuple.Tuple;\n\npublic class HashtagReaderBolt implements IRichBolt {\n private OutputCollector collector;\n\n @Override\n public void prepare(Map conf, TopologyContext context, OutputCollector collector) {\n this.collector = collector;\n }\n\n @Override\n public void execute(Tuple tuple) {\n Status tweet = (Status) tuple.getValueByField(\"tweet\");\n for(HashtagEntity hashtage : tweet.getHashtagEntities()) {\n System.out.println(\"Hashtag: \" + hashtage.getText());\n this.collector.emit(new Values(hashtage.getText()));\n }\n }\n\n @Override\n public void cleanup() {}\n\n @Override\n public void declareOutputFields(OutputFieldsDeclarer declarer) {\n declarer.declare(new Fields(\"hashtag\"));\n }\n\t\n @Override\n public Map<String, Object> getComponentConfiguration() {\n return null;\n }\n\t\n}"
},
{
"code": null,
"e": 8875,
"s": 8653,
"text": "The emitted hashtag will be forwarded to HashtagCounterBolt. This bolt will process all the hashtags and save each and every hashtag and its count in memory using Java Map object. The complete program code is given below."
},
{
"code": null,
"e": 10284,
"s": 8875,
"text": "import java.util.HashMap;\nimport java.util.Map;\n\nimport backtype.storm.tuple.Fields;\nimport backtype.storm.tuple.Values;\n\nimport backtype.storm.task.OutputCollector;\nimport backtype.storm.task.TopologyContext;\n\nimport backtype.storm.topology.IRichBolt;\nimport backtype.storm.topology.OutputFieldsDeclarer;\nimport backtype.storm.tuple.Tuple;\n\npublic class HashtagCounterBolt implements IRichBolt {\n Map<String, Integer> counterMap;\n private OutputCollector collector;\n\n @Override\n public void prepare(Map conf, TopologyContext context, OutputCollector collector) {\n this.counterMap = new HashMap<String, Integer>();\n this.collector = collector;\n }\n\n @Override\n public void execute(Tuple tuple) {\n String key = tuple.getString(0);\n\n if(!counterMap.containsKey(key)){\n counterMap.put(key, 1);\n }else{\n Integer c = counterMap.get(key) + 1;\n counterMap.put(key, c);\n }\n\t\t\n collector.ack(tuple);\n }\n\n @Override\n public void cleanup() {\n for(Map.Entry<String, Integer> entry:counterMap.entrySet()){\n System.out.println(\"Result: \" + entry.getKey()+\" : \" + entry.getValue());\n }\n }\n\n @Override\n public void declareOutputFields(OutputFieldsDeclarer declarer) {\n declarer.declare(new Fields(\"hashtag\"));\n }\n\t\n @Override\n public Map<String, Object> getComponentConfiguration() {\n return null;\n }\n\t\n}"
},
{
"code": null,
"e": 10482,
"s": 10284,
"text": "Submitting a topology is the main application. Twitter topology consists of TwitterSampleSpout, HashtagReaderBolt, and HashtagCounterBolt. The following program code shows how to submit a topology."
},
{
"code": null,
"e": 11827,
"s": 10482,
"text": "import java.util.*;\n\nimport backtype.storm.tuple.Fields;\nimport backtype.storm.tuple.Values;\nimport backtype.storm.Config;\nimport backtype.storm.LocalCluster;\nimport backtype.storm.topology.TopologyBuilder;\n\npublic class TwitterHashtagStorm {\n public static void main(String[] args) throws Exception{\n String consumerKey = args[0];\n String consumerSecret = args[1];\n\t\t\n String accessToken = args[2];\n String accessTokenSecret = args[3];\n\t\t\n String[] arguments = args.clone();\n String[] keyWords = Arrays.copyOfRange(arguments, 4, arguments.length);\n\t\t\n Config config = new Config();\n config.setDebug(true);\n\t\t\n TopologyBuilder builder = new TopologyBuilder();\n builder.setSpout(\"twitter-spout\", new TwitterSampleSpout(consumerKey,\n consumerSecret, accessToken, accessTokenSecret, keyWords));\n\n builder.setBolt(\"twitter-hashtag-reader-bolt\", new HashtagReaderBolt())\n .shuffleGrouping(\"twitter-spout\");\n\n builder.setBolt(\"twitter-hashtag-counter-bolt\", new HashtagCounterBolt())\n .fieldsGrouping(\"twitter-hashtag-reader-bolt\", new Fields(\"hashtag\"));\n\t\t\t\n LocalCluster cluster = new LocalCluster();\n cluster.submitTopology(\"TwitterHashtagStorm\", config,\n builder.createTopology());\n Thread.sleep(10000);\n cluster.shutdown();\n }\n}"
},
{
"code": null,
"e": 11895,
"s": 11827,
"text": "The complete application has four Java codes. They are as follows −"
},
{
"code": null,
"e": 11919,
"s": 11895,
"text": "TwitterSampleSpout.java"
},
{
"code": null,
"e": 11942,
"s": 11919,
"text": "HashtagReaderBolt.java"
},
{
"code": null,
"e": 11966,
"s": 11942,
"text": "HashtagCounterBolt.java"
},
{
"code": null,
"e": 11991,
"s": 11966,
"text": "TwitterHashtagStorm.java"
},
{
"code": null,
"e": 12053,
"s": 11991,
"text": "You can compile the application using the following command −"
},
{
"code": null,
"e": 12140,
"s": 12053,
"text": "javac -cp “/path/to/storm/apache-storm-0.9.5/lib/*”:”/path/to/twitter4j/lib/*” *.java\n"
},
{
"code": null,
"e": 12195,
"s": 12140,
"text": "Execute the application using the following commands −"
},
{
"code": null,
"e": 12399,
"s": 12195,
"text": "javac -cp “/path/to/storm/apache-storm-0.9.5/lib/*”:”/path/to/twitter4j/lib/*”:.\nTwitterHashtagStorm <customerkey> <customersecret> <accesstoken> <accesstokensecret>\n<keyword1> <keyword2> ... <keywordN>\n"
},
{
"code": null,
"e": 12519,
"s": 12399,
"text": "The application will print the current available hashtag and its count. The output should be similar to the following −"
},
{
"code": null,
"e": 12972,
"s": 12519,
"text": "Result: jazztastic : 1\nResult: foodie : 1\nResult: Redskins : 1\nResult: Recipe : 1\nResult: cook : 1\nResult: android : 1\nResult: food : 2\nResult: NoToxicHorseMeat : 1\nResult: Purrs4Peace : 1\nResult: livemusic : 1\nResult: VIPremium : 1\nResult: Frome : 1\nResult: SundayRoast : 1\nResult: Millennials : 1\nResult: HealthWithKier : 1\nResult: LPs30DaysofGratitude : 1\nResult: cooking : 1\nResult: gameinsight : 1\nResult: Countryfile : 1\nResult: androidgames : 1\n"
},
{
"code": null,
"e": 13007,
"s": 12972,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 13026,
"s": 13007,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 13061,
"s": 13026,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 13082,
"s": 13061,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 13115,
"s": 13082,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 13128,
"s": 13115,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 13163,
"s": 13128,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 13181,
"s": 13163,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 13214,
"s": 13181,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 13232,
"s": 13214,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 13265,
"s": 13232,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 13283,
"s": 13265,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 13290,
"s": 13283,
"text": " Print"
},
{
"code": null,
"e": 13301,
"s": 13290,
"text": " Add Notes"
}
] |
Java Program to Calculate Standard Deviation - GeeksforGeeks | 27 Nov, 2020
The standard deviation is the measure of how spread out numbers are. Its symbol is sigma( σ ). It is the square root of variance. The task is to calculate the standard deviation of some numbers.
Consider an example that consists of 6 numbers and then to calculate the standard deviation, first we need to calculate the sum of 6 numbers, and then the mean will be calculated. Then the standard deviation will be calculated using the standard deviation formula.
Standard deviation = square root of ∑(Xi - ų)2 / N
where,
Xi = each element of the array
ų = mean of the elements of the array
N = Number of elements
∑ = Sum of the each element
Input : [12, 32, 11, 55, 10, 23, 14, 30]
Output : 14.438988
Input : [10, 12, 22, 34, 21]
Output : 8.541663
Approach: Using Mathematical Formula
First, create a class called calculateSD2 Then create the main method and then in the main method create an object of the above class and call it using the object.Then declare an array in this class with the values given in the above example.Now, in order to iterate through the array, we need to find the size of the array.Now, use the for-loop and iterate through this array and increment it by 1 as we need to print all the elements of the array.Then, again use the for-loop and iterate through the array in order to calculate the sum of the elements of the array.After that, the mean will be calculated by mean = sum / n, where n is the number of elements in the array.Now, the standard deviation will be calculated with the help of mean, which is done by iterating through for-loop again and with the help of Mathematical predefined methods like Math.pow and Math.sqrt.After that, the value will be returned by that class and then print.
First, create a class called calculateSD2
Then create the main method and then in the main method create an object of the above class and call it using the object.
Then declare an array in this class with the values given in the above example.
Now, in order to iterate through the array, we need to find the size of the array.
Now, use the for-loop and iterate through this array and increment it by 1 as we need to print all the elements of the array.
Then, again use the for-loop and iterate through the array in order to calculate the sum of the elements of the array.
After that, the mean will be calculated by mean = sum / n, where n is the number of elements in the array.
Now, the standard deviation will be calculated with the help of mean, which is done by iterating through for-loop again and with the help of Mathematical predefined methods like Math.pow and Math.sqrt.
After that, the value will be returned by that class and then print.
Java
// Java program to calculate the standard deviation class calculateSD2 { double sum = 0.0; double standardDeviation = 0.0; double mean = 0.0; double res = 0.0; double sq = 0.0; double SD() { int[] arr = { 12, 32, 11, 55, 10, 23, 14, 30 }; int n = arr.length; System.out.println("Elements are:"); for (int i = 0; i < n; i++) { System.out.println(arr[i]); } for (int i = 0; i < n; i++) { sum = sum + arr[i]; } mean = sum / (n); for (int i = 0; i < n; i++) { standardDeviation = standardDeviation + Math.pow((arr[i] - mean), 2); } sq = standardDeviation / n; res = Math.sqrt(sq); return res; }} public class Standard { public static void main(String[] args) { calculateSD2 calsd = new calculateSD2(); double res = calsd.SD(); System.out.format("Standard Deviation = %.6f", res); }}
Elements are:
12
32
11
55
10
23
14
30
Standard Deviation = 14.438988
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Hashtable in Java
Constructors in Java
Different ways of Reading a text file in Java
Comparator Interface in Java with Examples
HashMap containsKey() Method 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": 23557,
"s": 23529,
"text": "\n27 Nov, 2020"
},
{
"code": null,
"e": 23753,
"s": 23557,
"text": "The standard deviation is the measure of how spread out numbers are. Its symbol is sigma( σ ). It is the square root of variance. The task is to calculate the standard deviation of some numbers. "
},
{
"code": null,
"e": 24018,
"s": 23753,
"text": "Consider an example that consists of 6 numbers and then to calculate the standard deviation, first we need to calculate the sum of 6 numbers, and then the mean will be calculated. Then the standard deviation will be calculated using the standard deviation formula."
},
{
"code": null,
"e": 24278,
"s": 24018,
"text": "Standard deviation = square root of ∑(Xi - ų)2 / N \n where, \n Xi = each element of the array\n ų = mean of the elements of the array\n N = Number of elements\n ∑ = Sum of the each element"
},
{
"code": null,
"e": 24386,
"s": 24278,
"text": "Input : [12, 32, 11, 55, 10, 23, 14, 30]\nOutput : 14.438988\n\nInput : [10, 12, 22, 34, 21]\nOutput : 8.541663"
},
{
"code": null,
"e": 24423,
"s": 24386,
"text": "Approach: Using Mathematical Formula"
},
{
"code": null,
"e": 25366,
"s": 24423,
"text": "First, create a class called calculateSD2 Then create the main method and then in the main method create an object of the above class and call it using the object.Then declare an array in this class with the values given in the above example.Now, in order to iterate through the array, we need to find the size of the array.Now, use the for-loop and iterate through this array and increment it by 1 as we need to print all the elements of the array.Then, again use the for-loop and iterate through the array in order to calculate the sum of the elements of the array.After that, the mean will be calculated by mean = sum / n, where n is the number of elements in the array.Now, the standard deviation will be calculated with the help of mean, which is done by iterating through for-loop again and with the help of Mathematical predefined methods like Math.pow and Math.sqrt.After that, the value will be returned by that class and then print."
},
{
"code": null,
"e": 25409,
"s": 25366,
"text": "First, create a class called calculateSD2 "
},
{
"code": null,
"e": 25531,
"s": 25409,
"text": "Then create the main method and then in the main method create an object of the above class and call it using the object."
},
{
"code": null,
"e": 25611,
"s": 25531,
"text": "Then declare an array in this class with the values given in the above example."
},
{
"code": null,
"e": 25694,
"s": 25611,
"text": "Now, in order to iterate through the array, we need to find the size of the array."
},
{
"code": null,
"e": 25820,
"s": 25694,
"text": "Now, use the for-loop and iterate through this array and increment it by 1 as we need to print all the elements of the array."
},
{
"code": null,
"e": 25939,
"s": 25820,
"text": "Then, again use the for-loop and iterate through the array in order to calculate the sum of the elements of the array."
},
{
"code": null,
"e": 26046,
"s": 25939,
"text": "After that, the mean will be calculated by mean = sum / n, where n is the number of elements in the array."
},
{
"code": null,
"e": 26248,
"s": 26046,
"text": "Now, the standard deviation will be calculated with the help of mean, which is done by iterating through for-loop again and with the help of Mathematical predefined methods like Math.pow and Math.sqrt."
},
{
"code": null,
"e": 26317,
"s": 26248,
"text": "After that, the value will be returned by that class and then print."
},
{
"code": null,
"e": 26322,
"s": 26317,
"text": "Java"
},
{
"code": "// Java program to calculate the standard deviation class calculateSD2 { double sum = 0.0; double standardDeviation = 0.0; double mean = 0.0; double res = 0.0; double sq = 0.0; double SD() { int[] arr = { 12, 32, 11, 55, 10, 23, 14, 30 }; int n = arr.length; System.out.println(\"Elements are:\"); for (int i = 0; i < n; i++) { System.out.println(arr[i]); } for (int i = 0; i < n; i++) { sum = sum + arr[i]; } mean = sum / (n); for (int i = 0; i < n; i++) { standardDeviation = standardDeviation + Math.pow((arr[i] - mean), 2); } sq = standardDeviation / n; res = Math.sqrt(sq); return res; }} public class Standard { public static void main(String[] args) { calculateSD2 calsd = new calculateSD2(); double res = calsd.SD(); System.out.format(\"Standard Deviation = %.6f\", res); }}",
"e": 27360,
"s": 26322,
"text": null
},
{
"code": null,
"e": 27429,
"s": 27360,
"text": "Elements are:\n12\n32\n11\n55\n10\n23\n14\n30\nStandard Deviation = 14.438988"
},
{
"code": null,
"e": 27436,
"s": 27429,
"text": "Picked"
},
{
"code": null,
"e": 27441,
"s": 27436,
"text": "Java"
},
{
"code": null,
"e": 27455,
"s": 27441,
"text": "Java Programs"
},
{
"code": null,
"e": 27460,
"s": 27455,
"text": "Java"
},
{
"code": null,
"e": 27558,
"s": 27460,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27567,
"s": 27558,
"text": "Comments"
},
{
"code": null,
"e": 27580,
"s": 27567,
"text": "Old Comments"
},
{
"code": null,
"e": 27598,
"s": 27580,
"text": "Hashtable in Java"
},
{
"code": null,
"e": 27619,
"s": 27598,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27665,
"s": 27619,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27708,
"s": 27665,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 27745,
"s": 27708,
"text": "HashMap containsKey() Method in Java"
},
{
"code": null,
"e": 27789,
"s": 27745,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 27815,
"s": 27789,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 27849,
"s": 27815,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 27896,
"s": 27849,
"text": "Implementing a Linked List in Java using Class"
}
] |
Check if suffix and prefix of a string are palindromes - GeeksforGeeks | 26 May, 2021
Given a string ‘s’, the task is to check whether the string has both prefix and suffix substrings of length greater than 1 which are palindromes. Print ‘YES’ if the above condition is satisfied or ‘NO’ otherwise.Examples:
Input : s = abartbb
Output : YES
Explanation : The string has prefix substring 'aba'
and suffix substring 'bb' which are both palindromes, so the output is 'YES'.
Input : s = abcc
Output : NO
Explanation : The string has no prefix substring which is palindrome,
it only has a suffix substring 'cc' which is a palindrome.
So the output is 'NO'.
Approach:
First, check all the prefix substrings of length > 1 to find if there’s any which is a palindrome.
Check all the suffix substrings as well.
If both the conditions are true, then the output is ‘YES’.
Otherwise, the output is ‘NO’.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to check whether// the string is a palindromebool isPalindrome(string r){ string p = r; // reverse the string to // compare with the // original string reverse(p.begin(), p.end()); // check if both are same return (r == p);} // Function to check whether the string// has prefix and suffix substrings// of length greater than 1// which are palindromes.bool CheckStr(string s){ int l = s.length(); // check all prefix substrings int i; for (i = 2; i <= l; i++) { // check if the prefix substring // is a palindrome if (isPalindrome(s.substr(0, i))) break; } // If we did not find any palindrome prefix // of length greater than 1. if (i == (l+1)) return false; // check all suffix substrings, // as the string is reversed now i = 2; for (i = 2; i <= l; i++) { // check if the suffix substring // is a palindrome if (isPalindrome(s.substr(l-i, i))) return true; } // If we did not find a suffix return false; } // Driver codeint main(){ string s = "abccbarfgdbd"; if (CheckStr(s)) cout << "YES\n"; else cout << "NO\n"; return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ static String reverse(String input) { char[] a = input.toCharArray(); int l, r = 0; r = a.length - 1; for (l = 0; l < r; l++, r--) { // Swap values of l and r char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.valueOf(a); } // Function to check whether // the string is a palindrome static boolean isPalindrome(String r) { String p = r; // reverse the string to // compare with the // original string p = reverse(p); // check if both are same return (r.equals(p)); } // Function to check whether the string // has prefix and suffix substrings // of length greater than 1 // which are palindromes. static boolean CheckStr(String s) { int l = s.length(); // check all prefix substrings int i; for (i = 2; i <= l; i++) { // check if the prefix substring // is a palindrome if (isPalindrome(s.substring(0, i))) { break; } } // If we did not find any palindrome prefix // of length greater than 1. if (i == (l + 1)) { return false; } // check all suffix substrings, // as the string is reversed now i = 2; for (i = 2; i <=l; i++) { // check if the suffix substring // is a palindrome if (isPalindrome(s.substring(l-i,l))) { return true; } } // If we did not find a suffix return false; } // Driver code public static void main(String args[]) { String s = "abccbarfgdbd"; if (CheckStr(s)) { System.out.println("Yes"); } else { System.out.println("No"); } }} // This code is contributed by Rajput-Ji
# Python3 implementation of the approach # Function to check whether# the string is a palindromedef isPalindrome(r): # Reverse the string and assign # it to new variable for comparison p = r[::-1] # check if both are same return r == p # Function to check whether the string# has prefix and suffix substrings# of length greater than 1# which are palindromes.def CheckStr(s): l = len(s) # check all prefix substrings i = 0 for i in range(2, l + 1): # check if the prefix substring # is a palindrome if isPalindrome(s[0:i]) == True: break # If we did not find any palindrome # prefix of length greater than 1. if i == (l + 1): return False # check all suffix substrings, # as the string is reversed now for i in range(2, l + 1): # check if the suffix substring # is a palindrome if isPalindrome(s[l - i : l]) == True: return True # If we did not find a suffix return False # Driver codeif __name__ == "__main__": s = "abccbarfgdbd" if CheckStr(s) == True: print("YES") else: print("NO") # This code is contributed by Rituraj Jain
// C# implementation of the approachusing System; class GFG{ static String reverse(String input) { char[] a = input.ToCharArray(); int l, r = 0; r = a.Length - 1; for (l = 0; l < r; l++, r--) { // Swap values of l and r char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.Join("",a); } // Function to check whether // the string is a palindrome static Boolean isPalindrome(String r) { String p = r; // reverse the string to // compare with the // original string p = reverse(p); // check if both are same return (r.Equals(p)); } // Function to check whether the string // has prefix and suffix substrings // of length greater than 1 // which are palindromes. static Boolean CheckStr(String s) { int l = s.Length; // check all prefix substrings int i; for (i = 2; i <= l; i++) { // check if the prefix substring // is a palindrome if (isPalindrome(s.Substring(0, i))) { break; } } // If we did not find any palindrome prefix // of length greater than 1. if (i == (l + 1)) { return false; } // check all suffix substrings, // as the string is reversed now i = 2; for (i = 2; i <=l; i++) { // check if the suffix substring // is a palindrome if (isPalindrome(s.Substring(l-i,i))) { return true; } } // If we did not find a suffix return false; } // Driver code public static void Main(String []args) { String s = "abccbarfgdbd"; if (CheckStr(s)) { Console.WriteLine("Yes"); } else { Console.WriteLine("No"); } }} // This code is contributed by 29AjayKumar
<?php// PHP implementation of the approach // Function to check whether// the string is a palindromefunction isPalindrome($r){ $p = $r; // reverse the string to // compare with the // original string strrev($p); // check if both are same return ($r == $p);} // Function to check whether the// string has prefix and suffix// substrings of length greater// than 1 which are palindromes.function CheckStr($s){ $l = strlen($s); // check all prefix substrings for ($i = 2; $i <= $l; $i++) { // check if the prefix substring // is a palindrome if (isPalindrome(substr($s, 0, $i))) break; } // If we did not find any palindrome // prefix of length greater than 1. if ($i == ($l + 1)) return false; // check all suffix substrings, // as the string is reversed now $i = 2; for ($i = 2; $i <= $l; $i++) { // check if the suffix substring // is a palindrome if (isPalindrome(substr($s, $l - $i, $i))) return true; } // If we did not find a suffix return false;} // Driver code$s = "abccbarfgdbd";if (CheckStr($s)) echo ("YES\n");else echo ("NO\n"); // This code is contributed// by Shivi_Aggarwal?>
<script> // JavaScript implementation of the approach // Function to check whether// the string is a palindromefunction isPalindrome(r){ var p = r; // reverse the string to // compare with the // original string p.split('').reverse().join(''); // check if both are same return (r == p);} // Function to check whether the string// has prefix and suffix substrings// of length greater than 1// which are palindromes.function CheckStr( s){ var l = s.length; // check all prefix substrings var i; for (i = 2; i <= l; i++) { // check if the prefix substring // is a palindrome if (isPalindrome(s.substring(0, i))) break; } // If we did not find any palindrome prefix // of length greater than 1. if (i == (l+1)) return false; // check all suffix substrings, // as the string is reversed now i = 2; for (i = 2; i <= l; i++) { // check if the suffix substring // is a palindrome if (isPalindrome(s.substring(l-i, l))) return true; } // If we did not find a suffix return false; } // Driver codevar s = "abccbarfgdbd";if (CheckStr(s)) document.write( "YES");else document.write( "NO"); </script>
YES
Complexity: O(n^2)
Shivi_Aggarwal
rituraj_jain
Rajput-Ji
29AjayKumar
rutvik_56
cpp-string
palindrome
substring
Strings
Strings
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 String Coding Problems for Interviews
Vigenère Cipher
How to Append a Character to a String in C
Program to add two binary strings
Convert character array to string in C++
Return maximum occurring character in an input string
Naive algorithm for Pattern Searching
Hill Cipher
sprintf() in C
A Program to check if strings are rotations of each other or not | [
{
"code": null,
"e": 24437,
"s": 24409,
"text": "\n26 May, 2021"
},
{
"code": null,
"e": 24661,
"s": 24437,
"text": "Given a string ‘s’, the task is to check whether the string has both prefix and suffix substrings of length greater than 1 which are palindromes. Print ‘YES’ if the above condition is satisfied or ‘NO’ otherwise.Examples: "
},
{
"code": null,
"e": 25009,
"s": 24661,
"text": "Input : s = abartbb\nOutput : YES\nExplanation : The string has prefix substring 'aba' \nand suffix substring 'bb' which are both palindromes, so the output is 'YES'.\n\nInput : s = abcc\nOutput : NO\nExplanation : The string has no prefix substring which is palindrome, \nit only has a suffix substring 'cc' which is a palindrome. \nSo the output is 'NO'."
},
{
"code": null,
"e": 25023,
"s": 25011,
"text": "Approach: "
},
{
"code": null,
"e": 25122,
"s": 25023,
"text": "First, check all the prefix substrings of length > 1 to find if there’s any which is a palindrome."
},
{
"code": null,
"e": 25163,
"s": 25122,
"text": "Check all the suffix substrings as well."
},
{
"code": null,
"e": 25222,
"s": 25163,
"text": "If both the conditions are true, then the output is ‘YES’."
},
{
"code": null,
"e": 25253,
"s": 25222,
"text": "Otherwise, the output is ‘NO’."
},
{
"code": null,
"e": 25306,
"s": 25253,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25310,
"s": 25306,
"text": "C++"
},
{
"code": null,
"e": 25315,
"s": 25310,
"text": "Java"
},
{
"code": null,
"e": 25323,
"s": 25315,
"text": "Python3"
},
{
"code": null,
"e": 25326,
"s": 25323,
"text": "C#"
},
{
"code": null,
"e": 25330,
"s": 25326,
"text": "PHP"
},
{
"code": null,
"e": 25341,
"s": 25330,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to check whether// the string is a palindromebool isPalindrome(string r){ string p = r; // reverse the string to // compare with the // original string reverse(p.begin(), p.end()); // check if both are same return (r == p);} // Function to check whether the string// has prefix and suffix substrings// of length greater than 1// which are palindromes.bool CheckStr(string s){ int l = s.length(); // check all prefix substrings int i; for (i = 2; i <= l; i++) { // check if the prefix substring // is a palindrome if (isPalindrome(s.substr(0, i))) break; } // If we did not find any palindrome prefix // of length greater than 1. if (i == (l+1)) return false; // check all suffix substrings, // as the string is reversed now i = 2; for (i = 2; i <= l; i++) { // check if the suffix substring // is a palindrome if (isPalindrome(s.substr(l-i, i))) return true; } // If we did not find a suffix return false; } // Driver codeint main(){ string s = \"abccbarfgdbd\"; if (CheckStr(s)) cout << \"YES\\n\"; else cout << \"NO\\n\"; return 0;}",
"e": 26638,
"s": 25341,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{ static String reverse(String input) { char[] a = input.toCharArray(); int l, r = 0; r = a.length - 1; for (l = 0; l < r; l++, r--) { // Swap values of l and r char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.valueOf(a); } // Function to check whether // the string is a palindrome static boolean isPalindrome(String r) { String p = r; // reverse the string to // compare with the // original string p = reverse(p); // check if both are same return (r.equals(p)); } // Function to check whether the string // has prefix and suffix substrings // of length greater than 1 // which are palindromes. static boolean CheckStr(String s) { int l = s.length(); // check all prefix substrings int i; for (i = 2; i <= l; i++) { // check if the prefix substring // is a palindrome if (isPalindrome(s.substring(0, i))) { break; } } // If we did not find any palindrome prefix // of length greater than 1. if (i == (l + 1)) { return false; } // check all suffix substrings, // as the string is reversed now i = 2; for (i = 2; i <=l; i++) { // check if the suffix substring // is a palindrome if (isPalindrome(s.substring(l-i,l))) { return true; } } // If we did not find a suffix return false; } // Driver code public static void main(String args[]) { String s = \"abccbarfgdbd\"; if (CheckStr(s)) { System.out.println(\"Yes\"); } else { System.out.println(\"No\"); } }} // This code is contributed by Rajput-Ji",
"e": 28683,
"s": 26638,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to check whether# the string is a palindromedef isPalindrome(r): # Reverse the string and assign # it to new variable for comparison p = r[::-1] # check if both are same return r == p # Function to check whether the string# has prefix and suffix substrings# of length greater than 1# which are palindromes.def CheckStr(s): l = len(s) # check all prefix substrings i = 0 for i in range(2, l + 1): # check if the prefix substring # is a palindrome if isPalindrome(s[0:i]) == True: break # If we did not find any palindrome # prefix of length greater than 1. if i == (l + 1): return False # check all suffix substrings, # as the string is reversed now for i in range(2, l + 1): # check if the suffix substring # is a palindrome if isPalindrome(s[l - i : l]) == True: return True # If we did not find a suffix return False # Driver codeif __name__ == \"__main__\": s = \"abccbarfgdbd\" if CheckStr(s) == True: print(\"YES\") else: print(\"NO\") # This code is contributed by Rituraj Jain",
"e": 29890,
"s": 28683,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ static String reverse(String input) { char[] a = input.ToCharArray(); int l, r = 0; r = a.Length - 1; for (l = 0; l < r; l++, r--) { // Swap values of l and r char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.Join(\"\",a); } // Function to check whether // the string is a palindrome static Boolean isPalindrome(String r) { String p = r; // reverse the string to // compare with the // original string p = reverse(p); // check if both are same return (r.Equals(p)); } // Function to check whether the string // has prefix and suffix substrings // of length greater than 1 // which are palindromes. static Boolean CheckStr(String s) { int l = s.Length; // check all prefix substrings int i; for (i = 2; i <= l; i++) { // check if the prefix substring // is a palindrome if (isPalindrome(s.Substring(0, i))) { break; } } // If we did not find any palindrome prefix // of length greater than 1. if (i == (l + 1)) { return false; } // check all suffix substrings, // as the string is reversed now i = 2; for (i = 2; i <=l; i++) { // check if the suffix substring // is a palindrome if (isPalindrome(s.Substring(l-i,i))) { return true; } } // If we did not find a suffix return false; } // Driver code public static void Main(String []args) { String s = \"abccbarfgdbd\"; if (CheckStr(s)) { Console.WriteLine(\"Yes\"); } else { Console.WriteLine(\"No\"); } }} // This code is contributed by 29AjayKumar",
"e": 31925,
"s": 29890,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Function to check whether// the string is a palindromefunction isPalindrome($r){ $p = $r; // reverse the string to // compare with the // original string strrev($p); // check if both are same return ($r == $p);} // Function to check whether the// string has prefix and suffix// substrings of length greater// than 1 which are palindromes.function CheckStr($s){ $l = strlen($s); // check all prefix substrings for ($i = 2; $i <= $l; $i++) { // check if the prefix substring // is a palindrome if (isPalindrome(substr($s, 0, $i))) break; } // If we did not find any palindrome // prefix of length greater than 1. if ($i == ($l + 1)) return false; // check all suffix substrings, // as the string is reversed now $i = 2; for ($i = 2; $i <= $l; $i++) { // check if the suffix substring // is a palindrome if (isPalindrome(substr($s, $l - $i, $i))) return true; } // If we did not find a suffix return false;} // Driver code$s = \"abccbarfgdbd\";if (CheckStr($s)) echo (\"YES\\n\");else echo (\"NO\\n\"); // This code is contributed// by Shivi_Aggarwal?>",
"e": 33194,
"s": 31925,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach // Function to check whether// the string is a palindromefunction isPalindrome(r){ var p = r; // reverse the string to // compare with the // original string p.split('').reverse().join(''); // check if both are same return (r == p);} // Function to check whether the string// has prefix and suffix substrings// of length greater than 1// which are palindromes.function CheckStr( s){ var l = s.length; // check all prefix substrings var i; for (i = 2; i <= l; i++) { // check if the prefix substring // is a palindrome if (isPalindrome(s.substring(0, i))) break; } // If we did not find any palindrome prefix // of length greater than 1. if (i == (l+1)) return false; // check all suffix substrings, // as the string is reversed now i = 2; for (i = 2; i <= l; i++) { // check if the suffix substring // is a palindrome if (isPalindrome(s.substring(l-i, l))) return true; } // If we did not find a suffix return false; } // Driver codevar s = \"abccbarfgdbd\";if (CheckStr(s)) document.write( \"YES\");else document.write( \"NO\"); </script>",
"e": 34438,
"s": 33194,
"text": null
},
{
"code": null,
"e": 34442,
"s": 34438,
"text": "YES"
},
{
"code": null,
"e": 34464,
"s": 34444,
"text": "Complexity: O(n^2) "
},
{
"code": null,
"e": 34479,
"s": 34464,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 34492,
"s": 34479,
"text": "rituraj_jain"
},
{
"code": null,
"e": 34502,
"s": 34492,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 34514,
"s": 34502,
"text": "29AjayKumar"
},
{
"code": null,
"e": 34524,
"s": 34514,
"text": "rutvik_56"
},
{
"code": null,
"e": 34535,
"s": 34524,
"text": "cpp-string"
},
{
"code": null,
"e": 34546,
"s": 34535,
"text": "palindrome"
},
{
"code": null,
"e": 34556,
"s": 34546,
"text": "substring"
},
{
"code": null,
"e": 34564,
"s": 34556,
"text": "Strings"
},
{
"code": null,
"e": 34572,
"s": 34564,
"text": "Strings"
},
{
"code": null,
"e": 34583,
"s": 34572,
"text": "palindrome"
},
{
"code": null,
"e": 34681,
"s": 34583,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34690,
"s": 34681,
"text": "Comments"
},
{
"code": null,
"e": 34703,
"s": 34690,
"text": "Old Comments"
},
{
"code": null,
"e": 34748,
"s": 34703,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 34765,
"s": 34748,
"text": "Vigenère Cipher"
},
{
"code": null,
"e": 34808,
"s": 34765,
"text": "How to Append a Character to a String in C"
},
{
"code": null,
"e": 34842,
"s": 34808,
"text": "Program to add two binary strings"
},
{
"code": null,
"e": 34883,
"s": 34842,
"text": "Convert character array to string in C++"
},
{
"code": null,
"e": 34937,
"s": 34883,
"text": "Return maximum occurring character in an input string"
},
{
"code": null,
"e": 34975,
"s": 34937,
"text": "Naive algorithm for Pattern Searching"
},
{
"code": null,
"e": 34987,
"s": 34975,
"text": "Hill Cipher"
},
{
"code": null,
"e": 35002,
"s": 34987,
"text": "sprintf() in C"
}
] |
How to clear Text widget content while clicking on the Entry widget itself in Tkinter? | Tkinter Text widget is an Input widget that supports multiline user input. It is also known as Text Editor which allows users to write the content and data in it. The content of the text widget can be cleared by defining the delete(0, END) command. Similarly, we can clear the content by clicking the Entry widget itself. This can be achieved by binding the function with a click event.
#Import the required libraries
from tkinter import *
#Create an instance of Tkinter Frame
win = Tk()
#Set the geometry of Tkinter Frame
win.geometry("700x250")
#Define a function to clear the content of the text widget
def click(event):
name.configure(state=NORMAL)
name.delete(0, END)
name.unbind('<Button-1>', clicked)
#Create a Label widget
label = Label(win, text= "Enter Your Name", font= ('Helvetica 13 bold'))
label.pack(pady= 10)
#Create an Entry widget
name = Entry(win, width=45)
name.insert(0, 'Enter Your Name Here...')
name.pack(pady=10)
#Bind the Entry widget with Mouse Button to clear the content
clicked = name.bind('<Button-1>', click)
win.mainloop()
Running the above code will display a window with an Entry widget.
When we click the Entry field, it will clear its content automatically. | [
{
"code": null,
"e": 1449,
"s": 1062,
"text": "Tkinter Text widget is an Input widget that supports multiline user input. It is also known as Text Editor which allows users to write the content and data in it. The content of the text widget can be cleared by defining the delete(0, END) command. Similarly, we can clear the content by clicking the Entry widget itself. This can be achieved by binding the function with a click event."
},
{
"code": null,
"e": 2133,
"s": 1449,
"text": "#Import the required libraries\nfrom tkinter import *\n\n#Create an instance of Tkinter Frame\nwin = Tk()\n\n#Set the geometry of Tkinter Frame\nwin.geometry(\"700x250\")\n\n#Define a function to clear the content of the text widget\ndef click(event):\n name.configure(state=NORMAL)\n name.delete(0, END)\n name.unbind('<Button-1>', clicked)\n\n#Create a Label widget\nlabel = Label(win, text= \"Enter Your Name\", font= ('Helvetica 13 bold'))\nlabel.pack(pady= 10)\n\n#Create an Entry widget\nname = Entry(win, width=45)\nname.insert(0, 'Enter Your Name Here...')\nname.pack(pady=10)\n\n#Bind the Entry widget with Mouse Button to clear the content\nclicked = name.bind('<Button-1>', click)\nwin.mainloop()"
},
{
"code": null,
"e": 2200,
"s": 2133,
"text": "Running the above code will display a window with an Entry widget."
},
{
"code": null,
"e": 2272,
"s": 2200,
"text": "When we click the Entry field, it will clear its content automatically."
}
] |
Sum of XOR of sum of all pairs in an array in C++ | In this problem, we are given an array arr[] of size n. Our task is to create a program to find the sum of XOR of sum of all pairs in an array.
Let’s see an example to understand the problem,
Input: arr[5, 7, 9]
Output: 22
Explanation:
(5+5) ^ (5+7) ^ (5+9) ^ (7+5) ^ (7+7) ^ (7+9) ^ (9+5) ^ (9+7) ^ (9+9) = 22
A simple solution to the problem is by using a nested loop. And creating all possible pairs from the array. And calculate the XOR of the sum of each pair.
Algorithm:
Initialise XorSum = 0
Step 1: iterate from 0 to n. Follow:
Step 1.1: iterate from 0 to n. Follow
Step 1.1.1: Update XorSum i.e. XorSum = XorSum ^ (arr[i]+arr[j]).
Step 2: return sum
Live Demo
#include <iostream>
using namespace std;
int findSumXORPair(int arr[], int n) {
int XorSum = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
XorSum = XorSum^(arr[i]+arr[j]);
return XorSum;
}
int main() {
int arr[] = {5, 7, 9};
int n = sizeof(arr)/sizeof(arr[0]);
cout<<"XOR of sum of all pairs in an array is "<<findSumXORPair(arr, n);
return 0;
}
XOR of sum of all pairs in an array is 22
This solution is not efficient as its time complexity is of the order n2.
An efficient solution is using the properties of XOR. To solve the problem, we will calculate the XOR of all elements of the array and then multiply it by two.
Algorithm:
Initialize XorSum = 0
Step 1: Iterate from 0 to n.
Step 1.1: update XorSum i.e. XorSum = XorSum ^ arr[i]
Step 2: double the sum and return it.
Live Demo
#include <iostream>
using namespace std;
int findSumXORPair(int arr[], int n) {
int XorSum = 0;
for (int i = 0; i < n; i++)
XorSum = XorSum^arr[i];
XorSum = 2*XorSum;
return XorSum;
}
int main() {
int arr[] = {5, 7, 9};
int n = sizeof(arr)/sizeof(arr[0]);
cout<<"XOR of sum of all pairs in an array is "<<findSumXORPair(arr, n);
return 0;
}
XOR of sum of all pairs in an array is 22 | [
{
"code": null,
"e": 1206,
"s": 1062,
"text": "In this problem, we are given an array arr[] of size n. Our task is to create a program to find the sum of XOR of sum of all pairs in an array."
},
{
"code": null,
"e": 1255,
"s": 1206,
"text": "Let’s see an example to understand the problem, "
},
{
"code": null,
"e": 1275,
"s": 1255,
"text": "Input: arr[5, 7, 9]"
},
{
"code": null,
"e": 1286,
"s": 1275,
"text": "Output: 22"
},
{
"code": null,
"e": 1300,
"s": 1286,
"text": "Explanation: "
},
{
"code": null,
"e": 1375,
"s": 1300,
"text": "(5+5) ^ (5+7) ^ (5+9) ^ (7+5) ^ (7+7) ^ (7+9) ^ (9+5) ^ (9+7) ^ (9+9) = 22"
},
{
"code": null,
"e": 1530,
"s": 1375,
"text": "A simple solution to the problem is by using a nested loop. And creating all possible pairs from the array. And calculate the XOR of the sum of each pair."
},
{
"code": null,
"e": 1542,
"s": 1530,
"text": "Algorithm: "
},
{
"code": null,
"e": 1564,
"s": 1542,
"text": "Initialise XorSum = 0"
},
{
"code": null,
"e": 1601,
"s": 1564,
"text": "Step 1: iterate from 0 to n. Follow:"
},
{
"code": null,
"e": 1639,
"s": 1601,
"text": "Step 1.1: iterate from 0 to n. Follow"
},
{
"code": null,
"e": 1705,
"s": 1639,
"text": "Step 1.1.1: Update XorSum i.e. XorSum = XorSum ^ (arr[i]+arr[j])."
},
{
"code": null,
"e": 1724,
"s": 1705,
"text": "Step 2: return sum"
},
{
"code": null,
"e": 1734,
"s": 1724,
"text": "Live Demo"
},
{
"code": null,
"e": 2131,
"s": 1734,
"text": "#include <iostream>\nusing namespace std;\n\nint findSumXORPair(int arr[], int n) {\n\n int XorSum = 0;\n for (int i = 0; i < n; i++)\n for (int j = 0; j < n; j++)\n XorSum = XorSum^(arr[i]+arr[j]);\n return XorSum;\n}\n\nint main() {\n\n int arr[] = {5, 7, 9};\n int n = sizeof(arr)/sizeof(arr[0]);\n cout<<\"XOR of sum of all pairs in an array is \"<<findSumXORPair(arr, n);\n return 0;\n}"
},
{
"code": null,
"e": 2173,
"s": 2131,
"text": "XOR of sum of all pairs in an array is 22"
},
{
"code": null,
"e": 2247,
"s": 2173,
"text": "This solution is not efficient as its time complexity is of the order n2."
},
{
"code": null,
"e": 2407,
"s": 2247,
"text": "An efficient solution is using the properties of XOR. To solve the problem, we will calculate the XOR of all elements of the array and then multiply it by two."
},
{
"code": null,
"e": 2419,
"s": 2407,
"text": "Algorithm: "
},
{
"code": null,
"e": 2441,
"s": 2419,
"text": "Initialize XorSum = 0"
},
{
"code": null,
"e": 2470,
"s": 2441,
"text": "Step 1: Iterate from 0 to n."
},
{
"code": null,
"e": 2524,
"s": 2470,
"text": "Step 1.1: update XorSum i.e. XorSum = XorSum ^ arr[i]"
},
{
"code": null,
"e": 2562,
"s": 2524,
"text": "Step 2: double the sum and return it."
},
{
"code": null,
"e": 2572,
"s": 2562,
"text": "Live Demo"
},
{
"code": null,
"e": 2942,
"s": 2572,
"text": "#include <iostream>\nusing namespace std;\n\nint findSumXORPair(int arr[], int n) {\n\n int XorSum = 0;\n for (int i = 0; i < n; i++)\n XorSum = XorSum^arr[i];\n XorSum = 2*XorSum;\n return XorSum;\n}\n\nint main() {\n\nint arr[] = {5, 7, 9};\n int n = sizeof(arr)/sizeof(arr[0]);\n cout<<\"XOR of sum of all pairs in an array is \"<<findSumXORPair(arr, n);\n return 0;\n}"
},
{
"code": null,
"e": 2984,
"s": 2942,
"text": "XOR of sum of all pairs in an array is 22"
}
] |
ML From Scratch: Logistic and Softmax Regression | by Luke Newman | Towards Data Science | In this ML From Scratch series we create a library of machine learning algorithms in a similar style to Scikit-Learn’s using object-oriented programming. This means you can pip install the library and play around with all the available models in a style you are already familiar with.
If you have never implemented any learning algorithms from scratch, I’ll give you three good reasons to follow along and start now:
You’ll learn in great detail the special nuances within each model growing your understanding deeply.You’ll level up your coding skills by documenting code and creating test cases ensuring all functionality works as expected.You’ll develop a better understanding of object-oriented programming allowing you to improve your machine learning project workflow.
You’ll learn in great detail the special nuances within each model growing your understanding deeply.
You’ll level up your coding skills by documenting code and creating test cases ensuring all functionality works as expected.
You’ll develop a better understanding of object-oriented programming allowing you to improve your machine learning project workflow.
To view the Github repo visit here.
This project is meant to increase our understanding of learning algorithms and is not meant for use in actual data science work.
To use the classes and functions for testing purposes create a virtual environment and pip install the project.
$ pip install mlscratch==0.1.0
To download all source code in a local repository create a virtual environment and run the following commands in your terminal.
$ git clone https://github.com/lukenew2/mlscratch $ cd mlscratch $ python setup.py install
Logistic Regression is a common regression algorithm used in classification. It estimates the probability that an instance belongs to a particular class.
If the estimated probability is greater than or equal to 50%, the model predicts the instance belongs to the positive class. If the probability is less than 50%, the model predicts the negative class.
Logistic Regression works just like a Linear Regression model. It calculates a weighted sum of the feature array (plus a bias term), but instead of outputting the result directly like a Linear Regression model does, it outputs the logistic of this result.
The logistic — noted σ(*) — is a sigmoid function that transforms its input to a number between 0 and 1.
Once the model has estimated the probability that an instance belongs to the positive class, it simply makes its prediction based on the following rules.
For our implementation from scratch we’ll need to create a sigmoid function that can transform our inputs into probabilities. Let’s see how this is done.
Here we made a class and gave it one method. This special __call__ method let’s our class behave like a function when it is called. We’ll use this property soon when we create our Logistic Regression class.
Now that we know everything about how Logistic Regression estimates probabilities and makes predictions, let’s look at how it is trained.
The objective of training is to find the set of parameters Θ so that the model predicts high probabilities for positive instances and low probabilities for negative instances. This idea is captured by the cost function log loss.
Since we’ll be using Gradient Descent in our implementation, what we need to know is the partial derivatives of the cost function with regard to the model parameters Θ.
This equation is very similar to the cost function partial derivatives of Linear Regression. For each instance it computes the prediction error and multiplies it by the instance’s feature value, and then it computes the average over all instances.
When implementing Logistic Regression with batch gradient descent we don’t want to compute the average over all instances. We want the gradient vector containing all the partial derivatives allowing us to update our parameters in the opposite direction that they’re pointing.
Let’s get into the implementation. Please read the documentation to understand what each piece of code is doing.
There we go! We have a fully functional Logistic Regression model that can perform binary classification. Let’s write a test case to ensure its working properly.
In this test case we use the famous iris dataset and transform it into a binary classification problem, perform a train/test split, do some preprocessing, and then train our Logistic Regression model and test for accuracy greater than 80% on the test set.
Now, If we ever make changes to our code for whatever reason, we’ll always have a test case ensuring our changes didn’t break the model. Trust me, this saves a lot of headaches later on especially when our code base grows.
The Logistic Regression model we implemented only supports binary classification, but can be generalized to allow support for multiple classes. This is called Softmax Regression.
The idea is simple: for each instance, the Softmax Regression model computes a score for each class, then estimates the probability the instance belongs to each class by applying the softmax function to the scores.
In this equation:
K is the number of classes.
s(x) is a vector containing the scores of each class for the instance x.
Just like the Logistic Regression classifier, the Softmax Regression classifier predicts the class with the highest estimated probability.
Implementing the softmax function from scratch is a little tricky. When you divide exponents that can potentially be very large, you run into the issue of numerical stability. To avoid this, we use a normalization trick. Notice that if we multiply the top and bottom of the fraction by a constant C and push it into the sum, we get the following equivalent expression:
We are free to choose the value of C, but a common choice is to set log(C) equal to the negative of the max of the instance x. This shifts the values so the highest value is zero. Let’s see this in code:
Here we added a softmax class to the same module as our sigmoid class using a __call__ method so our class behaves like a function when called.
Now let’s take a look at training the Softmax Regression model and its cost function. The idea is the same as Logistic Regression. We want a model that predicts high probabilities for the target class, and low probabilities for the other classes. This idea is captured by the cost function cross entropy.
In this equation:
y is the target probability that the instance belongs to the target class. In our case, this value is always equal to 1 or 0, depending on whether the instance belongs to the class or not.
In the case of two classes cross entropy is equivalent to log loss.
Since we will be implementing Softmax Regression using Gradient Descent, we need the gradient vector of this cost function with regard to Θ.
When calculating the gradients, we need our target class (y) to be of the same dimension as our estimated probabilities (p). Our estimated probabilities will be of shape (n_samples, n_classes) because for each instance we’ll have a probability associated with that instance belonging to each class.
For example, if we have three classes labeled 0, 1, and 2 we need to transform our target vector containing ([1, 2, 0]) into an array that looks like this:
([[0, 1, 0], [0, 0, 1], [1, 0, 0]])
The first column represents class 0, the second column represents class 1, and the third column represents class 2. You might have noticed that we can accomplish this by One-Hot Encoding our target vector (y). Let’s see this in code:
Now we have every helper function we need to complete our Softmax Regression model. The code is well documented so please read for explanations of what each part is doing.
And that’s it! We have successfully added Softmax Regression to our machine learning library. Let’s take a quick look at a test case to ensure it is working properly.
We’ll use the iris dataset, but this time try to classify all three classes with at least 85% accuracy. First, we load the dataset, train/test split it, perform standardization, and then train our Softmax Regression model and predict the test set.
We’re finished! Our test case passed. We successfully added Softmax Regression to our machine learning library.
That concludes this part of the ML From Scratch series. We now have a machine learning library containing the most common linear models for regression and classification including:
Linear Regression
Polynomial Regression
Ridge
Lasso
Elastic Net
Logistic Regression
Softmax Regression
As always, thanks for reading and feedback is greatly appreciated!
In the next part of the series we’ll build upon our library and create support vector machines capable of classification and regression.
Give me a follow if you like the content you see here! :-) | [
{
"code": null,
"e": 457,
"s": 172,
"text": "In this ML From Scratch series we create a library of machine learning algorithms in a similar style to Scikit-Learn’s using object-oriented programming. This means you can pip install the library and play around with all the available models in a style you are already familiar with."
},
{
"code": null,
"e": 589,
"s": 457,
"text": "If you have never implemented any learning algorithms from scratch, I’ll give you three good reasons to follow along and start now:"
},
{
"code": null,
"e": 947,
"s": 589,
"text": "You’ll learn in great detail the special nuances within each model growing your understanding deeply.You’ll level up your coding skills by documenting code and creating test cases ensuring all functionality works as expected.You’ll develop a better understanding of object-oriented programming allowing you to improve your machine learning project workflow."
},
{
"code": null,
"e": 1049,
"s": 947,
"text": "You’ll learn in great detail the special nuances within each model growing your understanding deeply."
},
{
"code": null,
"e": 1174,
"s": 1049,
"text": "You’ll level up your coding skills by documenting code and creating test cases ensuring all functionality works as expected."
},
{
"code": null,
"e": 1307,
"s": 1174,
"text": "You’ll develop a better understanding of object-oriented programming allowing you to improve your machine learning project workflow."
},
{
"code": null,
"e": 1343,
"s": 1307,
"text": "To view the Github repo visit here."
},
{
"code": null,
"e": 1472,
"s": 1343,
"text": "This project is meant to increase our understanding of learning algorithms and is not meant for use in actual data science work."
},
{
"code": null,
"e": 1584,
"s": 1472,
"text": "To use the classes and functions for testing purposes create a virtual environment and pip install the project."
},
{
"code": null,
"e": 1619,
"s": 1584,
"text": " $ pip install mlscratch==0.1.0"
},
{
"code": null,
"e": 1747,
"s": 1619,
"text": "To download all source code in a local repository create a virtual environment and run the following commands in your terminal."
},
{
"code": null,
"e": 1848,
"s": 1747,
"text": " $ git clone https://github.com/lukenew2/mlscratch $ cd mlscratch $ python setup.py install"
},
{
"code": null,
"e": 2002,
"s": 1848,
"text": "Logistic Regression is a common regression algorithm used in classification. It estimates the probability that an instance belongs to a particular class."
},
{
"code": null,
"e": 2203,
"s": 2002,
"text": "If the estimated probability is greater than or equal to 50%, the model predicts the instance belongs to the positive class. If the probability is less than 50%, the model predicts the negative class."
},
{
"code": null,
"e": 2459,
"s": 2203,
"text": "Logistic Regression works just like a Linear Regression model. It calculates a weighted sum of the feature array (plus a bias term), but instead of outputting the result directly like a Linear Regression model does, it outputs the logistic of this result."
},
{
"code": null,
"e": 2564,
"s": 2459,
"text": "The logistic — noted σ(*) — is a sigmoid function that transforms its input to a number between 0 and 1."
},
{
"code": null,
"e": 2718,
"s": 2564,
"text": "Once the model has estimated the probability that an instance belongs to the positive class, it simply makes its prediction based on the following rules."
},
{
"code": null,
"e": 2872,
"s": 2718,
"text": "For our implementation from scratch we’ll need to create a sigmoid function that can transform our inputs into probabilities. Let’s see how this is done."
},
{
"code": null,
"e": 3079,
"s": 2872,
"text": "Here we made a class and gave it one method. This special __call__ method let’s our class behave like a function when it is called. We’ll use this property soon when we create our Logistic Regression class."
},
{
"code": null,
"e": 3217,
"s": 3079,
"text": "Now that we know everything about how Logistic Regression estimates probabilities and makes predictions, let’s look at how it is trained."
},
{
"code": null,
"e": 3446,
"s": 3217,
"text": "The objective of training is to find the set of parameters Θ so that the model predicts high probabilities for positive instances and low probabilities for negative instances. This idea is captured by the cost function log loss."
},
{
"code": null,
"e": 3615,
"s": 3446,
"text": "Since we’ll be using Gradient Descent in our implementation, what we need to know is the partial derivatives of the cost function with regard to the model parameters Θ."
},
{
"code": null,
"e": 3863,
"s": 3615,
"text": "This equation is very similar to the cost function partial derivatives of Linear Regression. For each instance it computes the prediction error and multiplies it by the instance’s feature value, and then it computes the average over all instances."
},
{
"code": null,
"e": 4139,
"s": 3863,
"text": "When implementing Logistic Regression with batch gradient descent we don’t want to compute the average over all instances. We want the gradient vector containing all the partial derivatives allowing us to update our parameters in the opposite direction that they’re pointing."
},
{
"code": null,
"e": 4252,
"s": 4139,
"text": "Let’s get into the implementation. Please read the documentation to understand what each piece of code is doing."
},
{
"code": null,
"e": 4414,
"s": 4252,
"text": "There we go! We have a fully functional Logistic Regression model that can perform binary classification. Let’s write a test case to ensure its working properly."
},
{
"code": null,
"e": 4670,
"s": 4414,
"text": "In this test case we use the famous iris dataset and transform it into a binary classification problem, perform a train/test split, do some preprocessing, and then train our Logistic Regression model and test for accuracy greater than 80% on the test set."
},
{
"code": null,
"e": 4893,
"s": 4670,
"text": "Now, If we ever make changes to our code for whatever reason, we’ll always have a test case ensuring our changes didn’t break the model. Trust me, this saves a lot of headaches later on especially when our code base grows."
},
{
"code": null,
"e": 5072,
"s": 4893,
"text": "The Logistic Regression model we implemented only supports binary classification, but can be generalized to allow support for multiple classes. This is called Softmax Regression."
},
{
"code": null,
"e": 5287,
"s": 5072,
"text": "The idea is simple: for each instance, the Softmax Regression model computes a score for each class, then estimates the probability the instance belongs to each class by applying the softmax function to the scores."
},
{
"code": null,
"e": 5305,
"s": 5287,
"text": "In this equation:"
},
{
"code": null,
"e": 5333,
"s": 5305,
"text": "K is the number of classes."
},
{
"code": null,
"e": 5406,
"s": 5333,
"text": "s(x) is a vector containing the scores of each class for the instance x."
},
{
"code": null,
"e": 5545,
"s": 5406,
"text": "Just like the Logistic Regression classifier, the Softmax Regression classifier predicts the class with the highest estimated probability."
},
{
"code": null,
"e": 5914,
"s": 5545,
"text": "Implementing the softmax function from scratch is a little tricky. When you divide exponents that can potentially be very large, you run into the issue of numerical stability. To avoid this, we use a normalization trick. Notice that if we multiply the top and bottom of the fraction by a constant C and push it into the sum, we get the following equivalent expression:"
},
{
"code": null,
"e": 6118,
"s": 5914,
"text": "We are free to choose the value of C, but a common choice is to set log(C) equal to the negative of the max of the instance x. This shifts the values so the highest value is zero. Let’s see this in code:"
},
{
"code": null,
"e": 6262,
"s": 6118,
"text": "Here we added a softmax class to the same module as our sigmoid class using a __call__ method so our class behaves like a function when called."
},
{
"code": null,
"e": 6567,
"s": 6262,
"text": "Now let’s take a look at training the Softmax Regression model and its cost function. The idea is the same as Logistic Regression. We want a model that predicts high probabilities for the target class, and low probabilities for the other classes. This idea is captured by the cost function cross entropy."
},
{
"code": null,
"e": 6585,
"s": 6567,
"text": "In this equation:"
},
{
"code": null,
"e": 6774,
"s": 6585,
"text": "y is the target probability that the instance belongs to the target class. In our case, this value is always equal to 1 or 0, depending on whether the instance belongs to the class or not."
},
{
"code": null,
"e": 6842,
"s": 6774,
"text": "In the case of two classes cross entropy is equivalent to log loss."
},
{
"code": null,
"e": 6983,
"s": 6842,
"text": "Since we will be implementing Softmax Regression using Gradient Descent, we need the gradient vector of this cost function with regard to Θ."
},
{
"code": null,
"e": 7282,
"s": 6983,
"text": "When calculating the gradients, we need our target class (y) to be of the same dimension as our estimated probabilities (p). Our estimated probabilities will be of shape (n_samples, n_classes) because for each instance we’ll have a probability associated with that instance belonging to each class."
},
{
"code": null,
"e": 7438,
"s": 7282,
"text": "For example, if we have three classes labeled 0, 1, and 2 we need to transform our target vector containing ([1, 2, 0]) into an array that looks like this:"
},
{
"code": null,
"e": 7476,
"s": 7438,
"text": "([[0, 1, 0], [0, 0, 1], [1, 0, 0]])"
},
{
"code": null,
"e": 7710,
"s": 7476,
"text": "The first column represents class 0, the second column represents class 1, and the third column represents class 2. You might have noticed that we can accomplish this by One-Hot Encoding our target vector (y). Let’s see this in code:"
},
{
"code": null,
"e": 7882,
"s": 7710,
"text": "Now we have every helper function we need to complete our Softmax Regression model. The code is well documented so please read for explanations of what each part is doing."
},
{
"code": null,
"e": 8049,
"s": 7882,
"text": "And that’s it! We have successfully added Softmax Regression to our machine learning library. Let’s take a quick look at a test case to ensure it is working properly."
},
{
"code": null,
"e": 8297,
"s": 8049,
"text": "We’ll use the iris dataset, but this time try to classify all three classes with at least 85% accuracy. First, we load the dataset, train/test split it, perform standardization, and then train our Softmax Regression model and predict the test set."
},
{
"code": null,
"e": 8409,
"s": 8297,
"text": "We’re finished! Our test case passed. We successfully added Softmax Regression to our machine learning library."
},
{
"code": null,
"e": 8590,
"s": 8409,
"text": "That concludes this part of the ML From Scratch series. We now have a machine learning library containing the most common linear models for regression and classification including:"
},
{
"code": null,
"e": 8608,
"s": 8590,
"text": "Linear Regression"
},
{
"code": null,
"e": 8630,
"s": 8608,
"text": "Polynomial Regression"
},
{
"code": null,
"e": 8636,
"s": 8630,
"text": "Ridge"
},
{
"code": null,
"e": 8642,
"s": 8636,
"text": "Lasso"
},
{
"code": null,
"e": 8654,
"s": 8642,
"text": "Elastic Net"
},
{
"code": null,
"e": 8674,
"s": 8654,
"text": "Logistic Regression"
},
{
"code": null,
"e": 8693,
"s": 8674,
"text": "Softmax Regression"
},
{
"code": null,
"e": 8760,
"s": 8693,
"text": "As always, thanks for reading and feedback is greatly appreciated!"
},
{
"code": null,
"e": 8897,
"s": 8760,
"text": "In the next part of the series we’ll build upon our library and create support vector machines capable of classification and regression."
}
] |
What are the differences between protected and default access specifiers in Java? | The Protected access specifier is visible within the same package and also visible in the subclass whereas the Default is a package level access specifier and it can be visible in the same package.
Protected will acts as public within the same package and acts as private outside the package.
Protected will also act as public outside the package only with respect to subclass objects.
Protected fields or methods cannot be used for classes and Interfaces.
The Fields, methods, and constructors declared as protected in a superclass can be accessed only by subclasses in other packages.
The classes in the same package can also access protected fields, methods and constructors as well, even if they are not a subclass of the protected member’s class.
Live Demo
public class ProtectedTest {
// variables that are protected
protected int age = 30;
protected String name = "Adithya";
/**
* This method is declared as protected.
*/
protected String getInfo() {
return name +" is "+ age +" years old.";
}
public static void main(String[] args) {
System.out.println(new ProtectedTest().getInfo());
}
}
Adithya is 30 years old.
Any member of a class mentioned without any access specifier then it is considered that as Default.
The Default will act as public within the same package and acts as private outside the package.
The Default members of any class can be available to anything within the same package and can not be available outside the package under any condition.
The Default restricts the access only to package level, even after extending the class having default data members we cannot able to access.
Live Demo
public class DefaultTest {
// variables that have no access modifier
int age = 25;
String name = "Jai";
/**
* This method is declared with default aacees specifier
*/
String getInfo() {
return name +" is "+ age +" years old.";
}
public static void main(String[] args) {
System.out.println(new DefaultTest().getInfo());
}
}
Jai is 25 years old. | [
{
"code": null,
"e": 1260,
"s": 1062,
"text": "The Protected access specifier is visible within the same package and also visible in the subclass whereas the Default is a package level access specifier and it can be visible in the same package."
},
{
"code": null,
"e": 1355,
"s": 1260,
"text": "Protected will acts as public within the same package and acts as private outside the package."
},
{
"code": null,
"e": 1448,
"s": 1355,
"text": "Protected will also act as public outside the package only with respect to subclass objects."
},
{
"code": null,
"e": 1519,
"s": 1448,
"text": "Protected fields or methods cannot be used for classes and Interfaces."
},
{
"code": null,
"e": 1649,
"s": 1519,
"text": "The Fields, methods, and constructors declared as protected in a superclass can be accessed only by subclasses in other packages."
},
{
"code": null,
"e": 1814,
"s": 1649,
"text": "The classes in the same package can also access protected fields, methods and constructors as well, even if they are not a subclass of the protected member’s class."
},
{
"code": null,
"e": 1824,
"s": 1814,
"text": "Live Demo"
},
{
"code": null,
"e": 2204,
"s": 1824,
"text": "public class ProtectedTest {\n // variables that are protected\n protected int age = 30;\n protected String name = \"Adithya\";\n\n /**\n * This method is declared as protected.\n */\n protected String getInfo() {\n return name +\" is \"+ age +\" years old.\";\n }\n public static void main(String[] args) {\n System.out.println(new ProtectedTest().getInfo());\n }\n}"
},
{
"code": null,
"e": 2230,
"s": 2204,
"text": "Adithya is 30 years old.\n"
},
{
"code": null,
"e": 2330,
"s": 2230,
"text": "Any member of a class mentioned without any access specifier then it is considered that as Default."
},
{
"code": null,
"e": 2426,
"s": 2330,
"text": "The Default will act as public within the same package and acts as private outside the package."
},
{
"code": null,
"e": 2578,
"s": 2426,
"text": "The Default members of any class can be available to anything within the same package and can not be available outside the package under any condition."
},
{
"code": null,
"e": 2719,
"s": 2578,
"text": "The Default restricts the access only to package level, even after extending the class having default data members we cannot able to access."
},
{
"code": null,
"e": 2729,
"s": 2719,
"text": "Live Demo"
},
{
"code": null,
"e": 3097,
"s": 2729,
"text": "public class DefaultTest {\n // variables that have no access modifier\n int age = 25;\n String name = \"Jai\";\n\n /**\n * This method is declared with default aacees specifier\n */\n String getInfo() {\n return name +\" is \"+ age +\" years old.\";\n }\n public static void main(String[] args) {\n System.out.println(new DefaultTest().getInfo());\n }\n}"
},
{
"code": null,
"e": 3119,
"s": 3097,
"text": "Jai is 25 years old.\n"
}
] |
Difference between Static and Dynamic Testing - GeeksforGeeks | 27 Feb, 2020
Static Testing:Static Testing is a type of a Software Testing method which is performed to check the defects in software without actually executing the code of the software application.
Static testing is performed in early stage of development to avoid errors as it is easier to find sources of failures and it can be fixed easily. The errors that can’t not be found using Dynamic Testing, can be easily found by Static Testing.
Dynamic Testing:Dynamic Testing is a type of Software Testing which is performed to analyze the dynamic behavior of the code. It includes the testing of the software for the input values and output values that are analyzed.
Difference between Static Testing and Dynamic Testing:
Verification
Validation
ashushrma378
Software Testing
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional vs Non Functional Requirements
Software Engineering | Classical Waterfall Model
Software Requirement Specification (SRS) Format
Differences between Verification and Validation
Software Engineering | Requirements Engineering Process
Levels in Data Flow Diagrams (DFD)
Software Engineering | Requirements Elicitation
DFD for Library Management System
Software Engineering | SDLC V-Model
What is DFD(Data Flow Diagram)? | [
{
"code": null,
"e": 24627,
"s": 24599,
"text": "\n27 Feb, 2020"
},
{
"code": null,
"e": 24813,
"s": 24627,
"text": "Static Testing:Static Testing is a type of a Software Testing method which is performed to check the defects in software without actually executing the code of the software application."
},
{
"code": null,
"e": 25056,
"s": 24813,
"text": "Static testing is performed in early stage of development to avoid errors as it is easier to find sources of failures and it can be fixed easily. The errors that can’t not be found using Dynamic Testing, can be easily found by Static Testing."
},
{
"code": null,
"e": 25280,
"s": 25056,
"text": "Dynamic Testing:Dynamic Testing is a type of Software Testing which is performed to analyze the dynamic behavior of the code. It includes the testing of the software for the input values and output values that are analyzed."
},
{
"code": null,
"e": 25335,
"s": 25280,
"text": "Difference between Static Testing and Dynamic Testing:"
},
{
"code": null,
"e": 25348,
"s": 25335,
"text": "Verification"
},
{
"code": null,
"e": 25359,
"s": 25348,
"text": "Validation"
},
{
"code": null,
"e": 25372,
"s": 25359,
"text": "ashushrma378"
},
{
"code": null,
"e": 25389,
"s": 25372,
"text": "Software Testing"
},
{
"code": null,
"e": 25410,
"s": 25389,
"text": "Software Engineering"
},
{
"code": null,
"e": 25508,
"s": 25410,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25517,
"s": 25508,
"text": "Comments"
},
{
"code": null,
"e": 25530,
"s": 25517,
"text": "Old Comments"
},
{
"code": null,
"e": 25572,
"s": 25530,
"text": "Functional vs Non Functional Requirements"
},
{
"code": null,
"e": 25621,
"s": 25572,
"text": "Software Engineering | Classical Waterfall Model"
},
{
"code": null,
"e": 25669,
"s": 25621,
"text": "Software Requirement Specification (SRS) Format"
},
{
"code": null,
"e": 25717,
"s": 25669,
"text": "Differences between Verification and Validation"
},
{
"code": null,
"e": 25773,
"s": 25717,
"text": "Software Engineering | Requirements Engineering Process"
},
{
"code": null,
"e": 25808,
"s": 25773,
"text": "Levels in Data Flow Diagrams (DFD)"
},
{
"code": null,
"e": 25856,
"s": 25808,
"text": "Software Engineering | Requirements Elicitation"
},
{
"code": null,
"e": 25890,
"s": 25856,
"text": "DFD for Library Management System"
},
{
"code": null,
"e": 25926,
"s": 25890,
"text": "Software Engineering | SDLC V-Model"
}
] |
DAX Date & Time - TIMEVALUE function | Converts time in text format to time in datetime format.
TIMEVALUE (<time_text>)
time_text
A text string that represents a certain time of the day.
Any date information included in the time_text parameter is ignored.
A date in datetime format.
When the time_text parameter is a text representation of the date and time, DAX TIMEVALUE function uses the locale and date/time settings of the client computer to understand the text value in order to perform the conversion. Most locales use the colon (:) as the time separator, and any input text using colons as time separators will parse correctly.
Review your locale settings to understand your results.
= TIMEVALUE ("14:45:35") returns 12/30/1899 2:45:35 PM.
= TIMEVALUE ("2:35:55") returns 12/30/1899 2:35:55 AM.
53 Lectures
5.5 hours
Abhay Gadiya
24 Lectures
2 hours
Randy Minder
26 Lectures
4.5 hours
Randy Minder
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2058,
"s": 2001,
"text": "Converts time in text format to time in datetime format."
},
{
"code": null,
"e": 2084,
"s": 2058,
"text": "TIMEVALUE (<time_text>) \n"
},
{
"code": null,
"e": 2094,
"s": 2084,
"text": "time_text"
},
{
"code": null,
"e": 2151,
"s": 2094,
"text": "A text string that represents a certain time of the day."
},
{
"code": null,
"e": 2220,
"s": 2151,
"text": "Any date information included in the time_text parameter is ignored."
},
{
"code": null,
"e": 2247,
"s": 2220,
"text": "A date in datetime format."
},
{
"code": null,
"e": 2600,
"s": 2247,
"text": "When the time_text parameter is a text representation of the date and time, DAX TIMEVALUE function uses the locale and date/time settings of the client computer to understand the text value in order to perform the conversion. Most locales use the colon (:) as the time separator, and any input text using colons as time separators will parse correctly."
},
{
"code": null,
"e": 2656,
"s": 2600,
"text": "Review your locale settings to understand your results."
},
{
"code": null,
"e": 2770,
"s": 2656,
"text": "= TIMEVALUE (\"14:45:35\") returns 12/30/1899 2:45:35 PM. \n= TIMEVALUE (\"2:35:55\") returns 12/30/1899 2:35:55 AM. "
},
{
"code": null,
"e": 2805,
"s": 2770,
"text": "\n 53 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 2819,
"s": 2805,
"text": " Abhay Gadiya"
},
{
"code": null,
"e": 2852,
"s": 2819,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2866,
"s": 2852,
"text": " Randy Minder"
},
{
"code": null,
"e": 2901,
"s": 2866,
"text": "\n 26 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 2915,
"s": 2901,
"text": " Randy Minder"
},
{
"code": null,
"e": 2922,
"s": 2915,
"text": " Print"
},
{
"code": null,
"e": 2933,
"s": 2922,
"text": " Add Notes"
}
] |
Python Functions - GeeksforGeeks | 18 Jan, 2021
chr(ord('A'))
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Comments
Old Comments
Must Do Coding Questions for Product Based Companies
How to set background images in ReactJS ?
Microsoft Interview Experience for Internship (Via Engage)
Difference between var, let and const keywords in JavaScript
Array of Objects in C++ with Examples
How to Alter Multiple Columns at Once in SQL Server?
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
C Program to read contents of Whole File
How to Replace Values in a List in Python? | [
{
"code": null,
"e": 27610,
"s": 27582,
"text": "\n18 Jan, 2021"
},
{
"code": null,
"e": 27625,
"s": 27610,
"text": "chr(ord('A'))\n"
},
{
"code": null,
"e": 27723,
"s": 27625,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 27732,
"s": 27723,
"text": "Comments"
},
{
"code": null,
"e": 27745,
"s": 27732,
"text": "Old Comments"
},
{
"code": null,
"e": 27798,
"s": 27745,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 27840,
"s": 27798,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 27899,
"s": 27840,
"text": "Microsoft Interview Experience for Internship (Via Engage)"
},
{
"code": null,
"e": 27960,
"s": 27899,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27998,
"s": 27960,
"text": "Array of Objects in C++ with Examples"
},
{
"code": null,
"e": 28051,
"s": 27998,
"text": "How to Alter Multiple Columns at Once in SQL Server?"
},
{
"code": null,
"e": 28113,
"s": 28051,
"text": "How to Replace Values in Column Based on Condition in Pandas?"
},
{
"code": null,
"e": 28193,
"s": 28113,
"text": "How to Fix: SyntaxError: positional argument follows keyword argument in Python"
},
{
"code": null,
"e": 28234,
"s": 28193,
"text": "C Program to read contents of Whole File"
}
] |
How to load external website into an <iframe> using jQuery? | To load an external HTML into <iframe> using jQuery, use the attr() method. In that set the source for iframe. You can try to run the following code to learn how to locate external HTML −
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#iframe').attr('src', 'https://www.qries.com');
});
</script>
</head>
<body>
<iframe id="iframe" name="myIframe" frameborder="5" width="500" height="300"></iframe>
</body>
</html> | [
{
"code": null,
"e": 1250,
"s": 1062,
"text": "To load an external HTML into <iframe> using jQuery, use the attr() method. In that set the source for iframe. You can try to run the following code to learn how to locate external HTML −"
},
{
"code": null,
"e": 1260,
"s": 1250,
"text": "Live Demo"
},
{
"code": null,
"e": 1606,
"s": 1260,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n<script>\n$(document).ready(function(){\n $('#iframe').attr('src', 'https://www.qries.com');\n});\n</script>\n</head>\n<body>\n\n<iframe id=\"iframe\" name=\"myIframe\" frameborder=\"5\" width=\"500\" height=\"300\"></iframe>\n\n</body>\n</html>"
}
] |
Spring MVC - Generate JSON Example | The following example shows how to generate JSON using the Spring Web MVC Framework. To start with, let us have a working Eclipse IDE in place and consider the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework −
package com.tutorialspoint;
public class User {
private String name;
private int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping(value="{name}", method = RequestMethod.GET)
public @ResponseBody User getUser(@PathVariable String name) {
User user = new User();
user.setName(name);
user.setId(1);
return user;
}
}
<beans xmlns = http://www.springframework.org/schema/beans"
xmlns:context = http://www.springframework.org/schema/context"
xmlns:xsi = http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc = http://www.springframework.org/schema/mvc"
xsi:schemaLocation =
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package = com.tutorialspoint" />
<mvc:annotation-driven />
</beans>
Here, we have created a Simple POJO User and in UserController we have returned the User. Spring automatically handles the JSON conversion based on RequestMapping and Jackson jar present in the classpath.
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your TestWeb.war file in Tomcat's webapps folder.
Now, start the Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try a URL – http://localhost:8080/TestWeb/mahesh and we will see the following screen.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3048,
"s": 2791,
"text": "The following example shows how to generate JSON using the Spring Web MVC Framework. To start with, let us have a working Eclipse IDE in place and consider the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework −"
},
{
"code": null,
"e": 3370,
"s": 3048,
"text": "package com.tutorialspoint;\n\npublic class User {\n private String name;\n private int id;\n public String getName() {\n return name;\n } \n public void setName(String name) {\n this.name = name;\n }\n public int getId() {\n return id;\n } \n public void setId(int id) {\n this.id = id;\n }\t\n}"
},
{
"code": null,
"e": 4000,
"s": 3370,
"text": "package com.tutorialspoint;\n\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.bind.annotation.ResponseBody;\n\n@Controller\n@RequestMapping(\"/user\")\npublic class UserController {\n\t\n @RequestMapping(value=\"{name}\", method = RequestMethod.GET)\n public @ResponseBody User getUser(@PathVariable String name) {\n\n User user = new User();\n\n user.setName(name);\n user.setId(1);\n return user;\n }\n}"
},
{
"code": null,
"e": 4726,
"s": 4000,
"text": "<beans xmlns = http://www.springframework.org/schema/beans\"\n xmlns:context = http://www.springframework.org/schema/context\" \n xmlns:xsi = http://www.w3.org/2001/XMLSchema-instance\"\n xmlns:mvc = http://www.springframework.org/schema/mvc\"\n xsi:schemaLocation = \n http://www.springframework.org/schema/beans \n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\n http://www.springframework.org/schema/context \n http://www.springframework.org/schema/context/spring-context-3.0.xsd\n http://www.springframework.org/schema/mvc\n http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd\">\n <context:component-scan base-package = com.tutorialspoint\" />\n <mvc:annotation-driven />\n</beans>"
},
{
"code": null,
"e": 4931,
"s": 4726,
"text": "Here, we have created a Simple POJO User and in UserController we have returned the User. Spring automatically handles the JSON conversion based on RequestMapping and Jackson jar present in the classpath."
},
{
"code": null,
"e": 5141,
"s": 4931,
"text": "Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your TestWeb.war file in Tomcat's webapps folder."
},
{
"code": null,
"e": 5359,
"s": 5141,
"text": "Now, start the Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try a URL – http://localhost:8080/TestWeb/mahesh and we will see the following screen."
},
{
"code": null,
"e": 5366,
"s": 5359,
"text": " Print"
},
{
"code": null,
"e": 5377,
"s": 5366,
"text": " Add Notes"
}
] |
Java 9 - Quick Guide | JAVA 9 (aka jdk 1.9) is a major release of JAVA programming language development. Its initial version was released on 21 Sep 2017. The main goals of Java 9 release are −
To make JDK and Java Standard Edition platform modular based in the sense that it can be scalled down to small computing devices well.
To make JDK and Java Standard Edition platform modular based in the sense that it can be scalled down to small computing devices well.
To improve the overall security of the JDK and Java Implementations.
To improve the overall security of the JDK and Java Implementations.
To make build process and maintainance of java code libraries and large applications easy for for JAVA SE and EE platforms.
To make build process and maintainance of java code libraries and large applications easy for for JAVA SE and EE platforms.
To design and implement a standard module system for the Java Platform which can be applied on both Platform and JDK easily.
To design and implement a standard module system for the Java Platform which can be applied on both Platform and JDK easily.
There are 90+ enhancements added to Java 8, the most significant ones are mentioned below −
Module − A new kind of Java programing component introduced as module, which is a named, self-describing collection of code and data.
Module − A new kind of Java programing component introduced as module, which is a named, self-describing collection of code and data.
REPL (JShell) − Read-Eval-Print Loop (REPL) capability added to the Java platform.
REPL (JShell) − Read-Eval-Print Loop (REPL) capability added to the Java platform.
HTTP 2 Client − new HTTPClient API supporting websockets and HTTP 2 streams and server push features.
HTTP 2 Client − new HTTPClient API supporting websockets and HTTP 2 streams and server push features.
Improved JavaDocs − Supports HTML5 output generation. Provides a search box to generated API documentation.
Improved JavaDocs − Supports HTML5 output generation. Provides a search box to generated API documentation.
Multirelease JAR − Enhances the JAR format so that multiple, Java release-specific versions of class files can coexist in a single archive.
Multirelease JAR − Enhances the JAR format so that multiple, Java release-specific versions of class files can coexist in a single archive.
Collection Factory Methods − New static factory methods for List, Set, and Map interfaces to create immutable instances of those collections.
Collection Factory Methods − New static factory methods for List, Set, and Map interfaces to create immutable instances of those collections.
Private Interface Methods − Enhanced interfaces with private and private static methods.
Private Interface Methods − Enhanced interfaces with private and private static methods.
Process API Improvements − Improved API to control and manage operating system processes.
Process API Improvements − Improved API to control and manage operating system processes.
Stream API Improvements − Enhanced security and robustness by allowing incoming streams of object-serialization data to be filtered.
Stream API Improvements − Enhanced security and robustness by allowing incoming streams of object-serialization data to be filtered.
Try With Resources improvement − Now final variables can be used as resources in the try-with-resources statement.
Try With Resources improvement − Now final variables can be used as resources in the try-with-resources statement.
Enhanced @Deprecated Annotation − @Deprecated annotation revamped to provide more information about the status and intended disposition of an API.
Enhanced @Deprecated Annotation − @Deprecated annotation revamped to provide more information about the status and intended disposition of an API.
Inner Class Diamond Operator − Allow the diamond operator to be used with anonymous classes if the argument type of the inferred type can be denoted.
Inner Class Diamond Operator − Allow the diamond operator to be used with anonymous classes if the argument type of the inferred type can be denoted.
Optional Class Improvements − New useful methods are added to java.util.Optional class.
Optional Class Improvements − New useful methods are added to java.util.Optional class.
Multiresolution Image API − Supports encapsulation of a set of images with different resolutions into a single multiresolution image.
Multiresolution Image API − Supports encapsulation of a set of images with different resolutions into a single multiresolution image.
CompletableFuture API improvements − The asynchronous mechanisms of the CompletableFuture class can perform an action when the process exits with ProcessHandle.onExit method.
CompletableFuture API improvements − The asynchronous mechanisms of the CompletableFuture class can perform an action when the process exits with ProcessHandle.onExit method.
Lightweight JSON − A lightweight API introduced to consume and generating documents and data streams via json in java 9.
Lightweight JSON − A lightweight API introduced to consume and generating documents and data streams via json in java 9.
Reactive Streams API − A new Reactive Streams API in Java SE 9 has been introduced to support reactive programming in java 9.
Reactive Streams API − A new Reactive Streams API in Java SE 9 has been introduced to support reactive programming in java 9.
If you want to set up your own environment for Java programming language, then this section guides you through the whole process. Please follow the steps given below to set up your Java environment.
Java SE is available for download for free. To download click here, please download a version compatible with your operating system.
Follow the instructions to download Java, and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories.
Assuming you have installed Java in c:\Program Files\java\jdk directory −
Right-click on 'My Computer' and select 'Properties'.
Right-click on 'My Computer' and select 'Properties'.
Click on the 'Environment variables' button under the 'Advanced' tab.
Click on the 'Environment variables' button under the 'Advanced' tab.
Now, edit the 'Path' variable and add the path to the Java executable directory at the end of it. For example, if the path is currently set to C:\Windows\System32, then edit it the following way
Now, edit the 'Path' variable and add the path to the Java executable directory at the end of it. For example, if the path is currently set to C:\Windows\System32, then edit it the following way
C:\Windows\System32;c:\Program Files\java\jdk\bin
Assuming you have installed Java in c:\Program Files\java\jdk directory −
Edit the 'C:\autoexec.bat' file and add the following line at the end −
Edit the 'C:\autoexec.bat' file and add the following line at the end −
SET PATH = %PATH%;C:\Program Files\java\jdk\bin
Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this.
For example, if you use bash as your shell, then you would add the following line at the end of your .bashrc −
export PATH = /path/to/java:$PATH'
To write Java programs, you need a text editor. There are even more sophisticated IDEs available in the market. The most popular ones are briefly described below −
Notepad − On Windows machine, you can use any simple text editor like Notepad (recommended for this tutorial) or WordPad. Notepad++ is also a free text editor which enhanced facilities.
Notepad − On Windows machine, you can use any simple text editor like Notepad (recommended for this tutorial) or WordPad. Notepad++ is also a free text editor which enhanced facilities.
Netbeans − It is a Java IDE that is open-source and free which can be downloaded from https://www.netbeans.org/index.html.
Netbeans − It is a Java IDE that is open-source and free which can be downloaded from https://www.netbeans.org/index.html.
Eclipse − It is also a Java IDE developed by the Eclipse open-source community and can be downloaded from https://www.eclipse.org/.
Eclipse − It is also a Java IDE developed by the Eclipse open-source community and can be downloaded from https://www.eclipse.org/.
IDE or Integrated Development Environment, provides all common tools and facilities to aid in programming, such as source code editor, build tools and debuggers etc.
Java 9, a new kind of programming component called module has been introduced. A module is a self-describing collection of code and data and has a name to identify it.
With the Modules component, following enhancements has been added in Java 9 −
A new optional phase,link time, is introduced. This phase is in-between compile time and run time. During this phase, a set of modules can be assembled and optimized, making a custom runtime image using jlink tool.
A new optional phase,link time, is introduced. This phase is in-between compile time and run time. During this phase, a set of modules can be assembled and optimized, making a custom runtime image using jlink tool.
javac, jlink, and java have additional options to specify module paths, which further locate definitions of modules.
javac, jlink, and java have additional options to specify module paths, which further locate definitions of modules.
JAR format updated as modular JAR, which contains module-info.class file in its root directory.
JAR format updated as modular JAR, which contains module-info.class file in its root directory.
JMOD format introduced, a packaging format (similar to JAR) which can include native code and configuration files.
JMOD format introduced, a packaging format (similar to JAR) which can include native code and configuration files.
Following the steps to create a module say com.tutorialspoint.greetings.
Create a folder C:\>JAVA\src. Now create a folder com.tutorialspoint.greetings which is same as the name of module we're creating.
Create module-info.java in C:\>JAVA\src\com.tutorialspoint.greetings folder with following code.
module-info.java
module com.tutorialspoint.greetings { }
module-info.java is the file which is used to create module. In this step we've created a module named com.tutorialspoint.greetings. By convention this file should reside in the folder whose name is same as module name.
Add the source code in the module. Create Java9Tester.java in C:\>JAVA\src\com.tutorialspoint.greetings\com\tutorialspoint\greetings folder with following code.
Java9Tester.java
package com.tutorialspoint.greetings;
public class Java9Tester {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
By convention, the source code of a module to lie in same directory which is the name of the module.
Create a folder C:\>JAVA\mods. Now create a folder com.tutorialspoint.greetings which is same as the name of module we've created. Now compile the module to mods directory.
C:/ > JAVA > javac -d mods/com.tutorialspoint.greetings
src/com.tutorialspoint.greetings/module-info.java
src/com.tutorialspoint.greetings/com/tutorialspoint/greetings/Java9Tester.java
Let's run the module to see the result. Run the following command.
C:/ > JAVA > java --module-path mods -m com.tutorialspoint.greetings/com.tutorialspoint.greetings.Java9Tester
Here module-path provides the module location as mods and -m signifies the main module.
It will print the following output on console.
Hello World!
REPL stands for Read-Eval-Print Loop. With JShell, java has REPL capability. Using REPL, we can code and test java based logic without compiling using javac and see the result of calculations directly.
Open command prompt and type jshell.
$ jshell
| Welcome to JShell -- Version 9-ea
| For an introduction type: /help intro
jshell>
Type /help once jshell command starts running.
jshell> /help
| Type a Java language expression, statement, or declaration.
| Or type one of the following commands:
| /list [<name or id>|-all|-start]
| list the source you have typed
| /edit <name or id>
| edit a source entry referenced by name or id
| /drop <name or id>
| delete a source entry referenced by name or id
| /save [-all|-history|-start] <file>
| Save snippet source to a file.
| /open <file>
| open a file as source input
| /vars [<name or id>|-all|-start]
| list the declared variables and their values
| /methods [<name or id>|-all|-start]
| list the declared methods and their signatures
| /types [<name or id>|-all|-start]
| list the declared types
| /imports
| list the imported items
Type /imports once jshell command starts running and see the used imports.
jshell> /imports
| import java.io.*
| import java.math.*
| import java.net.*
| import java.nio.file.*
| import java.util.*
| import java.util.concurrent.*
| import java.util.function.*
| import java.util.prefs.*
| import java.util.regex.*
| import java.util.stream.*
jshell>
Try running simple calculations in JShell.
jshell> 3+1
$1 ==> 4
jshell> 13%7
$2 ==> 6
jshell> $2
$2 ==> 6
jshell>
Create a function doubled() to take int and return its doubled value.
jshell> int doubled(int i){ return i*2;}
| created method doubled(int)
jshell> doubled(6)
$3 ==> 12
jshell>
Type /exit.
jshell> /exit
| Goodbye
Java documentation can be generated using javadoc tool. It currently generates documentation in html 4.0 format. In java 9, we can generate documentation in html 5 format by using -html5 option in command line arguments.
Consider the following code in C:/JAVA folder.
/**
* @author MahKumar
* @version 0.1
*/
public class Tester {
/**
* Default method to be run to print
* <p>Hello world</p>
* @param args command line arguments
*/
public static void main(String []args) {
System.out.println("Hello World");
}
}
Now run the javadoc tool of jdk 7 to generate documentation.
C:\JAVA>javadoc -d C:/JAVA Tester.java
Loading source file tester.java...
Constructing Javadoc information...
Standard Doclet version 1.7.0_21
Building tree for all the packages and classes...
Generating C:\JAVA\Tester.html...
Generating C:\JAVA\package-frame.html...
Generating C:\JAVA\package-summary.html...
Generating C:\JAVA\package-tree.html...
Generating C:\JAVA\constant-values.html...
Building index for all the packages and classes...
Generating C:\JAVA\overview-tree.html...
Generating C:\JAVA\index-all.html...
Generating C:\JAVA\deprecated-list.html...
Building index for all classes...
Generating C:\JAVA\allclasses-frame.html...
Generating C:\JAVA\allclasses-noframe.html...
Generating C:\JAVA\index.html...
Generating C:\JAVA\help-doc.html...
It will create the java documentation page in C:/JAVA directory and you will see the following output.
Run the javadoc tool of jdk 9 with -html5 flag to generate new type of documentation.
C:\JAVA> javadoc -d C:/JAVA -html5 Tester.java
Loading source file Tester.java...
Constructing Javadoc information...
Standard Doclet version 9.0.1
Building tree for all the packages and classes...
Generating C:\JAVA\Tester.html...
Generating C:\JAVA\package-frame.html...
Generating C:\JAVA\package-summary.html...
Generating C:\JAVA\package-tree.html...
Generating C:\JAVA\constant-values.html...
Building index for all the packages and classes...
Generating C:\JAVA\overview-tree.html...
Generating C:\JAVA\index-all.html...
Generating C:\JAVA\deprecated-list.html...
Building index for all classes...
Generating C:\JAVA\allclasses-frame.html...
Generating C:\JAVA\allclasses-frame.html...
Generating C:\JAVA\allclasses-noframe.html...
Generating C:\JAVA\allclasses-noframe.html...
Generating C:\JAVA\index.html...
Generating C:\JAVA\help-doc.html...
It will create the updated java documentation page in D:/test directory and you will see the following output.
In java 9, a new feature is introduced where a jar format has been enhanced to have different versions of java class or resources can be maintained and used as per the platform. In JAR, a file MANIFEST.MF file has a entry Multi-Release: true in its main section. META-INF directory also contains a versions subdirectory whose subdirectories (starting with 9 for Java 9 ) store version-specific classes and resource files.
In this example, we'll be using a multi-release jar to have two versions of Tester.java file, one for jdk 7 and one for jdk 9 and run it on different jdk versions.
Step 1 − Create a folder c:/test/java7/com/tutorialspoint. Create Test.java with following content −
package com.tutorialspoint;
public class Tester {
public static void main(String[] args) {
System.out.println("Inside java 7");
}
}
Step 2 − Create a folder c:/test/java9/com/tutorialspoint. Create Test.java with following content −
package com.tutorialspoint;
public class Tester {
public static void main(String[] args) {
System.out.println("Inside java 9");
}
}
Compile the source codes.
C:\test > javac --release 9 java9/com/tutorialspoint/Tester.java
C:\JAVA > javac --release 7 java7/com/tutorialspoint/Tester.java
Create the multi-release jar
C:\JAVA > jar -c -f test.jar -C java7 . --release 9 -C java9.
Warning: entry META-INF/versions/9/com/tutorialspoint/Tester.java,
multiple resources with same name
Run with JDK 7
C:\JAVA > java -cp test.jar com.tutorialspoint.Tester
Inside Java 7
Run with JDK 9
C:\JAVA > java -cp test.jar com.tutorialspoint.Tester
Inside Java 9
With Java 9, new factory methods are added to List, Set and Map interfaces to create immutable instances. These factory methods are convenience factory methods to create a collection in less verbose and in concise way.
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Tester {
public static void main(String []args) {
Set<String> set = new HashSet<>();
set.add("A");
set.add("B");
set.add("C");
set = Collections.unmodifiableSet(set);
System.out.println(set);
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
list = Collections.unmodifiableList(list);
System.out.println(list);
Map<String, String> map = new HashMap<>();
map.put("A","Apple");
map.put("B","Boy");
map.put("C","Cat");
map = Collections.unmodifiableMap(map);
System.out.println(map);
}
}
It will print the following output.
[A, B, C]
[A, B, C]
{A=Apple, B=Boy, C=Cat}
With java 9, following methods are added to List, Set and Map interfaces along with their overloaded counterparts.
static <E> List<E> of(E e1, E e2, E e3);
static <E> Set<E> of(E e1, E e2, E e3);
static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3);
static <K,V> Map<K,V> ofEntries(Map.Entry<? extends K,? extends V>... entries)
For List and Set interfaces, of(...) method is overloaded to have 0 to 10 parameters and one with var args parameter.
For List and Set interfaces, of(...) method is overloaded to have 0 to 10 parameters and one with var args parameter.
For Map interface, of(...) method is overloaded to have 0 to 10 parameters.
For Map interface, of(...) method is overloaded to have 0 to 10 parameters.
In case of more than 10 paramters for Map interface, ofEntries(...) method can be used accepting var args parameter.
In case of more than 10 paramters for Map interface, ofEntries(...) method can be used accepting var args parameter.
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.AbstractMap;
import java.util.Map;
import java.util.Set;
public class Tester {
public static void main(String []args) {
Set<String> set = Set.of("A", "B", "C");
System.out.println(set);
List<String> list = List.of("A", "B", "C");
System.out.println(list);
Map<String, String> map = Map.of("A","Apple","B","Boy","C","Cat");
System.out.println(map);
Map<String, String> map1 = Map.ofEntries (
new AbstractMap.SimpleEntry<>("A","Apple"),
new AbstractMap.SimpleEntry<>("B","Boy"),
new AbstractMap.SimpleEntry<>("C","Cat"));
System.out.println(map1);
}
}
It will print the following output.
[A, B, C]
[A, B, C]
{A=Apple, B=Boy, C=Cat}
{A=Apple, B=Boy, C=Cat}
Prior to java 8, interfaces can have following type of variables/methods.
Constant variables
Abstract methods
So we cannot have method implementation in interfaces or more precisely a default implementation prior to Java 8. See the example.
public class Tester {
public static void main(String []args) {
LogOracle log = new LogOracle();
log.logInfo("");
log.logWarn("");
log.logError("");
log.logFatal("");
LogMySql log1 = new LogMySql();
log1.logInfo("");
log1.logWarn("");
log1.logError("");
log1.logFatal("");
}
}
final class LogOracle implements Logging {
@Override
public void logInfo(String message) {
getConnection();
System.out.println("Log Message : " + "INFO");
closeConnection();
}
@Override
public void logWarn(String message) {
getConnection();
System.out.println("Log Message : " + "WARN");
closeConnection();
}
@Override
public void logError(String message) {
getConnection();
System.out.println("Log Message : " + "ERROR");
closeConnection();
}
@Override
public void logFatal(String message) {
getConnection();
System.out.println("Log Message : " + "FATAL");
closeConnection();
}
@Override
public void getConnection() {
System.out.println("Open Database connection");
}
@Override
public void closeConnection() {
System.out.println("Close Database connection");
}
}
final class LogMySql implements Logging {
@Override
public void logInfo(String message) {
getConnection();
System.out.println("Log Message : " + "INFO");
closeConnection();
}
@Override
public void logWarn(String message) {
getConnection();
System.out.println("Log Message : " + "WARN");
closeConnection();
}
@Override
public void logError(String message) {
getConnection();
System.out.println("Log Message : " + "ERROR");
closeConnection();
}
@Override
public void logFatal(String message) {
getConnection();
System.out.println("Log Message : " + "FATAL");
closeConnection();
}
@Override
public void getConnection() {
System.out.println("Open Database connection");
}
@Override
public void closeConnection() {
System.out.println("Close Database connection");
}
}
interface Logging {
String ORACLE = "Oracle_Database";
String MYSQL = "MySql_Database";
void logInfo(String message);
void logWarn(String message);
void logError(String message);
void logFatal(String message);
void getConnection();
void closeConnection();
}
You will see the following output.
Open Database connection
Log Message : INFO
Close Database connection
Open Database connection
Log Message : WARN
Close Database connection
Open Database connection
Log Message : ERROR
Close Database connection
Open Database connection
Log Message : FATAL
Close Database connection
In above example, each log method has its own implementation. With Java 8 interfaces can have following type of variables/methods.
Constant variables
Abstract methods
Default methods
Static methods
Let's have default implementation and static methods in interface itself using Java 8.
public class Tester {
public static void main(String []args) {
LogOracle log = new LogOracle();
log.logInfo("");
log.logWarn("");
log.logError("");
log.logFatal("");
LogMySql log1 = new LogMySql();
log1.logInfo("");
log1.logWarn("");
log1.logError("");
log1.logFatal("");
}
}
final class LogOracle implements Logging {
}
final class LogMySql implements Logging {
}
interface Logging {
String ORACLE = "Oracle_Database";
String MYSQL = "MySql_Database";
default void logInfo(String message) {
getConnection();
System.out.println("Log Message : " + "INFO");
closeConnection();
}
default void logWarn(String message) {
getConnection();
System.out.println("Log Message : " + "WARN");
closeConnection();
}
default void logError(String message) {
getConnection();
System.out.println("Log Message : " + "ERROR");
closeConnection();
}
default void logFatal(String message) {
getConnection();
System.out.println("Log Message : " + "FATAL");
closeConnection();
}
static void getConnection() {
System.out.println("Open Database connection");
}
static void closeConnection() {
System.out.println("Close Database connection");
}
}
You will see the following output.
Open Database connection
Log Message : INFO
Close Database connection
Open Database connection
Log Message : WARN
Close Database connection
Open Database connection
Log Message : ERROR
Close Database connection
Open Database connection
Log Message : FATAL
Close Database connection
In above example, we're having repeation again. With Java 9 interfaces can have following type of variables/methods.
Constant variables
Abstract methods
Default methods
Static methods
Private methods
Private Static methods
Let's have private methods and use them in Java 9.
public class Tester {
public static void main(String []args) {
LogOracle log = new LogOracle();
log.logInfo("");
log.logWarn("");
log.logError("");
log.logFatal("");
LogMySql log1 = new LogMySql();
log1.logInfo("");
log1.logWarn("");
log1.logError("");
log1.logFatal("");
}
}
final class LogOracle implements Logging {
}
final class LogMySql implements Logging {
}
interface Logging {
String ORACLE = "Oracle_Database";
String MYSQL = "MySql_Database";
private void log(String message, String prefix) {
getConnection();
System.out.println("Log Message : " + prefix);
closeConnection();
}
default void logInfo(String message) {
log(message, "INFO");
}
default void logWarn(String message) {
log(message, "WARN");
}
default void logError(String message) {
log(message, "ERROR");
}
default void logFatal(String message) {
log(message, "FATAL");
}
private static void getConnection() {
System.out.println("Open Database connection");
}
private static void closeConnection() {
System.out.println("Close Database connection");
}
}
You will see the following output.
Open Database connection
Log Message : INFO
Close Database connection
Open Database connection
Log Message : WARN
Close Database connection
Open Database connection
Log Message : ERROR
Close Database connection
Open Database connection
Log Message : FATAL
Close Database connection
In Java 9 Process API which is responsible to control and manage operating system processes has been improved considerably. ProcessHandle Class now provides process's native process ID, start time, accumulated CPU time, arguments, command, user, parent process, and descendants. ProcessHandle class also provides method to check processes' liveness and to destroy processes. It has onExit method, the CompletableFuture class can perform action asynchronously when process exits.
import java.time.ZoneId;
import java.util.stream.Stream;
import java.util.stream.Collectors;
import java.io.IOException;
public class Tester {
public static void main(String[] args) throws IOException {
ProcessBuilder pb = new ProcessBuilder("notepad.exe");
String np = "Not Present";
Process p = pb.start();
ProcessHandle.Info info = p.info();
System.out.printf("Process ID : %s%n", p.pid());
System.out.printf("Command name : %s%n", info.command().orElse(np));
System.out.printf("Command line : %s%n", info.commandLine().orElse(np));
System.out.printf("Start time: %s%n",
info.startInstant().map(i -> i.atZone(ZoneId.systemDefault())
.toLocalDateTime().toString()).orElse(np));
System.out.printf("Arguments : %s%n",
info.arguments().map(a -> Stream.of(a).collect(
Collectors.joining(" "))).orElse(np));
System.out.printf("User : %s%n", info.user().orElse(np));
}
}
You will see the following output.
Process ID : 5800
Command name : C:\Windows\System32\notepad.exe
Command line : Not Present
Start time: 2017-11-04T21:35:03.626
Arguments : Not Present
User: administrator
Streams were introduced in Java to help developers perform aggregate operations from a sequence of objects. With Java 9, few more methods are added to make streams better.
default Stream<T> takeWhile(Predicate<? super T> predicate)
takeWhile method takes all the values until the predicate returns false. It returns, in case of ordered stream, a stream consisting of the longest prefix of elements taken from this stream matching the given predicate.
import java.util.stream.Stream;
public class Tester {
public static void main(String[] args) {
Stream.of("a","b","c","","e","f").takeWhile(s->!s.isEmpty())
.forEach(System.out::print);
}
}
takeWhile method takes all a, b, and c values, then once string is empty, it stopped executing.
abc
default Stream<T> dropWhile(Predicate<? super T> predicate)
dropWhile method throw away all the values at the start until the predicate returns true. It returns, in case of ordered stream, a stream consisting of the remaining elements of this stream after dropping the longest prefix of elements matching the given predicate.
import java.util.stream.Stream;
public class Tester {
public static void main(String[] args) {
Stream.of("a","b","c","","e","f").dropWhile(s-> !s.isEmpty())
.forEach(System.out::print);
System.out.println();
Stream.of("a","b","c","","e","","f").dropWhile(s-> !s.isEmpty())
.forEach(System.out::print);
}
}
dropWhile method drops a,b and c values, then once string is empty, it takes all the values.
ef
ef
static <T> Stream<T> iterate(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next)
iterate method now has hasNext predicate as parameter which stops the loop once hasNext predicate returns false.
import java.util.stream.IntStream;
public class Tester {
public static void main(String[] args) {
IntStream.iterate(3, x -> x < 10, x -> x+ 3).forEach(System.out::println);
}
}
3
6
9
static <T> Stream<T> ofNullable(T t)
ofNullable method is introduced to prevent NullPointerExceptions and to avoid null checks for streams. This method returns a sequential Stream containing single element, if non-null, otherwise returns an empty Stream.
import java.util.stream.Stream;
public class Tester {
public static void main(String[] args) {
long count = Stream.ofNullable(100).count();
System.out.println(count);
count = Stream.ofNullable(null).count();
System.out.println(count);
}
}
1
0
The try-with-resources statement is a try statement with one or more resources duly declared. Here resource is an object which should be closed once it is no more required. The try-with-resources statement ensures that each resource is closed after the requirement finishes. Any object implementing java.lang.AutoCloseable or java.io.Closeable, interface can be used as a resource.
Prior to Java 9, resources are to be declared before try or inside try statement as shown below in given example. In this example, we'll use BufferedReader as resource to read a string and then BufferedReader is to be closed.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
public class Tester {
public static void main(String[] args) throws IOException {
System.out.println(readData("test"));
}
static String readData(String message) throws IOException {
Reader inputString = new StringReader(message);
BufferedReader br = new BufferedReader(inputString);
try (BufferedReader br1 = br) {
return br1.readLine();
}
}
}
test
Here we need to declare a resource br1 within try statment and then use it. In Java9, we don't need to declare br1 anymore and following program will give the same result.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
public class Tester {
public static void main(String[] args) throws IOException {
System.out.println(readData("test"));
}
static String readData(String message) throws IOException {
Reader inputString = new StringReader(message);
BufferedReader br = new BufferedReader(inputString);
try (br) {
return br.readLine();
}
}
}
test
@Deprecated annotation was introduced in java 5 version. A program element annotated with @Deprecated means it should not be used for any of the following reasons −
Its usage may leads to errors.
It may be incompatible in future version.
It may be removed in future version.
A better and efficient alternative has superseeded it.
Compiler generates warnings whenever a deprecated element is used. With Java 9, two new enhancements are made to @Deprecated annotation.
forRemoval − Indicates whether the annotated element is subject to removal in a future version. The default value is false.
forRemoval − Indicates whether the annotated element is subject to removal in a future version. The default value is false.
since − Returns the version in which the annotated element became deprecated. The default value is the empty string.
since − Returns the version in which the annotated element became deprecated. The default value is the empty string.
Following example of Boolean class javadoc on Java 9 illustrate the use of since attribute on @Deprecated annotation.
Boolean Class
Following example of System class javadoc on Java 9 illustrate the use of forRemoval attribute on @Deprecated annotation.
System Class
Diamond operator was introduced in java 7 to make code more readable but it could not be used with Anonymous inner classes. In java 9, it can be used with annonymous class as well to simplify code and improves readability. Consider the following code prior to Java 9.
public class Tester {
public static void main(String[] args) {
Handler<Integer> intHandler = new Handler<Integer>(1) {
@Override
public void handle() {
System.out.println(content);
}
};
intHandler.handle();
Handler<? extends Number> intHandler1 = new Handler<Number>(2) {
@Override
public void handle() {
System.out.println(content);
}
};
intHandler1.handle();
Handler<?> handler = new Handler<Object>("test") {
@Override
public void handle() {
System.out.println(content);
}
};
handler.handle();
}
}
abstract class Handler<T> {
public T content;
public Handler(T content) {
this.content = content;
}
abstract void handle();
}
1
2
Test
With Java 9, we can use <> operator with anonymous class as well as shown below.
public class Tester {
public static void main(String[] args) {
Handler<Integer> intHandler = new Handler<>(1) {
@Override
public void handle() {
System.out.println(content);
}
};
intHandler.handle();
Handler<? extends Number> intHandler1 = new Handler<>(2) {
@Override
public void handle() {
System.out.println(content);
}
};
intHandler1.handle();
Handler<?> handler = new Handler<>("test") {
@Override
public void handle() {
System.out.println(content);
}
};
handler.handle();
}
}
abstract class Handler<T> {
public T content;
public Handler(T content) {
this.content = content;
}
abstract void handle();
}
1
2
Test
Optional Class was introduced in Java 8 to avoid null checks and NullPointerException issues. In java 9, three new methods are added to improve its functionality.
stream()
ifPresentOrElse()
or()
public Stream<T> stream()
If a value is present, it returns a sequential Stream containing only that value, otherwise returns an empty Stream.
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Tester {
public static void main(String[] args) {
List<Optional<String>> list = Arrays.asList (
Optional.empty(),
Optional.of("A"),
Optional.empty(),
Optional.of("B"));
//filter the list based to print non-empty values
//if optional is non-empty, get the value in stream, otherwise return empty
List<String> filteredList = list.stream()
.flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())
.collect(Collectors.toList());
//Optional::stream method will return a stream of either one
//or zero element if data is present or not.
List<String> filteredListJava9 = list.stream()
.flatMap(Optional::stream)
.collect(Collectors.toList());
System.out.println(filteredList);
System.out.println(filteredListJava9);
}
}
[A, B]
[A, B]
public void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction)
If a value is present, performs the given action with the value, otherwise performs the given empty-based action.
import java.util.Optional;
public class Tester {
public static void main(String[] args) {
Optional<Integer> optional = Optional.of(1);
optional.ifPresentOrElse( x -> System.out.println("Value: " + x),() ->
System.out.println("Not Present."));
optional = Optional.empty();
optional.ifPresentOrElse( x -> System.out.println("Value: " + x),() ->
System.out.println("Not Present."));
}
}
Value: 1
Not Present.
public Optional<T> or(Supplier<? extends Optional<? extends T>> supplier)
If a value is present, returns an Optional describing the value, otherwise returns an Optional produced by the supplying function.
import java.util.Optional;
import java.util.function.Supplier;
public class Tester {
public static void main(String[] args) {
Optional<String> optional1 = Optional.of("Mahesh");
Supplier<Optional<String>> supplierString = () -> Optional.of("Not Present");
optional1 = optional1.or( supplierString);
optional1.ifPresent( x -> System.out.println("Value: " + x));
optional1 = Optional.empty();
optional1 = optional1.or( supplierString);
optional1.ifPresent( x -> System.out.println("Value: " + x));
}
}
Value: Mahesh
Value: Not Present
With Java 9, a new multi-resolution image API has been introduced which supports multiple images with different resolution variants. This API allows a set of images with different resolution to be used as a single multi-resolution image. Following are major operations of multi-resolution image.
Image getResolutionVariant(double destImageWidth, double destImageHeight) − Gets a specific image which is best variant to represent this logical image at the indicated size.
Image getResolutionVariant(double destImageWidth, double destImageHeight) − Gets a specific image which is best variant to represent this logical image at the indicated size.
List<Image> getResolutionVariants() − Gets a readable list of all resolution variants.
List<Image> getResolutionVariants() − Gets a readable list of all resolution variants.
import java.io.IOException;
import java.net.URL;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import java.awt.Image;
import java.awt.image.MultiResolutionImage;
import java.awt.image.BaseMultiResolutionImage;
import javax.imageio.ImageIO;
public class Tester {
public static void main(String[] args) throws IOException, MalformedURLException {
List<String> imgUrls = List.of("http://www.tutorialspoint.com/java9/images/logo.png",
"http://www.tutorialspoint.com/java9/images/mini_logo.png",
"http://www.tutorialspoint.com/java9/images/large_logo.png");
List<Image> images = new ArrayList<Image>();
for (String url : imgUrls) {
images.add(ImageIO.read(new URL(url)));
}
// read all images into one multiresolution image
MultiResolutionImage multiResolutionImage =
new BaseMultiResolutionImage(images.toArray(new Image[0]));
// get all variants of images
List<Image> variants = multiResolutionImage.getResolutionVariants();
System.out.println("Total number of images: " + variants.size());
for (Image img : variants) {
System.out.println(img);
}
// get a resolution-specific image variant for each indicated size
Image variant1 = multiResolutionImage.getResolutionVariant(156, 45);
System.out.printf("\nImage for destination[%d,%d]: [%d,%d]",
156, 45, variant1.getWidth(null), variant1.getHeight(null));
Image variant2 = multiResolutionImage.getResolutionVariant(311, 89);
System.out.printf("\nImage for destination[%d,%d]: [%d,%d]", 311, 89,
variant2.getWidth(null), variant2.getHeight(null));
Image variant3 = multiResolutionImage.getResolutionVariant(622, 178);
System.out.printf("\nImage for destination[%d,%d]: [%d,%d]", 622, 178,
variant3.getWidth(null), variant3.getHeight(null));
Image variant4 = multiResolutionImage.getResolutionVariant(300, 300);
System.out.printf("\nImage for destination[%d,%d]: [%d,%d]", 300, 300,
variant4.getWidth(null), variant4.getHeight(null));
}
}
Total number of images: 3
BufferedImage@7ce6a65d: type = 6 ColorModel: #pixelBits = 32 numComponents = 4
color space =java.awt.color.ICC_ColorSpace@548ad73b transparency = 3
has alpha = true isAlphaPre = false ByteInterleavedRaster: width =311
height = 89 #numDataElements 4 dataOff[0] = 3
BufferedImage@4c762604: type = 6 ColorModel: #pixelBits = 32 numComponents = 4
color space =java.awt.color.ICC_ColorSpace@548ad73b transparency = 3
has alpha = true isAlphaPre = false ByteInterleavedRaster: width =156
height = 45 #numDataElements 4 dataOff[0] = 3
BufferedImage@2641e737: type = 6 ColorModel: #pixelBits = 32 numComponents = 4
color space =java.awt.color.ICC_ColorSpace@548ad73b transparency = 3
has alpha = true isAlphaPre = false ByteInterleavedRaster: width =622
height = 178 #numDataElements 4 dataOff[0] = 3
Image for destination[156,45]: [311,89]
Image for destination[311,89]: [311,89]
Image for destination[622,178]: [622,178]
Image for destination[300,300]: [622,178]
CompletableFuture class was introduced in Java 8 to represent the Future which can be completed by setting its value and status explicity. It can be used as java.util.concurrent.CompletionStage. It supports dependent functions and actions which got triggered upon the future's completion. In java 9 CompletableFuture API has been enhanced further. Following are the relevant changes done to the API.
Support for delays and timeouts.
Improved support for subclassing.
New factory methods added.
public CompletableFuture<T> completeOnTimeout(T value, long timeout, TimeUnit unit)
This method completes this CompletableFuture with the given value if not otherwise completed before the given timeout.
public CompletableFuture<T> orTimeout(long timeout, TimeUnit unit)
This method exceptionally completes this CompletableFuture with a TimeoutException if not otherwise completed before the given timeout.
public Executor defaultExecutor()
It returns the default Executor used for async methods that do not specify an Executor. This method may be overridden in subclasses to return an Executor to provide one independent thread as minimum.
public <U> CompletableFuture<U> newIncompleteFuture()
Returns a new incomplete CompletableFuture of the type to be returned by a CompletionStage method. Subclasses of CompletableFuture class should override this method to return an instance of the same class as this CompletableFuture. The default implementation returns an instance of class CompletableFuture.
public static <U> CompletableFuture<U> completedFuture(U value)
This factory method returns a new CompletableFuture which is already completed with the given value.
public static <U> CompletionStage<U> completedStage(U value)
This factory method returns a new CompletionStage which is already completed with the given value and supports only those methods present in interface CompletionStage.
public static <U> CompletionStage<U> failedStage(Throwable ex)
This factory method returns a new CompletionStage which is already completed exceptionally with the given exception and supports only those methods present in interface CompletionStage.
Apart from mentioned features, with Java 9, a lot more enhancements are done to JDK platform. Some of them are listed below.
GC (Garbage Collector) Improvements
Stack-Walking API
Filter Incoming Serialization Data
Deprecate the Applet API
Indify String Concatenation
Enhanced Method Handles
Java Platform Logging API and Service
Compact Strings
Parser API for Nashorn
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2279,
"s": 2109,
"text": "JAVA 9 (aka jdk 1.9) is a major release of JAVA programming language development. Its initial version was released on 21 Sep 2017. The main goals of Java 9 release are −"
},
{
"code": null,
"e": 2414,
"s": 2279,
"text": "To make JDK and Java Standard Edition platform modular based in the sense that it can be scalled down to small computing devices well."
},
{
"code": null,
"e": 2549,
"s": 2414,
"text": "To make JDK and Java Standard Edition platform modular based in the sense that it can be scalled down to small computing devices well."
},
{
"code": null,
"e": 2618,
"s": 2549,
"text": "To improve the overall security of the JDK and Java Implementations."
},
{
"code": null,
"e": 2687,
"s": 2618,
"text": "To improve the overall security of the JDK and Java Implementations."
},
{
"code": null,
"e": 2811,
"s": 2687,
"text": "To make build process and maintainance of java code libraries and large applications easy for for JAVA SE and EE platforms."
},
{
"code": null,
"e": 2935,
"s": 2811,
"text": "To make build process and maintainance of java code libraries and large applications easy for for JAVA SE and EE platforms."
},
{
"code": null,
"e": 3060,
"s": 2935,
"text": "To design and implement a standard module system for the Java Platform which can be applied on both Platform and JDK easily."
},
{
"code": null,
"e": 3185,
"s": 3060,
"text": "To design and implement a standard module system for the Java Platform which can be applied on both Platform and JDK easily."
},
{
"code": null,
"e": 3277,
"s": 3185,
"text": "There are 90+ enhancements added to Java 8, the most significant ones are mentioned below −"
},
{
"code": null,
"e": 3411,
"s": 3277,
"text": "Module − A new kind of Java programing component introduced as module, which is a named, self-describing collection of code and data."
},
{
"code": null,
"e": 3545,
"s": 3411,
"text": "Module − A new kind of Java programing component introduced as module, which is a named, self-describing collection of code and data."
},
{
"code": null,
"e": 3628,
"s": 3545,
"text": "REPL (JShell) − Read-Eval-Print Loop (REPL) capability added to the Java platform."
},
{
"code": null,
"e": 3711,
"s": 3628,
"text": "REPL (JShell) − Read-Eval-Print Loop (REPL) capability added to the Java platform."
},
{
"code": null,
"e": 3813,
"s": 3711,
"text": "HTTP 2 Client − new HTTPClient API supporting websockets and HTTP 2 streams and server push features."
},
{
"code": null,
"e": 3915,
"s": 3813,
"text": "HTTP 2 Client − new HTTPClient API supporting websockets and HTTP 2 streams and server push features."
},
{
"code": null,
"e": 4023,
"s": 3915,
"text": "Improved JavaDocs − Supports HTML5 output generation. Provides a search box to generated API documentation."
},
{
"code": null,
"e": 4131,
"s": 4023,
"text": "Improved JavaDocs − Supports HTML5 output generation. Provides a search box to generated API documentation."
},
{
"code": null,
"e": 4271,
"s": 4131,
"text": "Multirelease JAR − Enhances the JAR format so that multiple, Java release-specific versions of class files can coexist in a single archive."
},
{
"code": null,
"e": 4411,
"s": 4271,
"text": "Multirelease JAR − Enhances the JAR format so that multiple, Java release-specific versions of class files can coexist in a single archive."
},
{
"code": null,
"e": 4553,
"s": 4411,
"text": "Collection Factory Methods − New static factory methods for List, Set, and Map interfaces to create immutable instances of those collections."
},
{
"code": null,
"e": 4695,
"s": 4553,
"text": "Collection Factory Methods − New static factory methods for List, Set, and Map interfaces to create immutable instances of those collections."
},
{
"code": null,
"e": 4784,
"s": 4695,
"text": "Private Interface Methods − Enhanced interfaces with private and private static methods."
},
{
"code": null,
"e": 4873,
"s": 4784,
"text": "Private Interface Methods − Enhanced interfaces with private and private static methods."
},
{
"code": null,
"e": 4963,
"s": 4873,
"text": "Process API Improvements − Improved API to control and manage operating system processes."
},
{
"code": null,
"e": 5053,
"s": 4963,
"text": "Process API Improvements − Improved API to control and manage operating system processes."
},
{
"code": null,
"e": 5186,
"s": 5053,
"text": "Stream API Improvements − Enhanced security and robustness by allowing incoming streams of object-serialization data to be filtered."
},
{
"code": null,
"e": 5319,
"s": 5186,
"text": "Stream API Improvements − Enhanced security and robustness by allowing incoming streams of object-serialization data to be filtered."
},
{
"code": null,
"e": 5434,
"s": 5319,
"text": "Try With Resources improvement − Now final variables can be used as resources in the try-with-resources statement."
},
{
"code": null,
"e": 5549,
"s": 5434,
"text": "Try With Resources improvement − Now final variables can be used as resources in the try-with-resources statement."
},
{
"code": null,
"e": 5696,
"s": 5549,
"text": "Enhanced @Deprecated Annotation − @Deprecated annotation revamped to provide more information about the status and intended disposition of an API."
},
{
"code": null,
"e": 5843,
"s": 5696,
"text": "Enhanced @Deprecated Annotation − @Deprecated annotation revamped to provide more information about the status and intended disposition of an API."
},
{
"code": null,
"e": 5993,
"s": 5843,
"text": "Inner Class Diamond Operator − Allow the diamond operator to be used with anonymous classes if the argument type of the inferred type can be denoted."
},
{
"code": null,
"e": 6143,
"s": 5993,
"text": "Inner Class Diamond Operator − Allow the diamond operator to be used with anonymous classes if the argument type of the inferred type can be denoted."
},
{
"code": null,
"e": 6231,
"s": 6143,
"text": "Optional Class Improvements − New useful methods are added to java.util.Optional class."
},
{
"code": null,
"e": 6319,
"s": 6231,
"text": "Optional Class Improvements − New useful methods are added to java.util.Optional class."
},
{
"code": null,
"e": 6453,
"s": 6319,
"text": "Multiresolution Image API − Supports encapsulation of a set of images with different resolutions into a single multiresolution image."
},
{
"code": null,
"e": 6587,
"s": 6453,
"text": "Multiresolution Image API − Supports encapsulation of a set of images with different resolutions into a single multiresolution image."
},
{
"code": null,
"e": 6762,
"s": 6587,
"text": "CompletableFuture API improvements − The asynchronous mechanisms of the CompletableFuture class can perform an action when the process exits with ProcessHandle.onExit method."
},
{
"code": null,
"e": 6937,
"s": 6762,
"text": "CompletableFuture API improvements − The asynchronous mechanisms of the CompletableFuture class can perform an action when the process exits with ProcessHandle.onExit method."
},
{
"code": null,
"e": 7058,
"s": 6937,
"text": "Lightweight JSON − A lightweight API introduced to consume and generating documents and data streams via json in java 9."
},
{
"code": null,
"e": 7179,
"s": 7058,
"text": "Lightweight JSON − A lightweight API introduced to consume and generating documents and data streams via json in java 9."
},
{
"code": null,
"e": 7305,
"s": 7179,
"text": "Reactive Streams API − A new Reactive Streams API in Java SE 9 has been introduced to support reactive programming in java 9."
},
{
"code": null,
"e": 7431,
"s": 7305,
"text": "Reactive Streams API − A new Reactive Streams API in Java SE 9 has been introduced to support reactive programming in java 9."
},
{
"code": null,
"e": 7630,
"s": 7431,
"text": "If you want to set up your own environment for Java programming language, then this section guides you through the whole process. Please follow the steps given below to set up your Java environment."
},
{
"code": null,
"e": 7764,
"s": 7630,
"text": "Java SE is available for download for free. To download click here, please download a version compatible with your operating system."
},
{
"code": null,
"e": 7992,
"s": 7764,
"text": "Follow the instructions to download Java, and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories."
},
{
"code": null,
"e": 8066,
"s": 7992,
"text": "Assuming you have installed Java in c:\\Program Files\\java\\jdk directory −"
},
{
"code": null,
"e": 8120,
"s": 8066,
"text": "Right-click on 'My Computer' and select 'Properties'."
},
{
"code": null,
"e": 8174,
"s": 8120,
"text": "Right-click on 'My Computer' and select 'Properties'."
},
{
"code": null,
"e": 8244,
"s": 8174,
"text": "Click on the 'Environment variables' button under the 'Advanced' tab."
},
{
"code": null,
"e": 8314,
"s": 8244,
"text": "Click on the 'Environment variables' button under the 'Advanced' tab."
},
{
"code": null,
"e": 8509,
"s": 8314,
"text": "Now, edit the 'Path' variable and add the path to the Java executable directory at the end of it. For example, if the path is currently set to C:\\Windows\\System32, then edit it the following way"
},
{
"code": null,
"e": 8704,
"s": 8509,
"text": "Now, edit the 'Path' variable and add the path to the Java executable directory at the end of it. For example, if the path is currently set to C:\\Windows\\System32, then edit it the following way"
},
{
"code": null,
"e": 8755,
"s": 8704,
"text": "C:\\Windows\\System32;c:\\Program Files\\java\\jdk\\bin\n"
},
{
"code": null,
"e": 8829,
"s": 8755,
"text": "Assuming you have installed Java in c:\\Program Files\\java\\jdk directory −"
},
{
"code": null,
"e": 8901,
"s": 8829,
"text": "Edit the 'C:\\autoexec.bat' file and add the following line at the end −"
},
{
"code": null,
"e": 8973,
"s": 8901,
"text": "Edit the 'C:\\autoexec.bat' file and add the following line at the end −"
},
{
"code": null,
"e": 9022,
"s": 8973,
"text": "SET PATH = %PATH%;C:\\Program Files\\java\\jdk\\bin\n"
},
{
"code": null,
"e": 9185,
"s": 9022,
"text": "Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this."
},
{
"code": null,
"e": 9296,
"s": 9185,
"text": "For example, if you use bash as your shell, then you would add the following line at the end of your .bashrc −"
},
{
"code": null,
"e": 9332,
"s": 9296,
"text": "export PATH = /path/to/java:$PATH'\n"
},
{
"code": null,
"e": 9496,
"s": 9332,
"text": "To write Java programs, you need a text editor. There are even more sophisticated IDEs available in the market. The most popular ones are briefly described below −"
},
{
"code": null,
"e": 9682,
"s": 9496,
"text": "Notepad − On Windows machine, you can use any simple text editor like Notepad (recommended for this tutorial) or WordPad. Notepad++ is also a free text editor which enhanced facilities."
},
{
"code": null,
"e": 9868,
"s": 9682,
"text": "Notepad − On Windows machine, you can use any simple text editor like Notepad (recommended for this tutorial) or WordPad. Notepad++ is also a free text editor which enhanced facilities."
},
{
"code": null,
"e": 9991,
"s": 9868,
"text": "Netbeans − It is a Java IDE that is open-source and free which can be downloaded from https://www.netbeans.org/index.html."
},
{
"code": null,
"e": 10114,
"s": 9991,
"text": "Netbeans − It is a Java IDE that is open-source and free which can be downloaded from https://www.netbeans.org/index.html."
},
{
"code": null,
"e": 10246,
"s": 10114,
"text": "Eclipse − It is also a Java IDE developed by the Eclipse open-source community and can be downloaded from https://www.eclipse.org/."
},
{
"code": null,
"e": 10378,
"s": 10246,
"text": "Eclipse − It is also a Java IDE developed by the Eclipse open-source community and can be downloaded from https://www.eclipse.org/."
},
{
"code": null,
"e": 10544,
"s": 10378,
"text": "IDE or Integrated Development Environment, provides all common tools and facilities to aid in programming, such as source code editor, build tools and debuggers etc."
},
{
"code": null,
"e": 10712,
"s": 10544,
"text": "Java 9, a new kind of programming component called module has been introduced. A module is a self-describing collection of code and data and has a name to identify it."
},
{
"code": null,
"e": 10790,
"s": 10712,
"text": "With the Modules component, following enhancements has been added in Java 9 −"
},
{
"code": null,
"e": 11005,
"s": 10790,
"text": "A new optional phase,link time, is introduced. This phase is in-between compile time and run time. During this phase, a set of modules can be assembled and optimized, making a custom runtime image using jlink tool."
},
{
"code": null,
"e": 11220,
"s": 11005,
"text": "A new optional phase,link time, is introduced. This phase is in-between compile time and run time. During this phase, a set of modules can be assembled and optimized, making a custom runtime image using jlink tool."
},
{
"code": null,
"e": 11337,
"s": 11220,
"text": "javac, jlink, and java have additional options to specify module paths, which further locate definitions of modules."
},
{
"code": null,
"e": 11454,
"s": 11337,
"text": "javac, jlink, and java have additional options to specify module paths, which further locate definitions of modules."
},
{
"code": null,
"e": 11550,
"s": 11454,
"text": "JAR format updated as modular JAR, which contains module-info.class file in its root directory."
},
{
"code": null,
"e": 11646,
"s": 11550,
"text": "JAR format updated as modular JAR, which contains module-info.class file in its root directory."
},
{
"code": null,
"e": 11761,
"s": 11646,
"text": "JMOD format introduced, a packaging format (similar to JAR) which can include native code and configuration files."
},
{
"code": null,
"e": 11876,
"s": 11761,
"text": "JMOD format introduced, a packaging format (similar to JAR) which can include native code and configuration files."
},
{
"code": null,
"e": 11949,
"s": 11876,
"text": "Following the steps to create a module say com.tutorialspoint.greetings."
},
{
"code": null,
"e": 12080,
"s": 11949,
"text": "Create a folder C:\\>JAVA\\src. Now create a folder com.tutorialspoint.greetings which is same as the name of module we're creating."
},
{
"code": null,
"e": 12177,
"s": 12080,
"text": "Create module-info.java in C:\\>JAVA\\src\\com.tutorialspoint.greetings folder with following code."
},
{
"code": null,
"e": 12194,
"s": 12177,
"text": "module-info.java"
},
{
"code": null,
"e": 12235,
"s": 12194,
"text": "module com.tutorialspoint.greetings { }\n"
},
{
"code": null,
"e": 12455,
"s": 12235,
"text": "module-info.java is the file which is used to create module. In this step we've created a module named com.tutorialspoint.greetings. By convention this file should reside in the folder whose name is same as module name."
},
{
"code": null,
"e": 12616,
"s": 12455,
"text": "Add the source code in the module. Create Java9Tester.java in C:\\>JAVA\\src\\com.tutorialspoint.greetings\\com\\tutorialspoint\\greetings folder with following code."
},
{
"code": null,
"e": 12633,
"s": 12616,
"text": "Java9Tester.java"
},
{
"code": null,
"e": 12792,
"s": 12633,
"text": "package com.tutorialspoint.greetings;\n\npublic class Java9Tester {\n public static void main(String[] args) {\n System.out.println(\"Hello World!\");\n }\n}"
},
{
"code": null,
"e": 12893,
"s": 12792,
"text": "By convention, the source code of a module to lie in same directory which is the name of the module."
},
{
"code": null,
"e": 13066,
"s": 12893,
"text": "Create a folder C:\\>JAVA\\mods. Now create a folder com.tutorialspoint.greetings which is same as the name of module we've created. Now compile the module to mods directory."
},
{
"code": null,
"e": 13260,
"s": 13066,
"text": "C:/ > JAVA > javac -d mods/com.tutorialspoint.greetings \n src/com.tutorialspoint.greetings/module-info.java \n src/com.tutorialspoint.greetings/com/tutorialspoint/greetings/Java9Tester.java\n"
},
{
"code": null,
"e": 13327,
"s": 13260,
"text": "Let's run the module to see the result. Run the following command."
},
{
"code": null,
"e": 13438,
"s": 13327,
"text": "C:/ > JAVA > java --module-path mods -m com.tutorialspoint.greetings/com.tutorialspoint.greetings.Java9Tester\n"
},
{
"code": null,
"e": 13526,
"s": 13438,
"text": "Here module-path provides the module location as mods and -m signifies the main module."
},
{
"code": null,
"e": 13573,
"s": 13526,
"text": "It will print the following output on console."
},
{
"code": null,
"e": 13587,
"s": 13573,
"text": "Hello World!\n"
},
{
"code": null,
"e": 13789,
"s": 13587,
"text": "REPL stands for Read-Eval-Print Loop. With JShell, java has REPL capability. Using REPL, we can code and test java based logic without compiling using javac and see the result of calculations directly."
},
{
"code": null,
"e": 13826,
"s": 13789,
"text": "Open command prompt and type jshell."
},
{
"code": null,
"e": 13922,
"s": 13826,
"text": "$ jshell\n| Welcome to JShell -- Version 9-ea\n| For an introduction type: /help intro\njshell>\n"
},
{
"code": null,
"e": 13969,
"s": 13922,
"text": "Type /help once jshell command starts running."
},
{
"code": null,
"e": 14698,
"s": 13969,
"text": "jshell> /help\n| Type a Java language expression, statement, or declaration.\n| Or type one of the following commands:\n| /list [<name or id>|-all|-start]\n| list the source you have typed\n| /edit <name or id>\n| edit a source entry referenced by name or id\n| /drop <name or id>\n| delete a source entry referenced by name or id\n| /save [-all|-history|-start] <file>\n| Save snippet source to a file.\n| /open <file>\n| open a file as source input\n| /vars [<name or id>|-all|-start]\n| list the declared variables and their values\n| /methods [<name or id>|-all|-start]\n| list the declared methods and their signatures\n| /types [<name or id>|-all|-start]\n| list the declared types\n| /imports \n| list the imported items\n"
},
{
"code": null,
"e": 14773,
"s": 14698,
"text": "Type /imports once jshell command starts running and see the used imports."
},
{
"code": null,
"e": 15079,
"s": 14773,
"text": "jshell> /imports\n| import java.io.*\n| import java.math.*\n| import java.net.*\n| import java.nio.file.*\n| import java.util.*\n| import java.util.concurrent.*\n| import java.util.function.*\n| import java.util.prefs.*\n| import java.util.regex.*\n| import java.util.stream.*\njshell>\n"
},
{
"code": null,
"e": 15123,
"s": 15079,
"text": " Try running simple calculations in JShell."
},
{
"code": null,
"e": 15195,
"s": 15123,
"text": "jshell> 3+1\n$1 ==> 4\njshell> 13%7\n$2 ==> 6\njshell> $2\n$2 ==> 6\njshell>\n"
},
{
"code": null,
"e": 15265,
"s": 15195,
"text": "Create a function doubled() to take int and return its doubled value."
},
{
"code": null,
"e": 15375,
"s": 15265,
"text": "jshell> int doubled(int i){ return i*2;}\n| created method doubled(int)\njshell> doubled(6)\n$3 ==> 12\njshell>\n"
},
{
"code": null,
"e": 15387,
"s": 15375,
"text": "Type /exit."
},
{
"code": null,
"e": 15412,
"s": 15387,
"text": "jshell> /exit\n| Goodbye\n"
},
{
"code": null,
"e": 15633,
"s": 15412,
"text": "Java documentation can be generated using javadoc tool. It currently generates documentation in html 4.0 format. In java 9, we can generate documentation in html 5 format by using -html5 option in command line arguments."
},
{
"code": null,
"e": 15680,
"s": 15633,
"text": "Consider the following code in C:/JAVA folder."
},
{
"code": null,
"e": 15955,
"s": 15680,
"text": "/**\n * @author MahKumar\n * @version 0.1\n */\npublic class Tester {\n /**\n * Default method to be run to print \n * <p>Hello world</p>\n * @param args command line arguments\n */\n public static void main(String []args) {\n System.out.println(\"Hello World\");\n }\n}"
},
{
"code": null,
"e": 16016,
"s": 15955,
"text": "Now run the javadoc tool of jdk 7 to generate documentation."
},
{
"code": null,
"e": 16776,
"s": 16016,
"text": "C:\\JAVA>javadoc -d C:/JAVA Tester.java\nLoading source file tester.java...\nConstructing Javadoc information...\nStandard Doclet version 1.7.0_21\nBuilding tree for all the packages and classes...\nGenerating C:\\JAVA\\Tester.html...\nGenerating C:\\JAVA\\package-frame.html...\nGenerating C:\\JAVA\\package-summary.html...\nGenerating C:\\JAVA\\package-tree.html...\nGenerating C:\\JAVA\\constant-values.html...\nBuilding index for all the packages and classes...\nGenerating C:\\JAVA\\overview-tree.html...\nGenerating C:\\JAVA\\index-all.html...\nGenerating C:\\JAVA\\deprecated-list.html...\nBuilding index for all classes...\nGenerating C:\\JAVA\\allclasses-frame.html...\nGenerating C:\\JAVA\\allclasses-noframe.html...\nGenerating C:\\JAVA\\index.html...\nGenerating C:\\JAVA\\help-doc.html...\n"
},
{
"code": null,
"e": 16879,
"s": 16776,
"text": "It will create the java documentation page in C:/JAVA directory and you will see the following output."
},
{
"code": null,
"e": 16965,
"s": 16879,
"text": "Run the javadoc tool of jdk 9 with -html5 flag to generate new type of documentation."
},
{
"code": null,
"e": 17820,
"s": 16965,
"text": "C:\\JAVA> javadoc -d C:/JAVA -html5 Tester.java\nLoading source file Tester.java...\nConstructing Javadoc information...\nStandard Doclet version 9.0.1\nBuilding tree for all the packages and classes...\nGenerating C:\\JAVA\\Tester.html...\nGenerating C:\\JAVA\\package-frame.html...\nGenerating C:\\JAVA\\package-summary.html...\nGenerating C:\\JAVA\\package-tree.html...\nGenerating C:\\JAVA\\constant-values.html...\nBuilding index for all the packages and classes...\nGenerating C:\\JAVA\\overview-tree.html...\nGenerating C:\\JAVA\\index-all.html...\nGenerating C:\\JAVA\\deprecated-list.html...\nBuilding index for all classes...\nGenerating C:\\JAVA\\allclasses-frame.html...\nGenerating C:\\JAVA\\allclasses-frame.html...\nGenerating C:\\JAVA\\allclasses-noframe.html...\nGenerating C:\\JAVA\\allclasses-noframe.html...\nGenerating C:\\JAVA\\index.html...\nGenerating C:\\JAVA\\help-doc.html...\n"
},
{
"code": null,
"e": 17931,
"s": 17820,
"text": "It will create the updated java documentation page in D:/test directory and you will see the following output."
},
{
"code": null,
"e": 18353,
"s": 17931,
"text": "In java 9, a new feature is introduced where a jar format has been enhanced to have different versions of java class or resources can be maintained and used as per the platform. In JAR, a file MANIFEST.MF file has a entry Multi-Release: true in its main section. META-INF directory also contains a versions subdirectory whose subdirectories (starting with 9 for Java 9 ) store version-specific classes and resource files."
},
{
"code": null,
"e": 18517,
"s": 18353,
"text": "In this example, we'll be using a multi-release jar to have two versions of Tester.java file, one for jdk 7 and one for jdk 9 and run it on different jdk versions."
},
{
"code": null,
"e": 18618,
"s": 18517,
"text": "Step 1 − Create a folder c:/test/java7/com/tutorialspoint. Create Test.java with following content −"
},
{
"code": null,
"e": 18763,
"s": 18618,
"text": "package com.tutorialspoint;\n\npublic class Tester {\n public static void main(String[] args) {\n System.out.println(\"Inside java 7\");\n }\n}"
},
{
"code": null,
"e": 18864,
"s": 18763,
"text": "Step 2 − Create a folder c:/test/java9/com/tutorialspoint. Create Test.java with following content −"
},
{
"code": null,
"e": 19009,
"s": 18864,
"text": "package com.tutorialspoint;\n\npublic class Tester {\n public static void main(String[] args) {\n System.out.println(\"Inside java 9\");\n }\n}"
},
{
"code": null,
"e": 19035,
"s": 19009,
"text": "Compile the source codes."
},
{
"code": null,
"e": 19167,
"s": 19035,
"text": "C:\\test > javac --release 9 java9/com/tutorialspoint/Tester.java\n\nC:\\JAVA > javac --release 7 java7/com/tutorialspoint/Tester.java\n"
},
{
"code": null,
"e": 19196,
"s": 19167,
"text": "Create the multi-release jar"
},
{
"code": null,
"e": 19364,
"s": 19196,
"text": "C:\\JAVA > jar -c -f test.jar -C java7 . --release 9 -C java9.\nWarning: entry META-INF/versions/9/com/tutorialspoint/Tester.java, \n multiple resources with same name\n"
},
{
"code": null,
"e": 19379,
"s": 19364,
"text": "Run with JDK 7"
},
{
"code": null,
"e": 19448,
"s": 19379,
"text": "C:\\JAVA > java -cp test.jar com.tutorialspoint.Tester\nInside Java 7\n"
},
{
"code": null,
"e": 19463,
"s": 19448,
"text": "Run with JDK 9"
},
{
"code": null,
"e": 19532,
"s": 19463,
"text": "C:\\JAVA > java -cp test.jar com.tutorialspoint.Tester\nInside Java 9\n"
},
{
"code": null,
"e": 19751,
"s": 19532,
"text": "With Java 9, new factory methods are added to List, Set and Map interfaces to create immutable instances. These factory methods are convenience factory methods to create a collection in less verbose and in concise way."
},
{
"code": null,
"e": 20578,
"s": 19751,
"text": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class Tester {\n\n public static void main(String []args) {\n Set<String> set = new HashSet<>();\n set.add(\"A\");\n set.add(\"B\");\n set.add(\"C\");\n set = Collections.unmodifiableSet(set);\n System.out.println(set);\n List<String> list = new ArrayList<>();\n\n list.add(\"A\");\n list.add(\"B\");\n list.add(\"C\");\n list = Collections.unmodifiableList(list);\n System.out.println(list);\n Map<String, String> map = new HashMap<>();\n\n map.put(\"A\",\"Apple\");\n map.put(\"B\",\"Boy\");\n map.put(\"C\",\"Cat\");\n map = Collections.unmodifiableMap(map);\n System.out.println(map);\n }\n}"
},
{
"code": null,
"e": 20614,
"s": 20578,
"text": "It will print the following output."
},
{
"code": null,
"e": 20659,
"s": 20614,
"text": "[A, B, C]\n[A, B, C]\n{A=Apple, B=Boy, C=Cat}\n"
},
{
"code": null,
"e": 20774,
"s": 20659,
"text": "With java 9, following methods are added to List, Set and Map interfaces along with their overloaded counterparts."
},
{
"code": null,
"e": 20997,
"s": 20774,
"text": "static <E> List<E> of(E e1, E e2, E e3);\nstatic <E> Set<E> of(E e1, E e2, E e3);\nstatic <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3);\nstatic <K,V> Map<K,V> ofEntries(Map.Entry<? extends K,? extends V>... entries)"
},
{
"code": null,
"e": 21115,
"s": 20997,
"text": "For List and Set interfaces, of(...) method is overloaded to have 0 to 10 parameters and one with var args parameter."
},
{
"code": null,
"e": 21233,
"s": 21115,
"text": "For List and Set interfaces, of(...) method is overloaded to have 0 to 10 parameters and one with var args parameter."
},
{
"code": null,
"e": 21309,
"s": 21233,
"text": "For Map interface, of(...) method is overloaded to have 0 to 10 parameters."
},
{
"code": null,
"e": 21385,
"s": 21309,
"text": "For Map interface, of(...) method is overloaded to have 0 to 10 parameters."
},
{
"code": null,
"e": 21502,
"s": 21385,
"text": "In case of more than 10 paramters for Map interface, ofEntries(...) method can be used accepting var args parameter."
},
{
"code": null,
"e": 21619,
"s": 21502,
"text": "In case of more than 10 paramters for Map interface, ofEntries(...) method can be used accepting var args parameter."
},
{
"code": null,
"e": 22411,
"s": 21619,
"text": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.AbstractMap;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class Tester {\n\n public static void main(String []args) {\n Set<String> set = Set.of(\"A\", \"B\", \"C\"); \n System.out.println(set);\n List<String> list = List.of(\"A\", \"B\", \"C\");\n System.out.println(list);\n Map<String, String> map = Map.of(\"A\",\"Apple\",\"B\",\"Boy\",\"C\",\"Cat\");\n System.out.println(map);\n \n Map<String, String> map1 = Map.ofEntries (\n new AbstractMap.SimpleEntry<>(\"A\",\"Apple\"),\n new AbstractMap.SimpleEntry<>(\"B\",\"Boy\"),\n new AbstractMap.SimpleEntry<>(\"C\",\"Cat\"));\n System.out.println(map1);\n }\n}"
},
{
"code": null,
"e": 22447,
"s": 22411,
"text": "It will print the following output."
},
{
"code": null,
"e": 22516,
"s": 22447,
"text": "[A, B, C]\n[A, B, C]\n{A=Apple, B=Boy, C=Cat}\n{A=Apple, B=Boy, C=Cat}\n"
},
{
"code": null,
"e": 22590,
"s": 22516,
"text": "Prior to java 8, interfaces can have following type of variables/methods."
},
{
"code": null,
"e": 22609,
"s": 22590,
"text": "Constant variables"
},
{
"code": null,
"e": 22626,
"s": 22609,
"text": "Abstract methods"
},
{
"code": null,
"e": 22757,
"s": 22626,
"text": "So we cannot have method implementation in interfaces or more precisely a default implementation prior to Java 8. See the example."
},
{
"code": null,
"e": 25199,
"s": 22757,
"text": "public class Tester {\n public static void main(String []args) {\n LogOracle log = new LogOracle();\n log.logInfo(\"\");\n log.logWarn(\"\");\n log.logError(\"\");\n log.logFatal(\"\");\n LogMySql log1 = new LogMySql();\n log1.logInfo(\"\");\n log1.logWarn(\"\");\n log1.logError(\"\");\n log1.logFatal(\"\");\n }\n}\n\nfinal class LogOracle implements Logging {\n @Override\n public void logInfo(String message) {\n getConnection();\n System.out.println(\"Log Message : \" + \"INFO\");\n closeConnection();\n }\n\n @Override\n public void logWarn(String message) {\n getConnection();\n System.out.println(\"Log Message : \" + \"WARN\");\n closeConnection();\n }\n\n @Override\n public void logError(String message) {\n getConnection();\n System.out.println(\"Log Message : \" + \"ERROR\");\n closeConnection();\n }\n\n @Override\n public void logFatal(String message) {\n getConnection();\n System.out.println(\"Log Message : \" + \"FATAL\");\n closeConnection();\n }\n\n @Override\n public void getConnection() {\n System.out.println(\"Open Database connection\");\n }\n\n @Override\n public void closeConnection() {\n System.out.println(\"Close Database connection\");\n }\n}\n\nfinal class LogMySql implements Logging {\n @Override\n public void logInfo(String message) {\n getConnection();\n System.out.println(\"Log Message : \" + \"INFO\");\n closeConnection();\n }\n\n @Override\n public void logWarn(String message) {\n getConnection();\n System.out.println(\"Log Message : \" + \"WARN\");\n closeConnection();\n }\n\n @Override\n public void logError(String message) {\n getConnection();\n System.out.println(\"Log Message : \" + \"ERROR\");\n closeConnection();\n }\n\n @Override\n public void logFatal(String message) {\n getConnection();\n System.out.println(\"Log Message : \" + \"FATAL\");\n closeConnection();\n }\n\n @Override\n public void getConnection() {\n System.out.println(\"Open Database connection\");\n }\n\n @Override\n public void closeConnection() {\n System.out.println(\"Close Database connection\");\n }\n}\n\ninterface Logging {\n String ORACLE = \"Oracle_Database\";\n String MYSQL = \"MySql_Database\";\n\n void logInfo(String message);\n void logWarn(String message);\n void logError(String message);\n void logFatal(String message);\n\n void getConnection();\n void closeConnection();\n}"
},
{
"code": null,
"e": 25234,
"s": 25199,
"text": "You will see the following output."
},
{
"code": null,
"e": 25517,
"s": 25234,
"text": "Open Database connection\nLog Message : INFO\nClose Database connection\nOpen Database connection\nLog Message : WARN\nClose Database connection\nOpen Database connection\nLog Message : ERROR\nClose Database connection\nOpen Database connection\nLog Message : FATAL\nClose Database connection\n"
},
{
"code": null,
"e": 25648,
"s": 25517,
"text": "In above example, each log method has its own implementation. With Java 8 interfaces can have following type of variables/methods."
},
{
"code": null,
"e": 25667,
"s": 25648,
"text": "Constant variables"
},
{
"code": null,
"e": 25684,
"s": 25667,
"text": "Abstract methods"
},
{
"code": null,
"e": 25700,
"s": 25684,
"text": "Default methods"
},
{
"code": null,
"e": 25715,
"s": 25700,
"text": "Static methods"
},
{
"code": null,
"e": 25802,
"s": 25715,
"text": "Let's have default implementation and static methods in interface itself using Java 8."
},
{
"code": null,
"e": 27131,
"s": 25802,
"text": "public class Tester {\n public static void main(String []args) {\n LogOracle log = new LogOracle();\n log.logInfo(\"\");\n log.logWarn(\"\");\n log.logError(\"\");\n log.logFatal(\"\");\n LogMySql log1 = new LogMySql();\n log1.logInfo(\"\");\n log1.logWarn(\"\");\n log1.logError(\"\");\n log1.logFatal(\"\");\n }\n}\n\nfinal class LogOracle implements Logging { \n}\n\nfinal class LogMySql implements Logging { \n}\n\ninterface Logging {\n String ORACLE = \"Oracle_Database\";\n String MYSQL = \"MySql_Database\";\n\n default void logInfo(String message) {\n getConnection();\n System.out.println(\"Log Message : \" + \"INFO\");\n closeConnection();\n }\n \n default void logWarn(String message) {\n getConnection();\n System.out.println(\"Log Message : \" + \"WARN\");\n closeConnection();\n }\n \n default void logError(String message) {\n getConnection();\n System.out.println(\"Log Message : \" + \"ERROR\");\n closeConnection();\n }\n \n default void logFatal(String message) {\n getConnection();\n System.out.println(\"Log Message : \" + \"FATAL\");\n closeConnection();\n }\n\n static void getConnection() {\n System.out.println(\"Open Database connection\");\n }\n static void closeConnection() {\n System.out.println(\"Close Database connection\");\n }\n}"
},
{
"code": null,
"e": 27166,
"s": 27131,
"text": "You will see the following output."
},
{
"code": null,
"e": 27449,
"s": 27166,
"text": "Open Database connection\nLog Message : INFO\nClose Database connection\nOpen Database connection\nLog Message : WARN\nClose Database connection\nOpen Database connection\nLog Message : ERROR\nClose Database connection\nOpen Database connection\nLog Message : FATAL\nClose Database connection\n"
},
{
"code": null,
"e": 27566,
"s": 27449,
"text": "In above example, we're having repeation again. With Java 9 interfaces can have following type of variables/methods."
},
{
"code": null,
"e": 27585,
"s": 27566,
"text": "Constant variables"
},
{
"code": null,
"e": 27602,
"s": 27585,
"text": "Abstract methods"
},
{
"code": null,
"e": 27618,
"s": 27602,
"text": "Default methods"
},
{
"code": null,
"e": 27633,
"s": 27618,
"text": "Static methods"
},
{
"code": null,
"e": 27649,
"s": 27633,
"text": "Private methods"
},
{
"code": null,
"e": 27672,
"s": 27649,
"text": "Private Static methods"
},
{
"code": null,
"e": 27723,
"s": 27672,
"text": "Let's have private methods and use them in Java 9."
},
{
"code": null,
"e": 28943,
"s": 27723,
"text": "public class Tester {\n public static void main(String []args) {\n LogOracle log = new LogOracle();\n log.logInfo(\"\");\n log.logWarn(\"\");\n log.logError(\"\");\n log.logFatal(\"\");\n LogMySql log1 = new LogMySql();\n log1.logInfo(\"\");\n log1.logWarn(\"\");\n log1.logError(\"\");\n log1.logFatal(\"\");\n }\n}\n\nfinal class LogOracle implements Logging { \n}\n\nfinal class LogMySql implements Logging { \n}\n\ninterface Logging {\n String ORACLE = \"Oracle_Database\";\n String MYSQL = \"MySql_Database\";\n\n private void log(String message, String prefix) {\n getConnection();\n System.out.println(\"Log Message : \" + prefix);\n closeConnection();\n }\n \n default void logInfo(String message) {\n log(message, \"INFO\");\n }\n \n default void logWarn(String message) {\n log(message, \"WARN\");\n }\n \n default void logError(String message) {\n log(message, \"ERROR\");\n }\n \n default void logFatal(String message) {\n log(message, \"FATAL\");\n }\n\n private static void getConnection() {\n System.out.println(\"Open Database connection\");\n }\n \n private static void closeConnection() {\n System.out.println(\"Close Database connection\");\n }\n}"
},
{
"code": null,
"e": 28978,
"s": 28943,
"text": "You will see the following output."
},
{
"code": null,
"e": 29261,
"s": 28978,
"text": "Open Database connection\nLog Message : INFO\nClose Database connection\nOpen Database connection\nLog Message : WARN\nClose Database connection\nOpen Database connection\nLog Message : ERROR\nClose Database connection\nOpen Database connection\nLog Message : FATAL\nClose Database connection\n"
},
{
"code": null,
"e": 29740,
"s": 29261,
"text": "In Java 9 Process API which is responsible to control and manage operating system processes has been improved considerably. ProcessHandle Class now provides process's native process ID, start time, accumulated CPU time, arguments, command, user, parent process, and descendants. ProcessHandle class also provides method to check processes' liveness and to destroy processes. It has onExit method, the CompletableFuture class can perform action asynchronously when process exits."
},
{
"code": null,
"e": 30717,
"s": 29740,
"text": "import java.time.ZoneId;\nimport java.util.stream.Stream;\nimport java.util.stream.Collectors;\nimport java.io.IOException;\n\npublic class Tester {\n public static void main(String[] args) throws IOException {\n ProcessBuilder pb = new ProcessBuilder(\"notepad.exe\");\n String np = \"Not Present\";\n Process p = pb.start();\n ProcessHandle.Info info = p.info();\n System.out.printf(\"Process ID : %s%n\", p.pid());\n System.out.printf(\"Command name : %s%n\", info.command().orElse(np));\n System.out.printf(\"Command line : %s%n\", info.commandLine().orElse(np));\n\n System.out.printf(\"Start time: %s%n\",\n info.startInstant().map(i -> i.atZone(ZoneId.systemDefault())\n .toLocalDateTime().toString()).orElse(np));\n\n System.out.printf(\"Arguments : %s%n\",\n info.arguments().map(a -> Stream.of(a).collect(\n Collectors.joining(\" \"))).orElse(np));\n\n System.out.printf(\"User : %s%n\", info.user().orElse(np));\n } \n}"
},
{
"code": null,
"e": 30752,
"s": 30717,
"text": "You will see the following output."
},
{
"code": null,
"e": 30925,
"s": 30752,
"text": "Process ID : 5800\nCommand name : C:\\Windows\\System32\\notepad.exe\nCommand line : Not Present\nStart time: 2017-11-04T21:35:03.626\nArguments : Not Present\nUser: administrator\n"
},
{
"code": null,
"e": 31097,
"s": 30925,
"text": "Streams were introduced in Java to help developers perform aggregate operations from a sequence of objects. With Java 9, few more methods are added to make streams better."
},
{
"code": null,
"e": 31157,
"s": 31097,
"text": "default Stream<T> takeWhile(Predicate<? super T> predicate)"
},
{
"code": null,
"e": 31376,
"s": 31157,
"text": "takeWhile method takes all the values until the predicate returns false. It returns, in case of ordered stream, a stream consisting of the longest prefix of elements taken from this stream matching the given predicate."
},
{
"code": null,
"e": 31591,
"s": 31376,
"text": "import java.util.stream.Stream;\n\npublic class Tester {\n public static void main(String[] args) {\n Stream.of(\"a\",\"b\",\"c\",\"\",\"e\",\"f\").takeWhile(s->!s.isEmpty())\n .forEach(System.out::print);\t\t \n } \n}"
},
{
"code": null,
"e": 31687,
"s": 31591,
"text": "takeWhile method takes all a, b, and c values, then once string is empty, it stopped executing."
},
{
"code": null,
"e": 31692,
"s": 31687,
"text": "abc\n"
},
{
"code": null,
"e": 31753,
"s": 31692,
"text": "default Stream<T> dropWhile(Predicate<? super T> predicate)\n"
},
{
"code": null,
"e": 32019,
"s": 31753,
"text": "dropWhile method throw away all the values at the start until the predicate returns true. It returns, in case of ordered stream, a stream consisting of the remaining elements of this stream after dropping the longest prefix of elements matching the given predicate."
},
{
"code": null,
"e": 32363,
"s": 32019,
"text": "import java.util.stream.Stream;\n\npublic class Tester {\n public static void main(String[] args) {\n Stream.of(\"a\",\"b\",\"c\",\"\",\"e\",\"f\").dropWhile(s-> !s.isEmpty())\n .forEach(System.out::print);\n System.out.println();\n Stream.of(\"a\",\"b\",\"c\",\"\",\"e\",\"\",\"f\").dropWhile(s-> !s.isEmpty())\n .forEach(System.out::print);\n } \n}"
},
{
"code": null,
"e": 32456,
"s": 32363,
"text": "dropWhile method drops a,b and c values, then once string is empty, it takes all the values."
},
{
"code": null,
"e": 32463,
"s": 32456,
"text": "ef\nef\n"
},
{
"code": null,
"e": 32553,
"s": 32463,
"text": "static <T> Stream<T> iterate(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next)"
},
{
"code": null,
"e": 32666,
"s": 32553,
"text": "iterate method now has hasNext predicate as parameter which stops the loop once hasNext predicate returns false."
},
{
"code": null,
"e": 32857,
"s": 32666,
"text": "import java.util.stream.IntStream;\n\npublic class Tester {\n public static void main(String[] args) {\n IntStream.iterate(3, x -> x < 10, x -> x+ 3).forEach(System.out::println);\n } \n}"
},
{
"code": null,
"e": 32864,
"s": 32857,
"text": "3\n6\n9\n"
},
{
"code": null,
"e": 32901,
"s": 32864,
"text": "static <T> Stream<T> ofNullable(T t)"
},
{
"code": null,
"e": 33119,
"s": 32901,
"text": "ofNullable method is introduced to prevent NullPointerExceptions and to avoid null checks for streams. This method returns a sequential Stream containing single element, if non-null, otherwise returns an empty Stream."
},
{
"code": null,
"e": 33393,
"s": 33119,
"text": "import java.util.stream.Stream;\n\npublic class Tester {\n public static void main(String[] args) {\n long count = Stream.ofNullable(100).count();\n System.out.println(count);\n \n count = Stream.ofNullable(null).count();\n System.out.println(count);\n } \n}"
},
{
"code": null,
"e": 33398,
"s": 33393,
"text": "1\n0\n"
},
{
"code": null,
"e": 33780,
"s": 33398,
"text": "The try-with-resources statement is a try statement with one or more resources duly declared. Here resource is an object which should be closed once it is no more required. The try-with-resources statement ensures that each resource is closed after the requirement finishes. Any object implementing java.lang.AutoCloseable or java.io.Closeable, interface can be used as a resource."
},
{
"code": null,
"e": 34006,
"s": 33780,
"text": "Prior to Java 9, resources are to be declared before try or inside try statement as shown below in given example. In this example, we'll use BufferedReader as resource to read a string and then BufferedReader is to be closed."
},
{
"code": null,
"e": 34515,
"s": 34006,
"text": "import java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.Reader;\nimport java.io.StringReader;\n\npublic class Tester {\n public static void main(String[] args) throws IOException {\n System.out.println(readData(\"test\"));\n } \n\n static String readData(String message) throws IOException {\n Reader inputString = new StringReader(message);\n BufferedReader br = new BufferedReader(inputString);\n try (BufferedReader br1 = br) {\n return br1.readLine();\n }\n }\n}"
},
{
"code": null,
"e": 34521,
"s": 34515,
"text": "test\n"
},
{
"code": null,
"e": 34693,
"s": 34521,
"text": "Here we need to declare a resource br1 within try statment and then use it. In Java9, we don't need to declare br1 anymore and following program will give the same result."
},
{
"code": null,
"e": 35180,
"s": 34693,
"text": "import java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.Reader;\nimport java.io.StringReader;\n\npublic class Tester {\n public static void main(String[] args) throws IOException {\n System.out.println(readData(\"test\"));\n } \n\n static String readData(String message) throws IOException {\n Reader inputString = new StringReader(message);\n BufferedReader br = new BufferedReader(inputString);\n try (br) {\n return br.readLine();\n }\n }\n}"
},
{
"code": null,
"e": 35186,
"s": 35180,
"text": "test\n"
},
{
"code": null,
"e": 35351,
"s": 35186,
"text": "@Deprecated annotation was introduced in java 5 version. A program element annotated with @Deprecated means it should not be used for any of the following reasons −"
},
{
"code": null,
"e": 35382,
"s": 35351,
"text": "Its usage may leads to errors."
},
{
"code": null,
"e": 35424,
"s": 35382,
"text": "It may be incompatible in future version."
},
{
"code": null,
"e": 35461,
"s": 35424,
"text": "It may be removed in future version."
},
{
"code": null,
"e": 35516,
"s": 35461,
"text": "A better and efficient alternative has superseeded it."
},
{
"code": null,
"e": 35653,
"s": 35516,
"text": "Compiler generates warnings whenever a deprecated element is used. With Java 9, two new enhancements are made to @Deprecated annotation."
},
{
"code": null,
"e": 35777,
"s": 35653,
"text": "forRemoval − Indicates whether the annotated element is subject to removal in a future version. The default value is false."
},
{
"code": null,
"e": 35901,
"s": 35777,
"text": "forRemoval − Indicates whether the annotated element is subject to removal in a future version. The default value is false."
},
{
"code": null,
"e": 36019,
"s": 35901,
"text": "since − Returns the version in which the annotated element became deprecated. The default value is the empty string."
},
{
"code": null,
"e": 36137,
"s": 36019,
"text": "since − Returns the version in which the annotated element became deprecated. The default value is the empty string."
},
{
"code": null,
"e": 36255,
"s": 36137,
"text": "Following example of Boolean class javadoc on Java 9 illustrate the use of since attribute on @Deprecated annotation."
},
{
"code": null,
"e": 36269,
"s": 36255,
"text": "Boolean Class"
},
{
"code": null,
"e": 36391,
"s": 36269,
"text": "Following example of System class javadoc on Java 9 illustrate the use of forRemoval attribute on @Deprecated annotation."
},
{
"code": null,
"e": 36404,
"s": 36391,
"text": "System Class"
},
{
"code": null,
"e": 36672,
"s": 36404,
"text": "Diamond operator was introduced in java 7 to make code more readable but it could not be used with Anonymous inner classes. In java 9, it can be used with annonymous class as well to simplify code and improves readability. Consider the following code prior to Java 9."
},
{
"code": null,
"e": 37543,
"s": 36672,
"text": "public class Tester {\n public static void main(String[] args) {\n Handler<Integer> intHandler = new Handler<Integer>(1) {\n \n @Override\n public void handle() {\n System.out.println(content);\n }\n };\n\n intHandler.handle();\n Handler<? extends Number> intHandler1 = new Handler<Number>(2) {\n \n @Override\n public void handle() {\n System.out.println(content);\n }\n };\n\n intHandler1.handle();\n Handler<?> handler = new Handler<Object>(\"test\") {\n \n @Override\n public void handle() {\n System.out.println(content);\n }\n };\n\n handler.handle(); \n } \n}\n\nabstract class Handler<T> {\n public T content;\n\n public Handler(T content) {\n this.content = content; \n }\n \n abstract void handle();\n}"
},
{
"code": null,
"e": 37553,
"s": 37543,
"text": "1\n2\nTest\n"
},
{
"code": null,
"e": 37634,
"s": 37553,
"text": "With Java 9, we can use <> operator with anonymous class as well as shown below."
},
{
"code": null,
"e": 38486,
"s": 37634,
"text": "public class Tester {\n public static void main(String[] args) {\n Handler<Integer> intHandler = new Handler<>(1) {\n \n @Override\n public void handle() {\n System.out.println(content);\n }\n };\n\n intHandler.handle();\n Handler<? extends Number> intHandler1 = new Handler<>(2) {\n \n @Override\n public void handle() {\n System.out.println(content);\n }\n };\n\n intHandler1.handle();\n Handler<?> handler = new Handler<>(\"test\") {\n \n @Override\n public void handle() {\n System.out.println(content);\n }\n };\n\n handler.handle(); \n } \n}\n\nabstract class Handler<T> {\n public T content;\n\n public Handler(T content) {\n this.content = content; \n }\n \n abstract void handle();\n}"
},
{
"code": null,
"e": 38496,
"s": 38486,
"text": "1\n2\nTest\n"
},
{
"code": null,
"e": 38659,
"s": 38496,
"text": "Optional Class was introduced in Java 8 to avoid null checks and NullPointerException issues. In java 9, three new methods are added to improve its functionality."
},
{
"code": null,
"e": 38668,
"s": 38659,
"text": "stream()"
},
{
"code": null,
"e": 38686,
"s": 38668,
"text": "ifPresentOrElse()"
},
{
"code": null,
"e": 38691,
"s": 38686,
"text": "or()"
},
{
"code": null,
"e": 38718,
"s": 38691,
"text": "public Stream<T> stream()\n"
},
{
"code": null,
"e": 38835,
"s": 38718,
"text": "If a value is present, it returns a sequential Stream containing only that value, otherwise returns an empty Stream."
},
{
"code": null,
"e": 39811,
"s": 38835,
"text": "import java.util.Arrays;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\n\npublic class Tester {\npublic static void main(String[] args) {\n List<Optional<String>> list = Arrays.asList (\n Optional.empty(), \n Optional.of(\"A\"), \n Optional.empty(), \n Optional.of(\"B\"));\n\n //filter the list based to print non-empty values\n \n //if optional is non-empty, get the value in stream, otherwise return empty\n List<String> filteredList = list.stream()\n .flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())\n .collect(Collectors.toList());\n\n //Optional::stream method will return a stream of either one \n //or zero element if data is present or not.\n List<String> filteredListJava9 = list.stream()\n .flatMap(Optional::stream)\n .collect(Collectors.toList());\n\n System.out.println(filteredList);\n System.out.println(filteredListJava9);\n } \n}"
},
{
"code": null,
"e": 39826,
"s": 39811,
"text": "[A, B]\n[A, B]\n"
},
{
"code": null,
"e": 39905,
"s": 39826,
"text": "public void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction)\n"
},
{
"code": null,
"e": 40019,
"s": 39905,
"text": "If a value is present, performs the given action with the value, otherwise performs the given empty-based action."
},
{
"code": null,
"e": 40459,
"s": 40019,
"text": "import java.util.Optional;\n\npublic class Tester {\n public static void main(String[] args) {\n Optional<Integer> optional = Optional.of(1);\n\n optional.ifPresentOrElse( x -> System.out.println(\"Value: \" + x),() -> \n System.out.println(\"Not Present.\"));\n\n optional = Optional.empty();\n\n optional.ifPresentOrElse( x -> System.out.println(\"Value: \" + x),() -> \n System.out.println(\"Not Present.\"));\n } \n}"
},
{
"code": null,
"e": 40482,
"s": 40459,
"text": "Value: 1\nNot Present.\n"
},
{
"code": null,
"e": 40557,
"s": 40482,
"text": "public Optional<T> or(Supplier<? extends Optional<? extends T>> supplier)\n"
},
{
"code": null,
"e": 40688,
"s": 40557,
"text": "If a value is present, returns an Optional describing the value, otherwise returns an Optional produced by the supplying function."
},
{
"code": null,
"e": 41259,
"s": 40688,
"text": "import java.util.Optional;\nimport java.util.function.Supplier;\n\npublic class Tester {\n public static void main(String[] args) {\n Optional<String> optional1 = Optional.of(\"Mahesh\");\n\n Supplier<Optional<String>> supplierString = () -> Optional.of(\"Not Present\");\n\n optional1 = optional1.or( supplierString);\n \n optional1.ifPresent( x -> System.out.println(\"Value: \" + x));\n \n optional1 = Optional.empty(); \n\n optional1 = optional1.or( supplierString);\n \n optional1.ifPresent( x -> System.out.println(\"Value: \" + x)); \n } \n}"
},
{
"code": null,
"e": 41293,
"s": 41259,
"text": "Value: Mahesh\nValue: Not Present\n"
},
{
"code": null,
"e": 41589,
"s": 41293,
"text": "With Java 9, a new multi-resolution image API has been introduced which supports multiple images with different resolution variants. This API allows a set of images with different resolution to be used as a single multi-resolution image. Following are major operations of multi-resolution image."
},
{
"code": null,
"e": 41764,
"s": 41589,
"text": "Image getResolutionVariant(double destImageWidth, double destImageHeight) − Gets a specific image which is best variant to represent this logical image at the indicated size."
},
{
"code": null,
"e": 41939,
"s": 41764,
"text": "Image getResolutionVariant(double destImageWidth, double destImageHeight) − Gets a specific image which is best variant to represent this logical image at the indicated size."
},
{
"code": null,
"e": 42026,
"s": 41939,
"text": "List<Image> getResolutionVariants() − Gets a readable list of all resolution variants."
},
{
"code": null,
"e": 42113,
"s": 42026,
"text": "List<Image> getResolutionVariants() − Gets a readable list of all resolution variants."
},
{
"code": null,
"e": 44267,
"s": 42113,
"text": "import java.io.IOException;\nimport java.net.URL;\nimport java.net.MalformedURLException;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.awt.Image;\nimport java.awt.image.MultiResolutionImage;\nimport java.awt.image.BaseMultiResolutionImage;\n\nimport javax.imageio.ImageIO;\n\npublic class Tester {\n public static void main(String[] args) throws IOException, MalformedURLException {\n\n List<String> imgUrls = List.of(\"http://www.tutorialspoint.com/java9/images/logo.png\",\n \"http://www.tutorialspoint.com/java9/images/mini_logo.png\",\n \"http://www.tutorialspoint.com/java9/images/large_logo.png\");\n\n List<Image> images = new ArrayList<Image>();\n\n for (String url : imgUrls) {\n images.add(ImageIO.read(new URL(url)));\n }\n\n // read all images into one multiresolution image\n MultiResolutionImage multiResolutionImage = \n new BaseMultiResolutionImage(images.toArray(new Image[0]));\n\n // get all variants of images\n List<Image> variants = multiResolutionImage.getResolutionVariants();\n\n System.out.println(\"Total number of images: \" + variants.size());\n\n for (Image img : variants) {\n System.out.println(img);\n }\n\n // get a resolution-specific image variant for each indicated size\n Image variant1 = multiResolutionImage.getResolutionVariant(156, 45);\n System.out.printf(\"\\nImage for destination[%d,%d]: [%d,%d]\", \n 156, 45, variant1.getWidth(null), variant1.getHeight(null));\n\n Image variant2 = multiResolutionImage.getResolutionVariant(311, 89);\n System.out.printf(\"\\nImage for destination[%d,%d]: [%d,%d]\", 311, 89, \n variant2.getWidth(null), variant2.getHeight(null));\n\n Image variant3 = multiResolutionImage.getResolutionVariant(622, 178);\n System.out.printf(\"\\nImage for destination[%d,%d]: [%d,%d]\", 622, 178, \n variant3.getWidth(null), variant3.getHeight(null));\n\n Image variant4 = multiResolutionImage.getResolutionVariant(300, 300);\n System.out.printf(\"\\nImage for destination[%d,%d]: [%d,%d]\", 300, 300, \n variant4.getWidth(null), variant4.getHeight(null));\n } \n}"
},
{
"code": null,
"e": 45263,
"s": 44267,
"text": "Total number of images: 3\nBufferedImage@7ce6a65d: type = 6 ColorModel: #pixelBits = 32 numComponents = 4 \ncolor space =java.awt.color.ICC_ColorSpace@548ad73b transparency = 3 \nhas alpha = true isAlphaPre = false ByteInterleavedRaster: width =311 \nheight = 89 #numDataElements 4 dataOff[0] = 3\n\nBufferedImage@4c762604: type = 6 ColorModel: #pixelBits = 32 numComponents = 4 \ncolor space =java.awt.color.ICC_ColorSpace@548ad73b transparency = 3 \nhas alpha = true isAlphaPre = false ByteInterleavedRaster: width =156 \nheight = 45 #numDataElements 4 dataOff[0] = 3\n\nBufferedImage@2641e737: type = 6 ColorModel: #pixelBits = 32 numComponents = 4 \ncolor space =java.awt.color.ICC_ColorSpace@548ad73b transparency = 3 \nhas alpha = true isAlphaPre = false ByteInterleavedRaster: width =622 \nheight = 178 #numDataElements 4 dataOff[0] = 3\n\nImage for destination[156,45]: [311,89]\nImage for destination[311,89]: [311,89]\nImage for destination[622,178]: [622,178]\nImage for destination[300,300]: [622,178]\n"
},
{
"code": null,
"e": 45663,
"s": 45263,
"text": "CompletableFuture class was introduced in Java 8 to represent the Future which can be completed by setting its value and status explicity. It can be used as java.util.concurrent.CompletionStage. It supports dependent functions and actions which got triggered upon the future's completion. In java 9 CompletableFuture API has been enhanced further. Following are the relevant changes done to the API."
},
{
"code": null,
"e": 45696,
"s": 45663,
"text": "Support for delays and timeouts."
},
{
"code": null,
"e": 45730,
"s": 45696,
"text": "Improved support for subclassing."
},
{
"code": null,
"e": 45757,
"s": 45730,
"text": "New factory methods added."
},
{
"code": null,
"e": 45841,
"s": 45757,
"text": "public CompletableFuture<T> completeOnTimeout(T value, long timeout, TimeUnit unit)"
},
{
"code": null,
"e": 45960,
"s": 45841,
"text": "This method completes this CompletableFuture with the given value if not otherwise completed before the given timeout."
},
{
"code": null,
"e": 46027,
"s": 45960,
"text": "public CompletableFuture<T> orTimeout(long timeout, TimeUnit unit)"
},
{
"code": null,
"e": 46163,
"s": 46027,
"text": "This method exceptionally completes this CompletableFuture with a TimeoutException if not otherwise completed before the given timeout."
},
{
"code": null,
"e": 46197,
"s": 46163,
"text": "public Executor defaultExecutor()"
},
{
"code": null,
"e": 46397,
"s": 46197,
"text": "It returns the default Executor used for async methods that do not specify an Executor. This method may be overridden in subclasses to return an Executor to provide one independent thread as minimum."
},
{
"code": null,
"e": 46451,
"s": 46397,
"text": "public <U> CompletableFuture<U> newIncompleteFuture()"
},
{
"code": null,
"e": 46758,
"s": 46451,
"text": "Returns a new incomplete CompletableFuture of the type to be returned by a CompletionStage method. Subclasses of CompletableFuture class should override this method to return an instance of the same class as this CompletableFuture. The default implementation returns an instance of class CompletableFuture."
},
{
"code": null,
"e": 46822,
"s": 46758,
"text": "public static <U> CompletableFuture<U> completedFuture(U value)"
},
{
"code": null,
"e": 46923,
"s": 46822,
"text": "This factory method returns a new CompletableFuture which is already completed with the given value."
},
{
"code": null,
"e": 46984,
"s": 46923,
"text": "public static <U> CompletionStage<U> completedStage(U value)"
},
{
"code": null,
"e": 47152,
"s": 46984,
"text": "This factory method returns a new CompletionStage which is already completed with the given value and supports only those methods present in interface CompletionStage."
},
{
"code": null,
"e": 47215,
"s": 47152,
"text": "public static <U> CompletionStage<U> failedStage(Throwable ex)"
},
{
"code": null,
"e": 47401,
"s": 47215,
"text": "This factory method returns a new CompletionStage which is already completed exceptionally with the given exception and supports only those methods present in interface CompletionStage."
},
{
"code": null,
"e": 47526,
"s": 47401,
"text": "Apart from mentioned features, with Java 9, a lot more enhancements are done to JDK platform. Some of them are listed below."
},
{
"code": null,
"e": 47562,
"s": 47526,
"text": "GC (Garbage Collector) Improvements"
},
{
"code": null,
"e": 47580,
"s": 47562,
"text": "Stack-Walking API"
},
{
"code": null,
"e": 47615,
"s": 47580,
"text": "Filter Incoming Serialization Data"
},
{
"code": null,
"e": 47640,
"s": 47615,
"text": "Deprecate the Applet API"
},
{
"code": null,
"e": 47668,
"s": 47640,
"text": "Indify String Concatenation"
},
{
"code": null,
"e": 47692,
"s": 47668,
"text": "Enhanced Method Handles"
},
{
"code": null,
"e": 47730,
"s": 47692,
"text": "Java Platform Logging API and Service"
},
{
"code": null,
"e": 47746,
"s": 47730,
"text": "Compact Strings"
},
{
"code": null,
"e": 47769,
"s": 47746,
"text": "Parser API for Nashorn"
},
{
"code": null,
"e": 47802,
"s": 47769,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 47818,
"s": 47802,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 47851,
"s": 47818,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 47867,
"s": 47851,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 47902,
"s": 47867,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 47916,
"s": 47902,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 47950,
"s": 47916,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 47964,
"s": 47950,
"text": " Tushar Kale"
},
{
"code": null,
"e": 48001,
"s": 47964,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 48016,
"s": 48001,
"text": " Monica Mittal"
},
{
"code": null,
"e": 48049,
"s": 48016,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 48068,
"s": 48049,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 48075,
"s": 48068,
"text": " Print"
},
{
"code": null,
"e": 48086,
"s": 48075,
"text": " Add Notes"
}
] |
Forecasting with Bayesian Dynamic Generalized Linear Models in Python | by Ryan Clukey | Towards Data Science | Forecasting is critical for nearly all businesses when planning for revenue goals, inventory management, headcount, and other economic considerations essential for managing a successful business. Highly accurate forecasts are often difficult to achieve, but essential to enable businesses plan for shifts and changes in a dynamic market. Often forecast models can (and should) take advantage of additional inputs or variables that may help explain the variability in the target or dependent series. For example, predicting the number of units sold based on visits to the website, or forecasting monthly revenue based on monthly marketing spend. As is often the case, the available data is often limited or incomplete, which complicates the ability to use standard algorithms to generate accurate forecasts.
In this article I’ll introduce the Bayesian approach to multivariate time series and provide a contrast to traditional frequentist methods, like ARIMA. Time series is a special case of regression where the independent variable is a regular interval time measure (i.e. weeks, months, years, etc.), along with potential exogeneous features which may be useful in explaining the residual variation of a sequential series. ARIMA (Auto Regressive, Integrated, Moving Average) has been one of the standard approaches to time series forecasting; it is a powerful algorithm and widely used across many industries. However, there are many complex considerations: the data should be stationary, there may be multiple trends, independent variables are often lagged, there is seasonality — sometimes multiple seasons in the same data, there must be a considerable amount of available data, etc. For these reasons, time series is a difficult statistical technique to master, and generating accurate forecasts is quite challenging.
The Bayesian approach offers a probabilistic approach to time series to reduce uncertainty and incorporate “prior” information. These models are referred to as Dynamic Linear Models or Structural Time Series (state space models). They work by fitting the structural changes in a time series dynamically — in other words, evolving and updating the model parameters over time with the addition of new information. In contrast, ARIMA estimates parameters for the series, which remain fixed, then uses Maximum Likelihood estimation for determining the time series predictions. Bayesian methods use MCMC (Monte Carlo Markov Chains) to generate estimates from distributions. For this case study I’ll be using Pybats — a Bayesian Forecasting package for Python. For those who are interested, and in-depth article on the statistical mechanics of Bayesian methods for time series can be found here.
In this case study we evaluate the effect of two independent time series (covariates) on our dependent variable: total number of monthly vehicle purchases for a particular auto manufacturer. Since this is count data, we are looking at a Poisson process, which assumes a different underlying distribution than that of Gaussian. Poisson models are based on counts, and therefore the lowest possible value is 0. The two covariates include: spend on marketing, aggregated at the monthly level and a measure of consumer sentiment for the given brand, normalized to a scale of 0–100.
Our data consists of 48 observations between January 2017 and December 2020. There are no missing values. The data represent monthly counts of vehicle sales, average marketing spend (in tens of thousands) and average consumer sentiment — a proprietary metric. Since we are using Python, I’ll provide some code snippets through to demonstrate the analysis steps.
# Import the necessary librariesimport pandas as pdimport numpy as npfrom scipy import statsimport pmdarima as pmdimport matplotlib.pyplot as pltimport pybatsfrom pybats.loss_functions import MAPEfrom pybats.analysis import analysisfrom pybats.point_forecast import median# import the datadfv = pd.read_csv("vechicle_data.csv")
Our dataset above shows the three variables we will be using for this analysis: Transactions is the dependent variable, with Marketing Spend and Consumer Sentiment as two Independent variables (or covariates) in the Dynamic Regression model. What we’re essentially saying here is: do Marketing Spend and Consumer Sentiment have a time-varying effect on the number of Transactions; can we model their effects and use the knowledge we have of these variables to generate reasonable predictions of Transactions beyond our current dataset?
Let’s take a look at the 3 separate time series we have so far:
DV: Number of Vehicles Sold
Simply visual examination reveals a couple of important things happening in this series: 1) the data is not stationary, 2) there appears to be a possible seasonal effect, 3) the variance increases with time. For ARIMA, these would be problematic, and our series would be subject to multiple “adjustments” such as differencing and seasonal decomposition in order to achieve the requirement of stationarity.
IV 1: Marketing Spend
The plot below shows the variability of Average Marketing Spend over the same period of time. This series is less clear. There might be seasonality, there might be shifts in trend; the series does not appear stationary. However, as mentioned, such considerations are irrelevant for Bayesian approaches to time series.
IV 2: Consumer Sentiment
Our metric of Consumer Sentiment follows closely with that of Marketing Spend, which we might expect given that marketing efforts should have an effect on consumer sentiment.
To build the model we will be build a function in Python to make things a little easier. There are a number of parameters to adjust in the model itself, including learning and decay rates, seasonality, how long the prior period should be (to learn the prior variance), etc. I’ll not go into those here, as descriptions and guidelines are provided by the Pybats tutorial.
def bayes_forecast(iv,dv): ''' This functions runs the Pybats algorithm by taking two parameters: an independent variable matrix and a dependent variable. Both elements must be sequential time series. ''' # first check if the iv = None, indicating this would be a univariate series if iv is None: x = None else: x = iv.values y = dv.values # set the one-step-ahead value; by default we want 1 k = 1 forecast_start = 0 forecast_end = len(y)-1 mod, samples = analysis(Y=y, X=x, family='poisson', forecast_start=forecast_start, forecast_end=forecast_end, k=k, ntrend=1, nsamps=5000, seasPeriods=[12], seasHarmComponents=[[1,2]], prior_length=4, deltrend=0.94, delregn=0.90, delVar=0.98, delSeas=0.98, rho=.6, ) forecast = median(samples) # set confidence interval for in-sample forecast credible_interval=95 alpha = (100-credible_interval)/2 upper=np.percentile(samples, [100-alpha], axis=0).reshape(-1) lower=np.percentile(samples, [alpha], axis=0).reshape(-1) print("MAPE:", MAPE(y[-18:], forecast[-18:]).round(2)) #Generate the Bayesian Future Forecast return mod, forecast, samples, ymv_mod, mv_for, mv_samp, mv_y = bayes_forecast(dfv.iloc[:,2:4], dfv.Transactions)
We’re going to use our Python function above to also run the equivalent model without the covariates — so a standard univariate time series. We’re doing this to determine if including the independent variables in the model is having the intended effect of reducing the overall residual error in the model. In other words, does including the variables improve our understanding of the data; is it worth including them in the model?
# Calculate Bayesian estimate for the univariate modeluv_mod, uv_for, uv_samp, uv_y = bayes_forecast(None, dfv.Transactions)
The plot below shows the results of our analysis. There are a number of observations we have. First, the model had a difficult time learning the beginning structure of the series, as evidenced by the wide credible intervals at the beginning of the series. Eventually the model parameters “learned” and the one-step ahead predictions for the multivariate model begin to more closely and follow the original series. This what we expected. However, note that the Univariate series did quite a poor job at capturing the movement and values of the original series. While it appears to learn the trend, its predictions are substantially and consistently off from the original dependent values, especially later in the series. This tells us something about the efficacy of the additional covariates in the model — we’ll come to that next.
One-Step-Ahead Predictions
The plot above shows the output from the Bayesian forecast. It shows one-step-ahead predictions with a 95% Credible Interval. This differs from ARIMA, which produces in-sample predictions.
An important difference between in-sample ARIMA predictions and those made with Pybats: In ARIMA, the in-sample predictions are practically quite useless. They reflect how well the estimated parameters fit the data, and to this end you can very easily over-fit the data simply by over parameterizing your model; it tells us nothing about how well the parameters perform on unseen data (not to mention the parameters are fixed). with Pybats, it’s not really an “in-sample” prediction. It’s a one-step-ahead prediction starting from the beginning of the series and updating each parameter as you move through the series. Therefore, each step-ahead is actually a true “out-of-sample prediction”, and thus there error from the prediction reflects true out-of-sample estimates based on the posterior probabilities. For ARIMA to do this, you would need to specify a hold-out sample at the end of your series, then implement a for-loop that iterates of each data point in the hold-out sample, update the model, move to the next point, update the model, etc.
Bayesian: Comparing Univariate to Multivariate
Did our multivariate Bayesian model perform better than the univariate model? We can observe this difference more readily by comparing the cumulative absolute error in the multivariate and univariate predictions. The plot below compares the cumulative error between the two models (univariate and multivariate). It shows that the covariates begin to explain more of the variability in the time series model as time progresses — which is what we would expect as the model learns and adjusts the parameters based on previous values.
Additionally we can examine the MAPE (mean absolute percentage error) for each model, and determine which model is more accurate in the one-step-ahead forecasts. In this case we examined the predictions for the previous 12 months and compared the MAPE. For the multivariate model we achieved a MAPE of ~20%, while the univariate model achieved a MAPE of 54%. 20% leaves a lot of room for improvement, but it’s certainly much better than 54! The MAD (mean absolute deviation) for the multivariate model is ~3,300, which means that our vehicle transaction estimates are estimated to be off by about 3,300 units each month.
Let’s take a look at how ARIMA does with our data. First, we’ll need to create a train/test split in the data; here we’ll use the last 12 months of the series as a holdout sample.
dfv_train = dfv[:-12]dfv_test = dfv[-12:]dfv_test
We’re using pmdarima, which is a convenient package that has built a wrapper around the Statsmodels implementation of SARIMAX.
mod = pmd.auto_arima(y=dfv_train.Transactions, exogenous=dfv_train.iloc[:,2:4], stepwise=True, m=12, seasonal=True)y_pred = mod.predict_in_sample(exogenous=dfv_train.iloc[:,2:4], return_conf_int=True, alpha=0.05)a_low = y_pred[1][:,0]a_high = y_pred[1][:,1]mod.summary()
Our output from the SARIMX (because it’s seasonal, and there are two exogenous covariates) is shown below. There’s lots of complexity here. First, the model is differenced, we observe a moving average component in both the main series, and in the seasonal component, the seasonal effect is also differenced. Clearly the data is not stationary. Neither of our covariates were found to be statistically significant in the model; according to ARIMA they are having no effect. This is a different outcome than what the Bayesian model observed.
How well did the ARIMA model perform in the hold-out sample of 12 months? Not too bad. we observed a MAPE of 22% The Bayesian model had a MAPE of 20% for the same 12-month time period.
The next step is to predict the future using the model we have created. Because we have introduced additional covariates, we will also need to predict (or somehow know) the future values of those covariates as well. In reality the practitioner will need to use their domain expertise to generate reliable estimates of the predictors out into the future. In some cases, the best approach may be to just use another model to forecast future values for these variables. However, cautionary note: generating forecasts from forecasts is potentially dangerous territory! For the purposes of this example, we estimated the 12-month forecast for each covariate using a univariate BTS model (Pybats using just a single variable), and used those projections as inputs when predicting the target series — against our better judgement.
The plot below shows how the model predictions the next 12 months. I’ve also provided the comparable ARIMA prediction using the same data. Note that ARIMA predictions are notably higher than those of the Bayesian model. We’ll need to track these as data comes in each month. I wouldn’t be surprised if the ARIMA model were constantly off, and the Bayesian model was more accurate, given the historical pattern of transactions.
This article provided a brief introduction to using Pybats for multivariate Bayesian forecasting. There tool is quite powerful, and worth looking into for those needing to produce accurate forecasts leveraging the power of dynamic linear regression models. The Bayesian approach more than makes up for the short-comings of ARIMA, especially where there is insufficient data, multiple variables and needing to understand the relative importance of variables in the model — in a more transparent way than ARIMA can provide. | [
{
"code": null,
"e": 979,
"s": 172,
"text": "Forecasting is critical for nearly all businesses when planning for revenue goals, inventory management, headcount, and other economic considerations essential for managing a successful business. Highly accurate forecasts are often difficult to achieve, but essential to enable businesses plan for shifts and changes in a dynamic market. Often forecast models can (and should) take advantage of additional inputs or variables that may help explain the variability in the target or dependent series. For example, predicting the number of units sold based on visits to the website, or forecasting monthly revenue based on monthly marketing spend. As is often the case, the available data is often limited or incomplete, which complicates the ability to use standard algorithms to generate accurate forecasts."
},
{
"code": null,
"e": 1997,
"s": 979,
"text": "In this article I’ll introduce the Bayesian approach to multivariate time series and provide a contrast to traditional frequentist methods, like ARIMA. Time series is a special case of regression where the independent variable is a regular interval time measure (i.e. weeks, months, years, etc.), along with potential exogeneous features which may be useful in explaining the residual variation of a sequential series. ARIMA (Auto Regressive, Integrated, Moving Average) has been one of the standard approaches to time series forecasting; it is a powerful algorithm and widely used across many industries. However, there are many complex considerations: the data should be stationary, there may be multiple trends, independent variables are often lagged, there is seasonality — sometimes multiple seasons in the same data, there must be a considerable amount of available data, etc. For these reasons, time series is a difficult statistical technique to master, and generating accurate forecasts is quite challenging."
},
{
"code": null,
"e": 2887,
"s": 1997,
"text": "The Bayesian approach offers a probabilistic approach to time series to reduce uncertainty and incorporate “prior” information. These models are referred to as Dynamic Linear Models or Structural Time Series (state space models). They work by fitting the structural changes in a time series dynamically — in other words, evolving and updating the model parameters over time with the addition of new information. In contrast, ARIMA estimates parameters for the series, which remain fixed, then uses Maximum Likelihood estimation for determining the time series predictions. Bayesian methods use MCMC (Monte Carlo Markov Chains) to generate estimates from distributions. For this case study I’ll be using Pybats — a Bayesian Forecasting package for Python. For those who are interested, and in-depth article on the statistical mechanics of Bayesian methods for time series can be found here."
},
{
"code": null,
"e": 3465,
"s": 2887,
"text": "In this case study we evaluate the effect of two independent time series (covariates) on our dependent variable: total number of monthly vehicle purchases for a particular auto manufacturer. Since this is count data, we are looking at a Poisson process, which assumes a different underlying distribution than that of Gaussian. Poisson models are based on counts, and therefore the lowest possible value is 0. The two covariates include: spend on marketing, aggregated at the monthly level and a measure of consumer sentiment for the given brand, normalized to a scale of 0–100."
},
{
"code": null,
"e": 3827,
"s": 3465,
"text": "Our data consists of 48 observations between January 2017 and December 2020. There are no missing values. The data represent monthly counts of vehicle sales, average marketing spend (in tens of thousands) and average consumer sentiment — a proprietary metric. Since we are using Python, I’ll provide some code snippets through to demonstrate the analysis steps."
},
{
"code": null,
"e": 4155,
"s": 3827,
"text": "# Import the necessary librariesimport pandas as pdimport numpy as npfrom scipy import statsimport pmdarima as pmdimport matplotlib.pyplot as pltimport pybatsfrom pybats.loss_functions import MAPEfrom pybats.analysis import analysisfrom pybats.point_forecast import median# import the datadfv = pd.read_csv(\"vechicle_data.csv\")"
},
{
"code": null,
"e": 4691,
"s": 4155,
"text": "Our dataset above shows the three variables we will be using for this analysis: Transactions is the dependent variable, with Marketing Spend and Consumer Sentiment as two Independent variables (or covariates) in the Dynamic Regression model. What we’re essentially saying here is: do Marketing Spend and Consumer Sentiment have a time-varying effect on the number of Transactions; can we model their effects and use the knowledge we have of these variables to generate reasonable predictions of Transactions beyond our current dataset?"
},
{
"code": null,
"e": 4755,
"s": 4691,
"text": "Let’s take a look at the 3 separate time series we have so far:"
},
{
"code": null,
"e": 4783,
"s": 4755,
"text": "DV: Number of Vehicles Sold"
},
{
"code": null,
"e": 5189,
"s": 4783,
"text": "Simply visual examination reveals a couple of important things happening in this series: 1) the data is not stationary, 2) there appears to be a possible seasonal effect, 3) the variance increases with time. For ARIMA, these would be problematic, and our series would be subject to multiple “adjustments” such as differencing and seasonal decomposition in order to achieve the requirement of stationarity."
},
{
"code": null,
"e": 5211,
"s": 5189,
"text": "IV 1: Marketing Spend"
},
{
"code": null,
"e": 5529,
"s": 5211,
"text": "The plot below shows the variability of Average Marketing Spend over the same period of time. This series is less clear. There might be seasonality, there might be shifts in trend; the series does not appear stationary. However, as mentioned, such considerations are irrelevant for Bayesian approaches to time series."
},
{
"code": null,
"e": 5554,
"s": 5529,
"text": "IV 2: Consumer Sentiment"
},
{
"code": null,
"e": 5729,
"s": 5554,
"text": "Our metric of Consumer Sentiment follows closely with that of Marketing Spend, which we might expect given that marketing efforts should have an effect on consumer sentiment."
},
{
"code": null,
"e": 6100,
"s": 5729,
"text": "To build the model we will be build a function in Python to make things a little easier. There are a number of parameters to adjust in the model itself, including learning and decay rates, seasonality, how long the prior period should be (to learn the prior variance), etc. I’ll not go into those here, as descriptions and guidelines are provided by the Pybats tutorial."
},
{
"code": null,
"e": 7659,
"s": 6100,
"text": "def bayes_forecast(iv,dv): ''' This functions runs the Pybats algorithm by taking two parameters: an independent variable matrix and a dependent variable. Both elements must be sequential time series. ''' # first check if the iv = None, indicating this would be a univariate series if iv is None: x = None else: x = iv.values y = dv.values # set the one-step-ahead value; by default we want 1 k = 1 forecast_start = 0 forecast_end = len(y)-1 mod, samples = analysis(Y=y, X=x, family='poisson', forecast_start=forecast_start, forecast_end=forecast_end, k=k, ntrend=1, nsamps=5000, seasPeriods=[12], seasHarmComponents=[[1,2]], prior_length=4, deltrend=0.94, delregn=0.90, delVar=0.98, delSeas=0.98, rho=.6, ) forecast = median(samples) # set confidence interval for in-sample forecast credible_interval=95 alpha = (100-credible_interval)/2 upper=np.percentile(samples, [100-alpha], axis=0).reshape(-1) lower=np.percentile(samples, [alpha], axis=0).reshape(-1) print(\"MAPE:\", MAPE(y[-18:], forecast[-18:]).round(2)) #Generate the Bayesian Future Forecast return mod, forecast, samples, ymv_mod, mv_for, mv_samp, mv_y = bayes_forecast(dfv.iloc[:,2:4], dfv.Transactions)"
},
{
"code": null,
"e": 8090,
"s": 7659,
"text": "We’re going to use our Python function above to also run the equivalent model without the covariates — so a standard univariate time series. We’re doing this to determine if including the independent variables in the model is having the intended effect of reducing the overall residual error in the model. In other words, does including the variables improve our understanding of the data; is it worth including them in the model?"
},
{
"code": null,
"e": 8215,
"s": 8090,
"text": "# Calculate Bayesian estimate for the univariate modeluv_mod, uv_for, uv_samp, uv_y = bayes_forecast(None, dfv.Transactions)"
},
{
"code": null,
"e": 9047,
"s": 8215,
"text": "The plot below shows the results of our analysis. There are a number of observations we have. First, the model had a difficult time learning the beginning structure of the series, as evidenced by the wide credible intervals at the beginning of the series. Eventually the model parameters “learned” and the one-step ahead predictions for the multivariate model begin to more closely and follow the original series. This what we expected. However, note that the Univariate series did quite a poor job at capturing the movement and values of the original series. While it appears to learn the trend, its predictions are substantially and consistently off from the original dependent values, especially later in the series. This tells us something about the efficacy of the additional covariates in the model — we’ll come to that next."
},
{
"code": null,
"e": 9074,
"s": 9047,
"text": "One-Step-Ahead Predictions"
},
{
"code": null,
"e": 9263,
"s": 9074,
"text": "The plot above shows the output from the Bayesian forecast. It shows one-step-ahead predictions with a 95% Credible Interval. This differs from ARIMA, which produces in-sample predictions."
},
{
"code": null,
"e": 10314,
"s": 9263,
"text": "An important difference between in-sample ARIMA predictions and those made with Pybats: In ARIMA, the in-sample predictions are practically quite useless. They reflect how well the estimated parameters fit the data, and to this end you can very easily over-fit the data simply by over parameterizing your model; it tells us nothing about how well the parameters perform on unseen data (not to mention the parameters are fixed). with Pybats, it’s not really an “in-sample” prediction. It’s a one-step-ahead prediction starting from the beginning of the series and updating each parameter as you move through the series. Therefore, each step-ahead is actually a true “out-of-sample prediction”, and thus there error from the prediction reflects true out-of-sample estimates based on the posterior probabilities. For ARIMA to do this, you would need to specify a hold-out sample at the end of your series, then implement a for-loop that iterates of each data point in the hold-out sample, update the model, move to the next point, update the model, etc."
},
{
"code": null,
"e": 10361,
"s": 10314,
"text": "Bayesian: Comparing Univariate to Multivariate"
},
{
"code": null,
"e": 10892,
"s": 10361,
"text": "Did our multivariate Bayesian model perform better than the univariate model? We can observe this difference more readily by comparing the cumulative absolute error in the multivariate and univariate predictions. The plot below compares the cumulative error between the two models (univariate and multivariate). It shows that the covariates begin to explain more of the variability in the time series model as time progresses — which is what we would expect as the model learns and adjusts the parameters based on previous values."
},
{
"code": null,
"e": 11513,
"s": 10892,
"text": "Additionally we can examine the MAPE (mean absolute percentage error) for each model, and determine which model is more accurate in the one-step-ahead forecasts. In this case we examined the predictions for the previous 12 months and compared the MAPE. For the multivariate model we achieved a MAPE of ~20%, while the univariate model achieved a MAPE of 54%. 20% leaves a lot of room for improvement, but it’s certainly much better than 54! The MAD (mean absolute deviation) for the multivariate model is ~3,300, which means that our vehicle transaction estimates are estimated to be off by about 3,300 units each month."
},
{
"code": null,
"e": 11693,
"s": 11513,
"text": "Let’s take a look at how ARIMA does with our data. First, we’ll need to create a train/test split in the data; here we’ll use the last 12 months of the series as a holdout sample."
},
{
"code": null,
"e": 11743,
"s": 11693,
"text": "dfv_train = dfv[:-12]dfv_test = dfv[-12:]dfv_test"
},
{
"code": null,
"e": 11870,
"s": 11743,
"text": "We’re using pmdarima, which is a convenient package that has built a wrapper around the Statsmodels implementation of SARIMAX."
},
{
"code": null,
"e": 12141,
"s": 11870,
"text": "mod = pmd.auto_arima(y=dfv_train.Transactions, exogenous=dfv_train.iloc[:,2:4], stepwise=True, m=12, seasonal=True)y_pred = mod.predict_in_sample(exogenous=dfv_train.iloc[:,2:4], return_conf_int=True, alpha=0.05)a_low = y_pred[1][:,0]a_high = y_pred[1][:,1]mod.summary()"
},
{
"code": null,
"e": 12681,
"s": 12141,
"text": "Our output from the SARIMX (because it’s seasonal, and there are two exogenous covariates) is shown below. There’s lots of complexity here. First, the model is differenced, we observe a moving average component in both the main series, and in the seasonal component, the seasonal effect is also differenced. Clearly the data is not stationary. Neither of our covariates were found to be statistically significant in the model; according to ARIMA they are having no effect. This is a different outcome than what the Bayesian model observed."
},
{
"code": null,
"e": 12866,
"s": 12681,
"text": "How well did the ARIMA model perform in the hold-out sample of 12 months? Not too bad. we observed a MAPE of 22% The Bayesian model had a MAPE of 20% for the same 12-month time period."
},
{
"code": null,
"e": 13690,
"s": 12866,
"text": "The next step is to predict the future using the model we have created. Because we have introduced additional covariates, we will also need to predict (or somehow know) the future values of those covariates as well. In reality the practitioner will need to use their domain expertise to generate reliable estimates of the predictors out into the future. In some cases, the best approach may be to just use another model to forecast future values for these variables. However, cautionary note: generating forecasts from forecasts is potentially dangerous territory! For the purposes of this example, we estimated the 12-month forecast for each covariate using a univariate BTS model (Pybats using just a single variable), and used those projections as inputs when predicting the target series — against our better judgement."
},
{
"code": null,
"e": 14117,
"s": 13690,
"text": "The plot below shows how the model predictions the next 12 months. I’ve also provided the comparable ARIMA prediction using the same data. Note that ARIMA predictions are notably higher than those of the Bayesian model. We’ll need to track these as data comes in each month. I wouldn’t be surprised if the ARIMA model were constantly off, and the Bayesian model was more accurate, given the historical pattern of transactions."
}
] |
How to decorate list bullets in arrow using CSS ? - GeeksforGeeks | 22 Apr, 2020
Given a list of items and the task is to customize the bullet style of the list and replace it with the arrow.
Method 1: By Unicode Character
First, we will turn off the default bullet style of the list.
Then We will insert Unicode of the arrow character in the content property in the “li::before” selector.
Example:
<!DOCTYPE html><html> <head> <title>Decorating Bullet Style</title> <!-- Internal css --> <style type="text/css"> <!-- Element selected by id --> #list{ color: green; background: white; font-size: 30px; } <!-- Removes default style of bullet point --> li{ list-style: none; } <!-- ::before creates a pseudo-element that is the first child of the selected element --> li::before{ <!-- Unicode for >> character --> content: "\00BB"; } </style></head> <body> <!-- list of elements --> <ul id="list"> <li> Geeks</li> <li> for</li> <li> Geeks</li> </ul></body> </html>
Output:
Method 2:
We will insert URL of the image that we want to insert in place of the default bullet styles in the “list-style-image” property.
Example:
<!DOCTYPE html><html> <head> <title>Decorating Bullet Style</title> <!-- Internal css --> <style type="text/css"> <!-- Element selected by id --> #list{ color: green; width: 300px; font-size: 45px; font-family: sans-serif; border:2px solid black; } ul{ margin: 100px 100px; } <!-- Adds desired image at the in place of default bullets --> li{ list-style-image:URL('https://media.geeksforgeeks.org/wp-content/uploads/20200331172037/image47.png'); list-style-position: inside; } </style></head> <body> <!-- list of elements --> <ul id="list"> <li> Geeks</li> <li> for</li> <li> Geeks</li> </ul></body> </html>
Output:
References:
https://developer.mozilla.org/en-US/docs/Web/CSS/::before
https://unicode-table.com/en/sets/arrow-symbols/
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Misc
HTML-Misc
Picked
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
Design a web page using HTML and CSS
Create a Responsive Navbar using ReactJS
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction) | [
{
"code": null,
"e": 23968,
"s": 23940,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 24079,
"s": 23968,
"text": "Given a list of items and the task is to customize the bullet style of the list and replace it with the arrow."
},
{
"code": null,
"e": 24110,
"s": 24079,
"text": "Method 1: By Unicode Character"
},
{
"code": null,
"e": 24172,
"s": 24110,
"text": "First, we will turn off the default bullet style of the list."
},
{
"code": null,
"e": 24277,
"s": 24172,
"text": "Then We will insert Unicode of the arrow character in the content property in the “li::before” selector."
},
{
"code": null,
"e": 24286,
"s": 24277,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Decorating Bullet Style</title> <!-- Internal css --> <style type=\"text/css\"> <!-- Element selected by id --> #list{ color: green; background: white; font-size: 30px; } <!-- Removes default style of bullet point --> li{ list-style: none; } <!-- ::before creates a pseudo-element that is the first child of the selected element --> li::before{ <!-- Unicode for >> character --> content: \"\\00BB\"; } </style></head> <body> <!-- list of elements --> <ul id=\"list\"> <li> Geeks</li> <li> for</li> <li> Geeks</li> </ul></body> </html>",
"e": 25073,
"s": 24286,
"text": null
},
{
"code": null,
"e": 25081,
"s": 25073,
"text": "Output:"
},
{
"code": null,
"e": 25091,
"s": 25081,
"text": "Method 2:"
},
{
"code": null,
"e": 25220,
"s": 25091,
"text": "We will insert URL of the image that we want to insert in place of the default bullet styles in the “list-style-image” property."
},
{
"code": null,
"e": 25229,
"s": 25220,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Decorating Bullet Style</title> <!-- Internal css --> <style type=\"text/css\"> <!-- Element selected by id --> #list{ color: green; width: 300px; font-size: 45px; font-family: sans-serif; border:2px solid black; } ul{ margin: 100px 100px; } <!-- Adds desired image at the in place of default bullets --> li{ list-style-image:URL('https://media.geeksforgeeks.org/wp-content/uploads/20200331172037/image47.png'); list-style-position: inside; } </style></head> <body> <!-- list of elements --> <ul id=\"list\"> <li> Geeks</li> <li> for</li> <li> Geeks</li> </ul></body> </html>",
"e": 26056,
"s": 25229,
"text": null
},
{
"code": null,
"e": 26064,
"s": 26056,
"text": "Output:"
},
{
"code": null,
"e": 26076,
"s": 26064,
"text": "References:"
},
{
"code": null,
"e": 26134,
"s": 26076,
"text": "https://developer.mozilla.org/en-US/docs/Web/CSS/::before"
},
{
"code": null,
"e": 26183,
"s": 26134,
"text": "https://unicode-table.com/en/sets/arrow-symbols/"
},
{
"code": null,
"e": 26320,
"s": 26183,
"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": 26329,
"s": 26320,
"text": "CSS-Misc"
},
{
"code": null,
"e": 26339,
"s": 26329,
"text": "HTML-Misc"
},
{
"code": null,
"e": 26346,
"s": 26339,
"text": "Picked"
},
{
"code": null,
"e": 26350,
"s": 26346,
"text": "CSS"
},
{
"code": null,
"e": 26355,
"s": 26350,
"text": "HTML"
},
{
"code": null,
"e": 26372,
"s": 26355,
"text": "Web Technologies"
},
{
"code": null,
"e": 26399,
"s": 26372,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 26404,
"s": 26399,
"text": "HTML"
},
{
"code": null,
"e": 26502,
"s": 26404,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26560,
"s": 26502,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 26597,
"s": 26560,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 26661,
"s": 26597,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 26698,
"s": 26661,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 26739,
"s": 26698,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 26799,
"s": 26739,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 26860,
"s": 26799,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 26913,
"s": 26860,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 26963,
"s": 26913,
"text": "How to Insert Form Data into Database using PHP ?"
}
] |
Automated Hyper-Parameter Optimization in SageMaker | by Zak Jost | Towards Data Science | Note: The code examples render on my blog much better than on Medium.
So you’ve built your model and are getting sensible results, and are now ready to squeeze out as much performance as possible. One possibility is doing Grid Search, where you try every possible combination of hyper-parameters and choose the best one. That works well if your number of choices are relatively small, but what if you have a large number of hyper-parameters, and some are continuous values that might span several orders of magnitude? Random Search works pretty well to explore the parameter space without committing to exploring all of it, but is randomly groping in the dark the best we can do?
Of course not. Bayesian Optimization is a technique for optimizing a function when making sequential decisions. In this case, we’re trying to maximize performance by choosing hyper-parameter values. This sequential decision framework means that the hyper-parameters you choose for the next step will be influenced by the performance of all the previous attempts. Bayesian Optimization makes principled decisions about how to balance exploring new regions of the parameter space vs exploiting regions that are known to perform well. This is all to say that it’s generally much more efficient to use Bayesian Optimization than alternatives like Grid Search and Random Search.
The good news is that SageMaker makes this very easy because the platform takes care of the following:
Implementing the Bayesian Optimization algorithm to handle categorical, integer, and float hyper-parametersOrchestrating the training and evaluation of models given a set of hyper-parameters from the HPO serviceIntegrate the training jobs and the HPO service, which communicates the selected hyper-parameter values and reports performance back once the job is complete
Implementing the Bayesian Optimization algorithm to handle categorical, integer, and float hyper-parameters
Orchestrating the training and evaluation of models given a set of hyper-parameters from the HPO service
Integrate the training jobs and the HPO service, which communicates the selected hyper-parameter values and reports performance back once the job is complete
The code below will assume we’re working with a TensorFlow Estimator model, but the HPO-relevant parts should extend to any SageMaker Estimator. To run code in the way this example presents, you’ll need the following:
Some understanding of how SageMaker works. If you’d like some examples of that, there are several official notebook examples in this repo. You might find the TensorFlow HPO example particularly relevant.
Have SageMaker’s Python SDK
Have configured the necessary API permissions, or are running in a SageMaker Notebook Instance
A key requirement to run HPO with SageMaker is that your model needs to both:
Expect the hyper-parameters to be passed from SageMakerWrite performance metrics to the logs
Expect the hyper-parameters to be passed from SageMaker
Write performance metrics to the logs
For built-in algorithms, this has already been completed for you. In the case of using SageMaker to build arbitrary TensorFlow models, this means configuring things correctly in the model.py file, a.k.a. the “entry point”. This is the file that SageMaker uses to build your TensorFlow model, and it expects certain functions to be defined that adhere to a particular input/output scheme. (See the TensorFlow README for more details about the functions you need to specify.)
To dynamically specify parameter values, your model code needs to accept, parse, and utilize them. In TensorFlow, you allow for hyper-parameters to be specified by SageMaker via the addition of the hyperparameters argument to the functions you need to specify in the entry point file. For example, for a hyper-parameter needed in your model_fn:
DEFAULT_LEARNING_RATE = 1e-3def model_fn(features, labels, mode, hyperparameters=None): if hyperparameters is None: hyperparameters = dict() # Extract parameters learning_rate = hyperparameters.get('learning_rate', DEFAULT_LEARNING_RATE) ...
You might also want a hyper-parameter in the train_input_fn, e.g. to specify the number of training epochs:
def train_input_fn(training_dir, hyperparameters=None): # Extract parameters if not hyperparameters: hyperparameters = dict() epochs = hyperparameters.get('epochs', None) ...
These examples extract the parameter if it’s specified, but use a default if not.
The second requirement of writing performance metrics to the logs is an implementation detail of SageMaker: it gets the model performance of the run by extracting it from the training logs text. These are the values that are sent back to the HPO engine.
For TensorFlow, metrics that are specified in the EstimatorSpec are written to the logs by default. For example, this code exists as part of my model_fn:
def model_fn(features, labels, model, hyperparameters=None) ... if mode == tf.estimator.ModeKeys.EVAL: eval_metric_ops = { "roc_auc": tf.metrics.auc( labels, predictions, summation_method='careful_interpolation'), "pr_auc": tf.metrics.auc( labels, predictions, summation_method='careful_interpolation', curve='PR'), } else: # e.g. in "training" mode eval_metric_ops = {} return tf.estimator.EstimatorSpec( mode=mode, loss=loss, train_op=train_op, eval_metric_ops=eval_metric_ops, )
During training, the model will periodically stop and evaluate the test set (the details of this process can be configured by you). The logs for these events will look something like the following:
2018–10–02 17:23:40,657 INFO — tensorflow — Saving dict for global step 101: global_step = 101, loss = 0.45420808, pr_auc = 0.36799875, roc_auc = 0.6891242
This is what SageMaker will use to measure the performance of any particular training job.
An Estimator is normally used to kick off a single training job. This enables you to tell SageMaker where to store the outputs, which instances to use for training...etc. Now that the functions in the entry point file have been properly configured to accept hyperparameters and write performance metrics to the logs, you can create the TensorFlow Estimator:
from sagemaker.tensorflow import TensorFlow# The parameters that are constant and will not be tunedshared_hyperparameters = { 'number_layers': 5,}tf_estimator = TensorFlow( entry_point='my/tensorflow/model.py', role='<sagemaker_role_arn>', train_instance_count=1, train_instance_type='ml.p3.2xlarge', training_steps=10000, hyperparameters=shared_hyperparameters,)
In this step, we need to tell SageMaker how to extract the performance information from the logs. This is done by specifying a RegEx expression and assigning it to a metric name. Although you can specify multiple expressions (which are automatically gathered in AWS CloudWatch for easy plotting/monitoring), one of them needs to be singled out as the optimization objective of the HPO. You also need to specify whether you want to maximize or minimize the number. Note that while the RegEx expression will likely match multiple log entries, it’s the last instance in the logs that’s returned as the final performance value.
objective_metric_name = 'PR-AUC'objective_type = 'Maximize'metric_definitions = [ {'Name': 'ROC-AUC', 'Regex': 'roc_auc = ([0-9\\.]+)'}, {'Name': 'PR-AUC', 'Regex': 'pr_auc = ([0-9\\.]+)'}]
We now need to specify what our hyper-parameters are called, what type they are (continuous, integer, or categorical), and what their possible values are. Below is an example:
from sagemaker.tuner import ( IntegerParameter, CategoricalParameter, ContinuousParameter, HyperparameterTuner)hyperparameter_ranges = { "learning_rate": ContinuousParameter(1e-5, 1e-1), "number_nodes": IntegerParameter(32, 512), "optimizer": CategoricalParameter(['Adam', 'SGD'])}
Finally, we need to decide how to run the HPO job. If you run many jobs in parallel, then you can explore a large part of the space simultaneously. However, if you just ran a million jobs in parallel, you would effectively be doing Random Search. It’s the sequential nature of Bayesian Optimization that allows future runs to be informed by the results of the previous runs.
We therefore need to decide how many total jobs to run, and how many to run in parallel at any given time. For instance, we might run 100 jobs, 5 in parallel. That would be 20 total sequential iterations, exploring 5 points at a time. The choices here will depend on the size of your parameter space and your budget.
Now you have everything you need to ask SageMaker to run HPO:
tuner = HyperparameterTuner( tf_estimator, objective_metric_name, hyperparameter_ranges, metric_definitions, max_jobs=100, max_parallel_jobs=5, objective_type=objective_type)# The data configurationchannel = { 'training': 's3://<bucket_name>/my/training_file.csv', 'test': 's3://<bucket_name>/my/test_file.csv',}tuner.fit(inputs=channel)
You can use the sdk for pinging SageMaker for status reports, or getting the stats of the best job from the HPO run. You can also do this from the AWS SageMaker console, which nicely presents a summary of all the jobs’ performance along with the HPO job configuration.
As mentioned above, you can go to CloudWatch in the console, click on Browse Metrics, and find the metrics you defined in the Name field of metric_definitions from Step 2.
And once everything is complete, you deploy the best model by simply issuing the following command:
tuner.deploy( initial_instance_count=1, instance_type='ml.p3.2xlarge')
You can find all of my content and subscribe at blog.zakjost.com | [
{
"code": null,
"e": 242,
"s": 172,
"text": "Note: The code examples render on my blog much better than on Medium."
},
{
"code": null,
"e": 852,
"s": 242,
"text": "So you’ve built your model and are getting sensible results, and are now ready to squeeze out as much performance as possible. One possibility is doing Grid Search, where you try every possible combination of hyper-parameters and choose the best one. That works well if your number of choices are relatively small, but what if you have a large number of hyper-parameters, and some are continuous values that might span several orders of magnitude? Random Search works pretty well to explore the parameter space without committing to exploring all of it, but is randomly groping in the dark the best we can do?"
},
{
"code": null,
"e": 1526,
"s": 852,
"text": "Of course not. Bayesian Optimization is a technique for optimizing a function when making sequential decisions. In this case, we’re trying to maximize performance by choosing hyper-parameter values. This sequential decision framework means that the hyper-parameters you choose for the next step will be influenced by the performance of all the previous attempts. Bayesian Optimization makes principled decisions about how to balance exploring new regions of the parameter space vs exploiting regions that are known to perform well. This is all to say that it’s generally much more efficient to use Bayesian Optimization than alternatives like Grid Search and Random Search."
},
{
"code": null,
"e": 1629,
"s": 1526,
"text": "The good news is that SageMaker makes this very easy because the platform takes care of the following:"
},
{
"code": null,
"e": 1998,
"s": 1629,
"text": "Implementing the Bayesian Optimization algorithm to handle categorical, integer, and float hyper-parametersOrchestrating the training and evaluation of models given a set of hyper-parameters from the HPO serviceIntegrate the training jobs and the HPO service, which communicates the selected hyper-parameter values and reports performance back once the job is complete"
},
{
"code": null,
"e": 2106,
"s": 1998,
"text": "Implementing the Bayesian Optimization algorithm to handle categorical, integer, and float hyper-parameters"
},
{
"code": null,
"e": 2211,
"s": 2106,
"text": "Orchestrating the training and evaluation of models given a set of hyper-parameters from the HPO service"
},
{
"code": null,
"e": 2369,
"s": 2211,
"text": "Integrate the training jobs and the HPO service, which communicates the selected hyper-parameter values and reports performance back once the job is complete"
},
{
"code": null,
"e": 2587,
"s": 2369,
"text": "The code below will assume we’re working with a TensorFlow Estimator model, but the HPO-relevant parts should extend to any SageMaker Estimator. To run code in the way this example presents, you’ll need the following:"
},
{
"code": null,
"e": 2791,
"s": 2587,
"text": "Some understanding of how SageMaker works. If you’d like some examples of that, there are several official notebook examples in this repo. You might find the TensorFlow HPO example particularly relevant."
},
{
"code": null,
"e": 2819,
"s": 2791,
"text": "Have SageMaker’s Python SDK"
},
{
"code": null,
"e": 2914,
"s": 2819,
"text": "Have configured the necessary API permissions, or are running in a SageMaker Notebook Instance"
},
{
"code": null,
"e": 2992,
"s": 2914,
"text": "A key requirement to run HPO with SageMaker is that your model needs to both:"
},
{
"code": null,
"e": 3085,
"s": 2992,
"text": "Expect the hyper-parameters to be passed from SageMakerWrite performance metrics to the logs"
},
{
"code": null,
"e": 3141,
"s": 3085,
"text": "Expect the hyper-parameters to be passed from SageMaker"
},
{
"code": null,
"e": 3179,
"s": 3141,
"text": "Write performance metrics to the logs"
},
{
"code": null,
"e": 3653,
"s": 3179,
"text": "For built-in algorithms, this has already been completed for you. In the case of using SageMaker to build arbitrary TensorFlow models, this means configuring things correctly in the model.py file, a.k.a. the “entry point”. This is the file that SageMaker uses to build your TensorFlow model, and it expects certain functions to be defined that adhere to a particular input/output scheme. (See the TensorFlow README for more details about the functions you need to specify.)"
},
{
"code": null,
"e": 3998,
"s": 3653,
"text": "To dynamically specify parameter values, your model code needs to accept, parse, and utilize them. In TensorFlow, you allow for hyper-parameters to be specified by SageMaker via the addition of the hyperparameters argument to the functions you need to specify in the entry point file. For example, for a hyper-parameter needed in your model_fn:"
},
{
"code": null,
"e": 4259,
"s": 3998,
"text": "DEFAULT_LEARNING_RATE = 1e-3def model_fn(features, labels, mode, hyperparameters=None): if hyperparameters is None: hyperparameters = dict() # Extract parameters learning_rate = hyperparameters.get('learning_rate', DEFAULT_LEARNING_RATE) ..."
},
{
"code": null,
"e": 4367,
"s": 4259,
"text": "You might also want a hyper-parameter in the train_input_fn, e.g. to specify the number of training epochs:"
},
{
"code": null,
"e": 4561,
"s": 4367,
"text": "def train_input_fn(training_dir, hyperparameters=None): # Extract parameters if not hyperparameters: hyperparameters = dict() epochs = hyperparameters.get('epochs', None) ..."
},
{
"code": null,
"e": 4643,
"s": 4561,
"text": "These examples extract the parameter if it’s specified, but use a default if not."
},
{
"code": null,
"e": 4897,
"s": 4643,
"text": "The second requirement of writing performance metrics to the logs is an implementation detail of SageMaker: it gets the model performance of the run by extracting it from the training logs text. These are the values that are sent back to the HPO engine."
},
{
"code": null,
"e": 5051,
"s": 4897,
"text": "For TensorFlow, metrics that are specified in the EstimatorSpec are written to the logs by default. For example, this code exists as part of my model_fn:"
},
{
"code": null,
"e": 5735,
"s": 5051,
"text": "def model_fn(features, labels, model, hyperparameters=None) ... if mode == tf.estimator.ModeKeys.EVAL: eval_metric_ops = { \"roc_auc\": tf.metrics.auc( labels, predictions, summation_method='careful_interpolation'), \"pr_auc\": tf.metrics.auc( labels, predictions, summation_method='careful_interpolation', curve='PR'), } else: # e.g. in \"training\" mode eval_metric_ops = {} return tf.estimator.EstimatorSpec( mode=mode, loss=loss, train_op=train_op, eval_metric_ops=eval_metric_ops, )"
},
{
"code": null,
"e": 5933,
"s": 5735,
"text": "During training, the model will periodically stop and evaluate the test set (the details of this process can be configured by you). The logs for these events will look something like the following:"
},
{
"code": null,
"e": 6089,
"s": 5933,
"text": "2018–10–02 17:23:40,657 INFO — tensorflow — Saving dict for global step 101: global_step = 101, loss = 0.45420808, pr_auc = 0.36799875, roc_auc = 0.6891242"
},
{
"code": null,
"e": 6180,
"s": 6089,
"text": "This is what SageMaker will use to measure the performance of any particular training job."
},
{
"code": null,
"e": 6538,
"s": 6180,
"text": "An Estimator is normally used to kick off a single training job. This enables you to tell SageMaker where to store the outputs, which instances to use for training...etc. Now that the functions in the entry point file have been properly configured to accept hyperparameters and write performance metrics to the logs, you can create the TensorFlow Estimator:"
},
{
"code": null,
"e": 6923,
"s": 6538,
"text": "from sagemaker.tensorflow import TensorFlow# The parameters that are constant and will not be tunedshared_hyperparameters = { 'number_layers': 5,}tf_estimator = TensorFlow( entry_point='my/tensorflow/model.py', role='<sagemaker_role_arn>', train_instance_count=1, train_instance_type='ml.p3.2xlarge', training_steps=10000, hyperparameters=shared_hyperparameters,)"
},
{
"code": null,
"e": 7547,
"s": 6923,
"text": "In this step, we need to tell SageMaker how to extract the performance information from the logs. This is done by specifying a RegEx expression and assigning it to a metric name. Although you can specify multiple expressions (which are automatically gathered in AWS CloudWatch for easy plotting/monitoring), one of them needs to be singled out as the optimization objective of the HPO. You also need to specify whether you want to maximize or minimize the number. Note that while the RegEx expression will likely match multiple log entries, it’s the last instance in the logs that’s returned as the final performance value."
},
{
"code": null,
"e": 7743,
"s": 7547,
"text": "objective_metric_name = 'PR-AUC'objective_type = 'Maximize'metric_definitions = [ {'Name': 'ROC-AUC', 'Regex': 'roc_auc = ([0-9\\\\.]+)'}, {'Name': 'PR-AUC', 'Regex': 'pr_auc = ([0-9\\\\.]+)'}]"
},
{
"code": null,
"e": 7919,
"s": 7743,
"text": "We now need to specify what our hyper-parameters are called, what type they are (continuous, integer, or categorical), and what their possible values are. Below is an example:"
},
{
"code": null,
"e": 8217,
"s": 7919,
"text": "from sagemaker.tuner import ( IntegerParameter, CategoricalParameter, ContinuousParameter, HyperparameterTuner)hyperparameter_ranges = { \"learning_rate\": ContinuousParameter(1e-5, 1e-1), \"number_nodes\": IntegerParameter(32, 512), \"optimizer\": CategoricalParameter(['Adam', 'SGD'])}"
},
{
"code": null,
"e": 8592,
"s": 8217,
"text": "Finally, we need to decide how to run the HPO job. If you run many jobs in parallel, then you can explore a large part of the space simultaneously. However, if you just ran a million jobs in parallel, you would effectively be doing Random Search. It’s the sequential nature of Bayesian Optimization that allows future runs to be informed by the results of the previous runs."
},
{
"code": null,
"e": 8909,
"s": 8592,
"text": "We therefore need to decide how many total jobs to run, and how many to run in parallel at any given time. For instance, we might run 100 jobs, 5 in parallel. That would be 20 total sequential iterations, exploring 5 points at a time. The choices here will depend on the size of your parameter space and your budget."
},
{
"code": null,
"e": 8971,
"s": 8909,
"text": "Now you have everything you need to ask SageMaker to run HPO:"
},
{
"code": null,
"e": 9336,
"s": 8971,
"text": "tuner = HyperparameterTuner( tf_estimator, objective_metric_name, hyperparameter_ranges, metric_definitions, max_jobs=100, max_parallel_jobs=5, objective_type=objective_type)# The data configurationchannel = { 'training': 's3://<bucket_name>/my/training_file.csv', 'test': 's3://<bucket_name>/my/test_file.csv',}tuner.fit(inputs=channel)"
},
{
"code": null,
"e": 9605,
"s": 9336,
"text": "You can use the sdk for pinging SageMaker for status reports, or getting the stats of the best job from the HPO run. You can also do this from the AWS SageMaker console, which nicely presents a summary of all the jobs’ performance along with the HPO job configuration."
},
{
"code": null,
"e": 9777,
"s": 9605,
"text": "As mentioned above, you can go to CloudWatch in the console, click on Browse Metrics, and find the metrics you defined in the Name field of metric_definitions from Step 2."
},
{
"code": null,
"e": 9877,
"s": 9777,
"text": "And once everything is complete, you deploy the best model by simply issuing the following command:"
},
{
"code": null,
"e": 9954,
"s": 9877,
"text": "tuner.deploy( initial_instance_count=1, instance_type='ml.p3.2xlarge')"
}
] |
Java Examples - Read a file using Applet | How to read a file using Applet?
Following example demonstrates how to read a file using an Applet using openStream() method of URL.
import java.applet.*;
import java.awt.*;
import java.io.*;
import java.net.*;
public class readFileApplet extends Applet {
String fileToRead = "test1.txt";
StringBuffer strBuff;
TextArea txtArea;
Graphics g;
public void init() {
txtArea = new TextArea(100, 100);
txtArea.setEditable(false);
add(txtArea, "center");
String prHtml = this.getParameter("fileToRead");
if (prHtml != null) fileToRead = new String(prHtml);
readFile();
}
public void readFile(){
String line;
URL url = null;
try {
url = new URL(getCodeBase(), fileToRead);
}
catch(MalformedURLException e){}
try {
InputStream in = url.openStream();
BufferedReader bf = new BufferedReader(new InputStreamReader(in));
strBuff = new StringBuffer();
while((line = bf.readLine()) != null) {
strBuff.append(line + "\n");
}
txtArea.append("File Name : " + fileToRead + "\n");
txtArea.append(strBuff.toString());
} catch(IOException e) {
e.printStackTrace();
}
}
}
The above code sample will produce the following result in a java enabled web browser.
View in Browser.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2101,
"s": 2068,
"text": "How to read a file using Applet?"
},
{
"code": null,
"e": 2201,
"s": 2101,
"text": "Following example demonstrates how to read a file using an Applet using openStream() method of URL."
},
{
"code": null,
"e": 3332,
"s": 2201,
"text": "import java.applet.*;\nimport java.awt.*;\nimport java.io.*;\nimport java.net.*;\n\npublic class readFileApplet extends Applet {\n String fileToRead = \"test1.txt\";\n StringBuffer strBuff;\n TextArea txtArea;\n Graphics g;\n \n public void init() {\n txtArea = new TextArea(100, 100);\n txtArea.setEditable(false);\n add(txtArea, \"center\");\n String prHtml = this.getParameter(\"fileToRead\");\n \n if (prHtml != null) fileToRead = new String(prHtml); \n readFile();\n }\n public void readFile(){\n String line;\n URL url = null;\n try {\n url = new URL(getCodeBase(), fileToRead);\n }\n catch(MalformedURLException e){}\n try {\n InputStream in = url.openStream();\n BufferedReader bf = new BufferedReader(new InputStreamReader(in));\n strBuff = new StringBuffer();\n while((line = bf.readLine()) != null) {\n strBuff.append(line + \"\\n\");\n }\n txtArea.append(\"File Name : \" + fileToRead + \"\\n\");\n txtArea.append(strBuff.toString());\n } catch(IOException e) {\n e.printStackTrace();\n }\n }\n}"
},
{
"code": null,
"e": 3419,
"s": 3332,
"text": "The above code sample will produce the following result in a java enabled web browser."
},
{
"code": null,
"e": 3438,
"s": 3419,
"text": "View in Browser. \n"
},
{
"code": null,
"e": 3445,
"s": 3438,
"text": " Print"
},
{
"code": null,
"e": 3456,
"s": 3445,
"text": " Add Notes"
}
] |
Triangle with no point inside - GeeksforGeeks | 13 Oct, 2021
Given N points in 2-dimensional space, we need to find three points such that triangle made by choosing these points should not contain any other points inside. All given points will not lie on the same line so solution will always exist. Examples:
In above diagram possible triangle with no point
inside can be formed by choosing these triplets,
[(0, 0), (2, 0), (1, 1)]
[(0, 0), (1, 1), (0, 2)]
[(1, 1), (2, 0), (2, 2)]
[(1, 1), (0, 2), (2, 2)]
So any of the above triplets can be the final answer.
The solution is based on the fact that if there exist triangle(s) with no points inside, then we can form a triangle with any random point among all points. We can solve this problem by searching all three points one by one. The first point can be chosen randomly. After choosing the first point, we need two points such that their slope should be different and no point should lie inside the triangle of these three points. We can do this by choosing the second point as nearest point to the first and third point as second nearest point with the different slope. For doing this, we first iterate over all points and choose the point which is nearest to the first one and designate that as second point of the required triangle. Then we iterate one more time to find point which has different slope and has the smallest distance, which will be the third point of our triangle.
C++
Java
Python 3
C#
Javascript
// C/C++ program to find triangle with no point inside#include <bits/stdc++.h>using namespace std; // method to get square of distance between// (x1, y1) and (x2, y2)int getDistance(int x1, int y1, int x2, int y2){ return (x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1);} // Method prints points which make triangle with no// point insidevoid triangleWithNoPointInside(int points[][2], int N){ // any point can be chosen as first point of triangle int first = 0; int second, third; int minD = INT_MAX; // choose nearest point as second point of triangle for (int i = 0; i < N; i++) { if (i == first) continue; // Get distance from first point and choose // nearest one int d = getDistance(points[i][0], points[i][1], points[first][0], points[first][1]); if (minD > d) { minD = d; second = i; } } // Pick third point by finding the second closest // point with different slope. minD = INT_MAX; for (int i = 0; i < N; i++) { // if already chosen point then skip them if (i == first || i == second) continue; // get distance from first point int d = getDistance(points[i][0], points[i][1], points[first][0], points[first][1]); /* the slope of the third point with the first point should not be equal to the slope of second point with first point (otherwise they'll be collinear) and among all such points, we choose point with the smallest distance */ // here cross multiplication is compared instead // of division comparison if ((points[i][0] - points[first][0]) * (points[second][1] - points[first][1]) != (points[second][0] - points[first][0]) * (points[i][1] - points[first][1]) && minD > d) { minD = d; third = i; } } cout << points[first][0] << ", " << points[first][1] << endl; cout << points[second][0] << ", " << points[second][1] << endl; cout << points[third][0] << ", " << points[third][1] << endl;} // Driver code to test above methodsint main(){ int points[][2] = {{0, 0}, {0, 2}, {2, 0}, {2, 2}, {1, 1}}; int N = sizeof(points) / sizeof(points[0]); triangleWithNoPointInside(points, N); return 0;}
// Java program to find triangle// with no point insideimport java.io.*; class GFG{ // method to get square of distance between // (x1, y1) and (x2, y2) static int getDistance(int x1, int y1, int x2, int y2) { return (x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1); } // Method prints points which make triangle with no // point inside static void triangleWithNoPointInside(int points[][], int N) { // any point can be chosen as first point of triangle int first = 0; int second =0; int third =0; int minD = Integer.MAX_VALUE; // choose nearest point as second point of triangle for (int i = 0; i < N; i++) { if (i == first) continue; // Get distance from first point and choose // nearest one int d = getDistance(points[i][0], points[i][1], points[first][0], points[first][1]); if (minD > d) { minD = d; second = i; } } // Pick third point by finding the second closest // point with different slope. minD = Integer.MAX_VALUE; for (int i = 0; i < N; i++) { // if already chosen point then skip them if (i == first || i == second) continue; // get distance from first point int d = getDistance(points[i][0], points[i][1], points[first][0], points[first][1]); /* the slope of the third point with the first point should not be equal to the slope of second point with first point (otherwise they'll be collinear) and among all such points, we choose point with the smallest distance */ // here cross multiplication is compared instead // of division comparison if ((points[i][0] - points[first][0]) * (points[second][1] - points[first][1]) != (points[second][0] - points[first][0]) * (points[i][1] - points[first][1]) && minD > d) { minD = d; third = i; } } System.out.println(points[first][0] + ", " + points[first][1]); System.out.println(points[second][0]+ ", " + points[second][1]) ; System.out.println(points[third][0] +", " + points[third][1]); } // Driver code public static void main (String[] args) { int points[][] = {{0, 0}, {0, 2}, {2, 0}, {2, 2}, {1, 1}}; int N = points.length; triangleWithNoPointInside(points, N); }} // This article is contributed by vt_m.
# Python3 program to find triangle# with no point insideimport sys # method to get square of distance between# (x1, y1) and (x2, y2)def getDistance(x1, y1, x2, y2): return (x2 - x1) * (x2 - x1) + \ (y2 - y1) * (y2 - y1) # Method prints points which make triangle# with no point insidedef triangleWithNoPointInside(points, N): # any point can be chosen as # first point of triangle first = 0 second = 0 third = 0 minD = sys.maxsize # choose nearest point as # second point of triangle for i in range(0, N): if i == first: continue # Get distance from first point and choose # nearest one d = getDistance(points[i][0], points[i][1], points[first][0], points[first][1]) if minD > d: minD = d second = i # Pick third point by finding the second closest # point with different slope. minD = sys.maxsize for i in range (0, N): # if already chosen point then skip them if i == first or i == second: continue # get distance from first point d = getDistance(points[i][0], points[i][1], points[first][0], points[first][1]) """ the slope of the third point with the first point should not be equal to the slope of second point with first point (otherwise they'll be collinear) and among all such points, we choose point with the smallest distance """ # here cross multiplication is compared instead # of division comparison if ((points[i][0] - points[first][0]) * (points[second][1] - points[first][1]) != (points[second][0] - points[first][0]) * (points[i][1] - points[first][1]) and minD > d) : minD = d third = i print(points[first][0], ', ', points[first][1]) print(points[second][0], ', ', points[second][1]) print(points[third][0], ', ', points[third][1]) # Driver codepoints = [[0, 0], [0, 2], [2, 0], [2, 2], [1, 1]]N = len(points)triangleWithNoPointInside(points, N) # This code is contributed by Gowtham Yuvaraj
using System; // C# program to find triangle// with no point inside public class GFG{ // method to get square of distance between // (x1, y1) and (x2, y2) public static int getDistance(int x1, int y1, int x2, int y2) { return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); } // Method prints points which make triangle with no // point inside public static void triangleWithNoPointInside(int[][] points, int N) { // any point can be chosen as first point of triangle int first = 0; int second = 0; int third = 0; int minD = int.MaxValue; // choose nearest point as second point of triangle for (int i = 0; i < N; i++) { if (i == first) { continue; } // Get distance from first point and choose // nearest one int d = getDistance(points[i][0], points[i][1], points[first][0], points[first][1]); if (minD > d) { minD = d; second = i; } } // Pick third point by finding the second closest // point with different slope. minD = int.MaxValue; for (int i = 0; i < N; i++) { // if already chosen point then skip them if (i == first || i == second) { continue; } // get distance from first point int d = getDistance(points[i][0], points[i][1], points[first][0], points[first][1]); /* the slope of the third point with the first point should not be equal to the slope of second point with first point (otherwise they'll be collinear) and among all such points, we choose point with the smallest distance */ // here cross multiplication is compared instead // of division comparison if ((points[i][0] - points[first][0]) * (points[second][1] - points[first][1]) != (points[second][0] - points[first][0]) * (points[i][1] - points[first][1]) && minD > d) { minD = d; third = i; } } Console.WriteLine(points[first][0] + ", " + points[first][1]); Console.WriteLine(points[second][0] + ", " + points[second][1]); Console.WriteLine(points[third][0] + ", " + points[third][1]); } // Driver code public static void Main(string[] args) { int[][] points = new int[][] { new int[] {0, 0}, new int[] {0, 2}, new int[] {2, 0}, new int[] {2, 2}, new int[] {1, 1} }; int N = points.Length; triangleWithNoPointInside(points, N); }} // This code is contributed by Shrikant13
<script>// javascript program to find triangle// with no point inside // method to get square of distance between // (x1, y1) and (x2, y2) function getDistance(x1 , y1 , x2 , y2) { return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); } // Method prints points which make triangle with no // point inside function triangleWithNoPointInside(points , N) { // any point can be chosen as first point of triangle var first = 0; var second = 0; var third = 0; var minD = Number.MAX_VALUE; // choose nearest point as second point of triangle for (i = 0; i < N; i++) { if (i == first) continue; // Get distance from first point and choose // nearest one var d = getDistance(points[i][0], points[i][1], points[first][0], points[first][1]); if (minD > d) { minD = d; second = i; } } // Pick third point by finding the second closest // point with different slope. minD = Number.MAX_VALUE; for (i = 0; i < N; i++) { // if already chosen point then skip them if (i == first || i == second) continue; // get distance from first point var d = getDistance(points[i][0], points[i][1], points[first][0], points[first][1]); /* * the slope of the third point with the first point should not be equal to the * slope of second point with first point (otherwise they'll be collinear) and * among all such points, we choose point with the smallest distance */ // here cross multiplication is compared instead // of division comparison if ((points[i][0] - points[first][0]) * (points[second][1] - points[first][1]) != (points[second][0] - points[first][0]) * (points[i][1] - points[first][1]) && minD > d) { minD = d; third = i; } } document.write(points[first][0] + ", " + points[first][1]+"<br/>"); document.write(points[second][0] + ", " + points[second][1]+"<br/>"); document.write(points[third][0] + ", " + points[third][1]+"<br/>"); } // Driver code var points = [ [ 0, 0 ], [ 0, 2 ], [ 2, 0 ], [ 2, 2 ], [ 1, 1 ] ]; var N = points.length; triangleWithNoPointInside(points, N); // This code contributed by umadevi9616</script>
Output:
0, 0
1, 1
0, 2
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
shrikanth13
gowtham_yuvaraj
umadevi9616
simranarora5sos
triangle
Geometric
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)
Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
Program for distance between two points on earth
Closest Pair of Points | O(nlogn) Implementation
Equation of circle when three points on the circle are given
Program to check if three points are collinear
Given n line segments, find if any two segments intersect
Polygon Clipping | Sutherland–Hodgman Algorithm
Convex Hull | Set 2 (Graham Scan)
Program for Point of Intersection of Two Lines | [
{
"code": null,
"e": 25102,
"s": 25074,
"text": "\n13 Oct, 2021"
},
{
"code": null,
"e": 25353,
"s": 25102,
"text": "Given N points in 2-dimensional space, we need to find three points such that triangle made by choosing these points should not contain any other points inside. All given points will not lie on the same line so solution will always exist. Examples: "
},
{
"code": null,
"e": 25607,
"s": 25353,
"text": "In above diagram possible triangle with no point \ninside can be formed by choosing these triplets,\n[(0, 0), (2, 0), (1, 1)]\n[(0, 0), (1, 1), (0, 2)]\n[(1, 1), (2, 0), (2, 2)]\n[(1, 1), (0, 2), (2, 2)]\n\nSo any of the above triplets can be the final answer."
},
{
"code": null,
"e": 26489,
"s": 25609,
"text": "The solution is based on the fact that if there exist triangle(s) with no points inside, then we can form a triangle with any random point among all points. We can solve this problem by searching all three points one by one. The first point can be chosen randomly. After choosing the first point, we need two points such that their slope should be different and no point should lie inside the triangle of these three points. We can do this by choosing the second point as nearest point to the first and third point as second nearest point with the different slope. For doing this, we first iterate over all points and choose the point which is nearest to the first one and designate that as second point of the required triangle. Then we iterate one more time to find point which has different slope and has the smallest distance, which will be the third point of our triangle. "
},
{
"code": null,
"e": 26493,
"s": 26489,
"text": "C++"
},
{
"code": null,
"e": 26498,
"s": 26493,
"text": "Java"
},
{
"code": null,
"e": 26507,
"s": 26498,
"text": "Python 3"
},
{
"code": null,
"e": 26510,
"s": 26507,
"text": "C#"
},
{
"code": null,
"e": 26521,
"s": 26510,
"text": "Javascript"
},
{
"code": "// C/C++ program to find triangle with no point inside#include <bits/stdc++.h>using namespace std; // method to get square of distance between// (x1, y1) and (x2, y2)int getDistance(int x1, int y1, int x2, int y2){ return (x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1);} // Method prints points which make triangle with no// point insidevoid triangleWithNoPointInside(int points[][2], int N){ // any point can be chosen as first point of triangle int first = 0; int second, third; int minD = INT_MAX; // choose nearest point as second point of triangle for (int i = 0; i < N; i++) { if (i == first) continue; // Get distance from first point and choose // nearest one int d = getDistance(points[i][0], points[i][1], points[first][0], points[first][1]); if (minD > d) { minD = d; second = i; } } // Pick third point by finding the second closest // point with different slope. minD = INT_MAX; for (int i = 0; i < N; i++) { // if already chosen point then skip them if (i == first || i == second) continue; // get distance from first point int d = getDistance(points[i][0], points[i][1], points[first][0], points[first][1]); /* the slope of the third point with the first point should not be equal to the slope of second point with first point (otherwise they'll be collinear) and among all such points, we choose point with the smallest distance */ // here cross multiplication is compared instead // of division comparison if ((points[i][0] - points[first][0]) * (points[second][1] - points[first][1]) != (points[second][0] - points[first][0]) * (points[i][1] - points[first][1]) && minD > d) { minD = d; third = i; } } cout << points[first][0] << \", \" << points[first][1] << endl; cout << points[second][0] << \", \" << points[second][1] << endl; cout << points[third][0] << \", \" << points[third][1] << endl;} // Driver code to test above methodsint main(){ int points[][2] = {{0, 0}, {0, 2}, {2, 0}, {2, 2}, {1, 1}}; int N = sizeof(points) / sizeof(points[0]); triangleWithNoPointInside(points, N); return 0;}",
"e": 28986,
"s": 26521,
"text": null
},
{
"code": "// Java program to find triangle// with no point insideimport java.io.*; class GFG{ // method to get square of distance between // (x1, y1) and (x2, y2) static int getDistance(int x1, int y1, int x2, int y2) { return (x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1); } // Method prints points which make triangle with no // point inside static void triangleWithNoPointInside(int points[][], int N) { // any point can be chosen as first point of triangle int first = 0; int second =0; int third =0; int minD = Integer.MAX_VALUE; // choose nearest point as second point of triangle for (int i = 0; i < N; i++) { if (i == first) continue; // Get distance from first point and choose // nearest one int d = getDistance(points[i][0], points[i][1], points[first][0], points[first][1]); if (minD > d) { minD = d; second = i; } } // Pick third point by finding the second closest // point with different slope. minD = Integer.MAX_VALUE; for (int i = 0; i < N; i++) { // if already chosen point then skip them if (i == first || i == second) continue; // get distance from first point int d = getDistance(points[i][0], points[i][1], points[first][0], points[first][1]); /* the slope of the third point with the first point should not be equal to the slope of second point with first point (otherwise they'll be collinear) and among all such points, we choose point with the smallest distance */ // here cross multiplication is compared instead // of division comparison if ((points[i][0] - points[first][0]) * (points[second][1] - points[first][1]) != (points[second][0] - points[first][0]) * (points[i][1] - points[first][1]) && minD > d) { minD = d; third = i; } } System.out.println(points[first][0] + \", \" + points[first][1]); System.out.println(points[second][0]+ \", \" + points[second][1]) ; System.out.println(points[third][0] +\", \" + points[third][1]); } // Driver code public static void main (String[] args) { int points[][] = {{0, 0}, {0, 2}, {2, 0}, {2, 2}, {1, 1}}; int N = points.length; triangleWithNoPointInside(points, N); }} // This article is contributed by vt_m.",
"e": 31819,
"s": 28986,
"text": null
},
{
"code": "# Python3 program to find triangle# with no point insideimport sys # method to get square of distance between# (x1, y1) and (x2, y2)def getDistance(x1, y1, x2, y2): return (x2 - x1) * (x2 - x1) + \\ (y2 - y1) * (y2 - y1) # Method prints points which make triangle# with no point insidedef triangleWithNoPointInside(points, N): # any point can be chosen as # first point of triangle first = 0 second = 0 third = 0 minD = sys.maxsize # choose nearest point as # second point of triangle for i in range(0, N): if i == first: continue # Get distance from first point and choose # nearest one d = getDistance(points[i][0], points[i][1], points[first][0], points[first][1]) if minD > d: minD = d second = i # Pick third point by finding the second closest # point with different slope. minD = sys.maxsize for i in range (0, N): # if already chosen point then skip them if i == first or i == second: continue # get distance from first point d = getDistance(points[i][0], points[i][1], points[first][0], points[first][1]) \"\"\" the slope of the third point with the first point should not be equal to the slope of second point with first point (otherwise they'll be collinear) and among all such points, we choose point with the smallest distance \"\"\" # here cross multiplication is compared instead # of division comparison if ((points[i][0] - points[first][0]) * (points[second][1] - points[first][1]) != (points[second][0] - points[first][0]) * (points[i][1] - points[first][1]) and minD > d) : minD = d third = i print(points[first][0], ', ', points[first][1]) print(points[second][0], ', ', points[second][1]) print(points[third][0], ', ', points[third][1]) # Driver codepoints = [[0, 0], [0, 2], [2, 0], [2, 2], [1, 1]]N = len(points)triangleWithNoPointInside(points, N) # This code is contributed by Gowtham Yuvaraj",
"e": 34085,
"s": 31819,
"text": null
},
{
"code": "using System; // C# program to find triangle// with no point inside public class GFG{ // method to get square of distance between // (x1, y1) and (x2, y2) public static int getDistance(int x1, int y1, int x2, int y2) { return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); } // Method prints points which make triangle with no // point inside public static void triangleWithNoPointInside(int[][] points, int N) { // any point can be chosen as first point of triangle int first = 0; int second = 0; int third = 0; int minD = int.MaxValue; // choose nearest point as second point of triangle for (int i = 0; i < N; i++) { if (i == first) { continue; } // Get distance from first point and choose // nearest one int d = getDistance(points[i][0], points[i][1], points[first][0], points[first][1]); if (minD > d) { minD = d; second = i; } } // Pick third point by finding the second closest // point with different slope. minD = int.MaxValue; for (int i = 0; i < N; i++) { // if already chosen point then skip them if (i == first || i == second) { continue; } // get distance from first point int d = getDistance(points[i][0], points[i][1], points[first][0], points[first][1]); /* the slope of the third point with the first point should not be equal to the slope of second point with first point (otherwise they'll be collinear) and among all such points, we choose point with the smallest distance */ // here cross multiplication is compared instead // of division comparison if ((points[i][0] - points[first][0]) * (points[second][1] - points[first][1]) != (points[second][0] - points[first][0]) * (points[i][1] - points[first][1]) && minD > d) { minD = d; third = i; } } Console.WriteLine(points[first][0] + \", \" + points[first][1]); Console.WriteLine(points[second][0] + \", \" + points[second][1]); Console.WriteLine(points[third][0] + \", \" + points[third][1]); } // Driver code public static void Main(string[] args) { int[][] points = new int[][] { new int[] {0, 0}, new int[] {0, 2}, new int[] {2, 0}, new int[] {2, 2}, new int[] {1, 1} }; int N = points.Length; triangleWithNoPointInside(points, N); }} // This code is contributed by Shrikant13",
"e": 36905,
"s": 34085,
"text": null
},
{
"code": "<script>// javascript program to find triangle// with no point inside // method to get square of distance between // (x1, y1) and (x2, y2) function getDistance(x1 , y1 , x2 , y2) { return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); } // Method prints points which make triangle with no // point inside function triangleWithNoPointInside(points , N) { // any point can be chosen as first point of triangle var first = 0; var second = 0; var third = 0; var minD = Number.MAX_VALUE; // choose nearest point as second point of triangle for (i = 0; i < N; i++) { if (i == first) continue; // Get distance from first point and choose // nearest one var d = getDistance(points[i][0], points[i][1], points[first][0], points[first][1]); if (minD > d) { minD = d; second = i; } } // Pick third point by finding the second closest // point with different slope. minD = Number.MAX_VALUE; for (i = 0; i < N; i++) { // if already chosen point then skip them if (i == first || i == second) continue; // get distance from first point var d = getDistance(points[i][0], points[i][1], points[first][0], points[first][1]); /* * the slope of the third point with the first point should not be equal to the * slope of second point with first point (otherwise they'll be collinear) and * among all such points, we choose point with the smallest distance */ // here cross multiplication is compared instead // of division comparison if ((points[i][0] - points[first][0]) * (points[second][1] - points[first][1]) != (points[second][0] - points[first][0]) * (points[i][1] - points[first][1]) && minD > d) { minD = d; third = i; } } document.write(points[first][0] + \", \" + points[first][1]+\"<br/>\"); document.write(points[second][0] + \", \" + points[second][1]+\"<br/>\"); document.write(points[third][0] + \", \" + points[third][1]+\"<br/>\"); } // Driver code var points = [ [ 0, 0 ], [ 0, 2 ], [ 2, 0 ], [ 2, 2 ], [ 1, 1 ] ]; var N = points.length; triangleWithNoPointInside(points, N); // This code contributed by umadevi9616</script>",
"e": 39462,
"s": 36905,
"text": null
},
{
"code": null,
"e": 39472,
"s": 39462,
"text": "Output: "
},
{
"code": null,
"e": 39487,
"s": 39472,
"text": "0, 0\n1, 1\n0, 2"
},
{
"code": null,
"e": 39911,
"s": 39487,
"text": "This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 39923,
"s": 39911,
"text": "shrikanth13"
},
{
"code": null,
"e": 39939,
"s": 39923,
"text": "gowtham_yuvaraj"
},
{
"code": null,
"e": 39951,
"s": 39939,
"text": "umadevi9616"
},
{
"code": null,
"e": 39967,
"s": 39951,
"text": "simranarora5sos"
},
{
"code": null,
"e": 39976,
"s": 39967,
"text": "triangle"
},
{
"code": null,
"e": 39986,
"s": 39976,
"text": "Geometric"
},
{
"code": null,
"e": 39996,
"s": 39986,
"text": "Geometric"
},
{
"code": null,
"e": 40094,
"s": 39996,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40103,
"s": 40094,
"text": "Comments"
},
{
"code": null,
"e": 40116,
"s": 40103,
"text": "Old Comments"
},
{
"code": null,
"e": 40169,
"s": 40116,
"text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)"
},
{
"code": null,
"e": 40220,
"s": 40169,
"text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)"
},
{
"code": null,
"e": 40269,
"s": 40220,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 40318,
"s": 40269,
"text": "Closest Pair of Points | O(nlogn) Implementation"
},
{
"code": null,
"e": 40379,
"s": 40318,
"text": "Equation of circle when three points on the circle are given"
},
{
"code": null,
"e": 40426,
"s": 40379,
"text": "Program to check if three points are collinear"
},
{
"code": null,
"e": 40484,
"s": 40426,
"text": "Given n line segments, find if any two segments intersect"
},
{
"code": null,
"e": 40532,
"s": 40484,
"text": "Polygon Clipping | Sutherland–Hodgman Algorithm"
},
{
"code": null,
"e": 40566,
"s": 40532,
"text": "Convex Hull | Set 2 (Graham Scan)"
}
] |
Int16.MaxValue Field in C# with Examples - GeeksforGeeks | 08 Apr, 2019
The MaxValue field or property of Int16 Struct is used to represent the maximum value of Int16. The value of this field is constant means that the user cannot change the value of this field. The value of this field is 32767. Its hexadecimal value is 0x7FFF. It is used to avoid the OverflowException while converting from a numeric type with a greater upper range (such as a UInt16 or an Int32) to an Int16.
Syntax:
public const short MaxValue = 32767;
Return Value: This field always returns 32767.
Example:
// C# program to illustrate the// Int16.MaxValue fieldusing System; class GFG { // Main Method static public void Main() { // display the Maximum value // of Int16 struct Console.WriteLine("Maximum Value is: "+ Int16.MaxValue); // Taking an array of long i.e Int64 data type long[]num = {345, -4677, -65245465445441, 44456564}; // taking variable of Int16 type short mynum; foreach(long n in num){ if(n >= Int16.MinValue && n <= Int16.MaxValue) { // using the method of Convert class // to convert Int64 to Int16 mynum = Convert.ToInt16(n); Console.WriteLine("Conversion is Possible."); } else { Console.WriteLine("Not Possible"); } } }}
Output:
Maximum Value is: 32767
Conversion is Possible.
Conversion is Possible.
Not Possible
Not Possible
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.int16.maxvalue?view=netframework-4.7.2
CSharp-Int16-Struct
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Delegates
C# | Method Overriding
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | Class and Object
C# | Constructors
C# | Replace() Method
Introduction to .NET Framework
C# | Data Types | [
{
"code": null,
"e": 25791,
"s": 25763,
"text": "\n08 Apr, 2019"
},
{
"code": null,
"e": 26199,
"s": 25791,
"text": "The MaxValue field or property of Int16 Struct is used to represent the maximum value of Int16. The value of this field is constant means that the user cannot change the value of this field. The value of this field is 32767. Its hexadecimal value is 0x7FFF. It is used to avoid the OverflowException while converting from a numeric type with a greater upper range (such as a UInt16 or an Int32) to an Int16."
},
{
"code": null,
"e": 26207,
"s": 26199,
"text": "Syntax:"
},
{
"code": null,
"e": 26244,
"s": 26207,
"text": "public const short MaxValue = 32767;"
},
{
"code": null,
"e": 26291,
"s": 26244,
"text": "Return Value: This field always returns 32767."
},
{
"code": null,
"e": 26300,
"s": 26291,
"text": "Example:"
},
{
"code": "// C# program to illustrate the// Int16.MaxValue fieldusing System; class GFG { // Main Method static public void Main() { // display the Maximum value // of Int16 struct Console.WriteLine(\"Maximum Value is: \"+ Int16.MaxValue); // Taking an array of long i.e Int64 data type long[]num = {345, -4677, -65245465445441, 44456564}; // taking variable of Int16 type short mynum; foreach(long n in num){ if(n >= Int16.MinValue && n <= Int16.MaxValue) { // using the method of Convert class // to convert Int64 to Int16 mynum = Convert.ToInt16(n); Console.WriteLine(\"Conversion is Possible.\"); } else { Console.WriteLine(\"Not Possible\"); } } }}",
"e": 27215,
"s": 26300,
"text": null
},
{
"code": null,
"e": 27223,
"s": 27215,
"text": "Output:"
},
{
"code": null,
"e": 27322,
"s": 27223,
"text": "Maximum Value is: 32767\nConversion is Possible.\nConversion is Possible.\nNot Possible\nNot Possible\n"
},
{
"code": null,
"e": 27333,
"s": 27322,
"text": "Reference:"
},
{
"code": null,
"e": 27423,
"s": 27333,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.int16.maxvalue?view=netframework-4.7.2"
},
{
"code": null,
"e": 27443,
"s": 27423,
"text": "CSharp-Int16-Struct"
},
{
"code": null,
"e": 27446,
"s": 27443,
"text": "C#"
},
{
"code": null,
"e": 27544,
"s": 27446,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27559,
"s": 27544,
"text": "C# | Delegates"
},
{
"code": null,
"e": 27582,
"s": 27559,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 27604,
"s": 27582,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 27650,
"s": 27604,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 27673,
"s": 27650,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27695,
"s": 27673,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 27713,
"s": 27695,
"text": "C# | Constructors"
},
{
"code": null,
"e": 27735,
"s": 27713,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 27766,
"s": 27735,
"text": "Introduction to .NET Framework"
}
] |
How to Create an App in Django ? - GeeksforGeeks | 30 Jan, 2022
Prerequisite – How to Create a Basic Project using MVT in Django?
Django is famous for its unique and fully managed app structure. For every functionality, an app can be created like a completely independent module. This article will take you through how to create a basic app and add functionalities using that app.For example, if you are creating a Blog, Separate modules should be created for Comments, Posts, Login/Logout, etc. In Django, these modules are known as apps. There is a different app for each task.
Django apps are reusable i.e. a Django app can be used with multiple projects.
We have loosely coupled i.e. almost independent components
Multiple developers can work on different components
Debugging and code organization is easy. Django has an excellent debugger tool.
It has in-built features like admin pages etc, which reduces the effort of building the same from stratch
Pre-installed apps – Django provides some pre-installed apps for users. To see pre-installed apps, navigate to projectName –> projectName –> settings.py In your settings.py file, you will find INSTALLED_APPS. Apps listed in INSTALLED_APPS are provided by Django for the developer’s comfort.
Also, Visit :Django ORM – Inserting, Updating & Deleting Data
Let us start building an app.
To create a basic app in your Django project you need to go to the directory containing manage.py and from there enter the command :
python manage.py startapp projectApp
To create a basic app in your Django project you need to go to the directory containing manage.py and from there enter the command :
django-admin startapp projectApp
Now you can see your directory structure as under :
To consider the app in your project you need to specify your project name in INSTALLED_APPS list as follows in settings.py:
Python3
# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'projectApp']
So, we have finally created an app but to render the app using URLs we need to include the app in our main project so that URLs redirected to that app can be rendered. Let us explore it. Move to projectName-> projectName -> urls.py and add below code in the header
from django.urls import include
Now in the list of URL patterns, you need to specify the app name for including your app URLs. Here is the code for it –
Python3
from django.contrib import adminfrom django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), # Enter the app name in following # syntax for this to work path('', include("projectApp.urls")),]
Now You can use the default MVT model to create URLs, models, views, etc. in your app and they will be automatically included in your main project.
The main feature of Django Apps is independence, every app functions as an independent unit in supporting the main project.
Now the urls.py in the project file will not access the app’s url.
To run your Django Web application properly the following actions must be taken:-
1. Create a file in the apps directory called urls.py
2. Include the following code:
Python3
from django.urls import path#now import the views.py file into this codefrom . import viewsurlpatterns=[ path('',views.index)
The above code will call or invoke the function which is defined in the views.py file so that it can be seen properly in the Web browser. Here it is assumed that views.py contains the following code :-
Python3
from django.http import HttpResponse def index(request): return HttpResponse("Hello Geeks")
After adding the above code, go to the settings.py file which is in the project directory, and change the value of ROOT_URLCONF from ‘project.urls’ to ‘app.urls’
From this:-
To this:
3. And then you can run the server(127.0.0.1:8000) and you will get the desired output
NaveenArora
utkr98jais
ddeevviissaavviittaa
subhrajitsengupta1
Django-basics
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
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() | [
{
"code": null,
"e": 42675,
"s": 42647,
"text": "\n30 Jan, 2022"
},
{
"code": null,
"e": 42741,
"s": 42675,
"text": "Prerequisite – How to Create a Basic Project using MVT in Django?"
},
{
"code": null,
"e": 43193,
"s": 42741,
"text": "Django is famous for its unique and fully managed app structure. For every functionality, an app can be created like a completely independent module. This article will take you through how to create a basic app and add functionalities using that app.For example, if you are creating a Blog, Separate modules should be created for Comments, Posts, Login/Logout, etc. In Django, these modules are known as apps. There is a different app for each task. "
},
{
"code": null,
"e": 43272,
"s": 43193,
"text": "Django apps are reusable i.e. a Django app can be used with multiple projects."
},
{
"code": null,
"e": 43331,
"s": 43272,
"text": "We have loosely coupled i.e. almost independent components"
},
{
"code": null,
"e": 43384,
"s": 43331,
"text": "Multiple developers can work on different components"
},
{
"code": null,
"e": 43464,
"s": 43384,
"text": "Debugging and code organization is easy. Django has an excellent debugger tool."
},
{
"code": null,
"e": 43570,
"s": 43464,
"text": "It has in-built features like admin pages etc, which reduces the effort of building the same from stratch"
},
{
"code": null,
"e": 43862,
"s": 43570,
"text": "Pre-installed apps – Django provides some pre-installed apps for users. To see pre-installed apps, navigate to projectName –> projectName –> settings.py In your settings.py file, you will find INSTALLED_APPS. Apps listed in INSTALLED_APPS are provided by Django for the developer’s comfort. "
},
{
"code": null,
"e": 43927,
"s": 43864,
"text": "Also, Visit :Django ORM – Inserting, Updating & Deleting Data "
},
{
"code": null,
"e": 43958,
"s": 43927,
"text": "Let us start building an app. "
},
{
"code": null,
"e": 44091,
"s": 43958,
"text": "To create a basic app in your Django project you need to go to the directory containing manage.py and from there enter the command :"
},
{
"code": null,
"e": 44128,
"s": 44091,
"text": "python manage.py startapp projectApp"
},
{
"code": null,
"e": 44261,
"s": 44128,
"text": "To create a basic app in your Django project you need to go to the directory containing manage.py and from there enter the command :"
},
{
"code": null,
"e": 44294,
"s": 44261,
"text": "django-admin startapp projectApp"
},
{
"code": null,
"e": 44347,
"s": 44294,
"text": "Now you can see your directory structure as under : "
},
{
"code": null,
"e": 44471,
"s": 44347,
"text": "To consider the app in your project you need to specify your project name in INSTALLED_APPS list as follows in settings.py:"
},
{
"code": null,
"e": 44479,
"s": 44471,
"text": "Python3"
},
{
"code": "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'projectApp']",
"e": 44720,
"s": 44479,
"text": null
},
{
"code": null,
"e": 44985,
"s": 44720,
"text": "So, we have finally created an app but to render the app using URLs we need to include the app in our main project so that URLs redirected to that app can be rendered. Let us explore it. Move to projectName-> projectName -> urls.py and add below code in the header"
},
{
"code": null,
"e": 45017,
"s": 44985,
"text": "from django.urls import include"
},
{
"code": null,
"e": 45138,
"s": 45017,
"text": "Now in the list of URL patterns, you need to specify the app name for including your app URLs. Here is the code for it –"
},
{
"code": null,
"e": 45146,
"s": 45138,
"text": "Python3"
},
{
"code": "from django.contrib import adminfrom django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), # Enter the app name in following # syntax for this to work path('', include(\"projectApp.urls\")),]",
"e": 45376,
"s": 45146,
"text": null
},
{
"code": null,
"e": 45524,
"s": 45376,
"text": "Now You can use the default MVT model to create URLs, models, views, etc. in your app and they will be automatically included in your main project."
},
{
"code": null,
"e": 45649,
"s": 45524,
"text": "The main feature of Django Apps is independence, every app functions as an independent unit in supporting the main project. "
},
{
"code": null,
"e": 45716,
"s": 45649,
"text": "Now the urls.py in the project file will not access the app’s url."
},
{
"code": null,
"e": 45798,
"s": 45716,
"text": "To run your Django Web application properly the following actions must be taken:-"
},
{
"code": null,
"e": 45852,
"s": 45798,
"text": "1. Create a file in the apps directory called urls.py"
},
{
"code": null,
"e": 45883,
"s": 45852,
"text": "2. Include the following code:"
},
{
"code": null,
"e": 45891,
"s": 45883,
"text": "Python3"
},
{
"code": "from django.urls import path#now import the views.py file into this codefrom . import viewsurlpatterns=[ path('',views.index)",
"e": 46018,
"s": 45891,
"text": null
},
{
"code": null,
"e": 46221,
"s": 46018,
"text": "The above code will call or invoke the function which is defined in the views.py file so that it can be seen properly in the Web browser. Here it is assumed that views.py contains the following code :- "
},
{
"code": null,
"e": 46229,
"s": 46221,
"text": "Python3"
},
{
"code": "from django.http import HttpResponse def index(request): return HttpResponse(\"Hello Geeks\")",
"e": 46323,
"s": 46229,
"text": null
},
{
"code": null,
"e": 46485,
"s": 46323,
"text": "After adding the above code, go to the settings.py file which is in the project directory, and change the value of ROOT_URLCONF from ‘project.urls’ to ‘app.urls’"
},
{
"code": null,
"e": 46497,
"s": 46485,
"text": "From this:-"
},
{
"code": null,
"e": 46506,
"s": 46497,
"text": "To this:"
},
{
"code": null,
"e": 46593,
"s": 46506,
"text": "3. And then you can run the server(127.0.0.1:8000) and you will get the desired output"
},
{
"code": null,
"e": 46605,
"s": 46593,
"text": "NaveenArora"
},
{
"code": null,
"e": 46616,
"s": 46605,
"text": "utkr98jais"
},
{
"code": null,
"e": 46637,
"s": 46616,
"text": "ddeevviissaavviittaa"
},
{
"code": null,
"e": 46656,
"s": 46637,
"text": "subhrajitsengupta1"
},
{
"code": null,
"e": 46670,
"s": 46656,
"text": "Django-basics"
},
{
"code": null,
"e": 46684,
"s": 46670,
"text": "Python Django"
},
{
"code": null,
"e": 46691,
"s": 46684,
"text": "Python"
},
{
"code": null,
"e": 46789,
"s": 46691,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 46817,
"s": 46789,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 46867,
"s": 46817,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 46889,
"s": 46867,
"text": "Python map() function"
},
{
"code": null,
"e": 46933,
"s": 46889,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 46968,
"s": 46933,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 47000,
"s": 46968,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 47022,
"s": 47000,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 47064,
"s": 47022,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 47094,
"s": 47064,
"text": "Iterate over a list in Python"
}
] |
PyQt5 – How to stop resizing of window | setFixedSize() method - GeeksforGeeks | 26 Mar, 2020
In this article, we will see how to stop resizing of the main window. While making a window, we get options like going full screen and using cursor to change its size. By using setFizedSize() method we can prevent the resizing of the image.
Syntax : self.setFixedSize(width, height)
Argument : It takes two integer as argument i.e width and height.
Action performed : It set the fixed size of window.
Code :
# importing the required libraries from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle("Python") width = 500 height = 400 # setting the fixed size of window self.setFixedSize(width, height) # creating a label widget self.label_1 = QLabel("Fixed size window", self) # moving position self.label_1.move(100, 100) # setting up the border self.label_1.setStyleSheet("border :3px solid black;") # resizing label self.label_1.resize(120, 80) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
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()
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python | [
{
"code": null,
"e": 26217,
"s": 26189,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 26458,
"s": 26217,
"text": "In this article, we will see how to stop resizing of the main window. While making a window, we get options like going full screen and using cursor to change its size. By using setFizedSize() method we can prevent the resizing of the image."
},
{
"code": null,
"e": 26500,
"s": 26458,
"text": "Syntax : self.setFixedSize(width, height)"
},
{
"code": null,
"e": 26566,
"s": 26500,
"text": "Argument : It takes two integer as argument i.e width and height."
},
{
"code": null,
"e": 26618,
"s": 26566,
"text": "Action performed : It set the fixed size of window."
},
{
"code": null,
"e": 26625,
"s": 26618,
"text": "Code :"
},
{
"code": "# importing the required libraries from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle(\"Python\") width = 500 height = 400 # setting the fixed size of window self.setFixedSize(width, height) # creating a label widget self.label_1 = QLabel(\"Fixed size window\", self) # moving position self.label_1.move(100, 100) # setting up the border self.label_1.setStyleSheet(\"border :3px solid black;\") # resizing label self.label_1.resize(120, 80) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 27524,
"s": 26625,
"text": null
},
{
"code": null,
"e": 27533,
"s": 27524,
"text": "Output :"
},
{
"code": null,
"e": 27544,
"s": 27533,
"text": "Python-gui"
},
{
"code": null,
"e": 27556,
"s": 27544,
"text": "Python-PyQt"
},
{
"code": null,
"e": 27563,
"s": 27556,
"text": "Python"
},
{
"code": null,
"e": 27661,
"s": 27563,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27679,
"s": 27661,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27714,
"s": 27679,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27746,
"s": 27714,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27768,
"s": 27746,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27810,
"s": 27768,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27840,
"s": 27810,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27866,
"s": 27840,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27910,
"s": 27866,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 27939,
"s": 27910,
"text": "*args and **kwargs in Python"
}
] |
ML | Stochastic Gradient Descent (SGD) - GeeksforGeeks | 13 Sep, 2021
What is Gradient Descent? Before explaining Stochastic Gradient Descent (SGD), let’s first describe what Gradient Descent is. Gradient Descent is a popular optimization technique in Machine Learning and Deep Learning, and it can be used with most, if not all, of the learning algorithms. A gradient is the slope of a function. It measures the degree of change of a variable in response to the changes of another variable. Mathematically, Gradient Descent is a convex function whose output is the partial derivative of a set of parameters of its inputs. The greater the gradient, the steeper the slope.
Starting from an initial value, Gradient Descent is run iteratively to find the optimal values of the parameters to find the minimum possible value of the given cost function.
Types of Gradient Descent: Typically, there are three types of Gradient Descent:
Batch Gradient DescentStochastic Gradient DescentMini-batch Gradient Descent
Batch Gradient Descent
Stochastic Gradient Descent
Mini-batch Gradient Descent
In this article, we will be discussing Stochastic Gradient Descent or SGD.
The word ‘stochastic‘ means a system or a process that is linked with a random probability. Hence, in Stochastic Gradient Descent, a few samples are selected randomly instead of the whole data set for each iteration. In Gradient Descent, there is a term called “batch” which denotes the total number of samples from a dataset that is used for calculating the gradient for each iteration. In typical Gradient Descent optimization, like Batch Gradient Descent, the batch is taken to be the whole dataset. Although, using the whole dataset is really useful for getting to the minima in a less noisy and less random manner, but the problem arises when our datasets get big. Suppose, you have a million samples in your dataset, so if you use a typical Gradient Descent optimization technique, you will have to use all of the one million samples for completing one iteration while performing the Gradient Descent, and it has to be done for every iteration until the minima are reached. Hence, it becomes computationally very expensive to perform.This problem is solved by Stochastic Gradient Descent. In SGD, it uses only a single sample, i.e., a batch size of one, to perform each iteration. The sample is randomly shuffled and selected for performing the iteration.
SGD algorithm: So, in SGD, we find out the gradient of the cost function of a single example at each iteration instead of the sum of the gradient of the cost function of all the examples.
In SGD, since only one sample from the dataset is chosen at random for each iteration, the path taken by the algorithm to reach the minima is usually noisier than your typical Gradient Descent algorithm. But that doesn’t matter all that much because the path taken by the algorithm does not matter, as long as we reach the minima and with a significantly shorter training time.
The path took by Batch Gradient Descent –
A path has been taken by Stochastic Gradient Descent –
One thing to be noted is that, as SGD is generally noisier than typical Gradient Descent, it usually took a higher number of iterations to reach the minima, because of its randomness in its descent. Even though it requires a higher number of iterations to reach the minima than typical Gradient Descent, it is still computationally much less expensive than typical Gradient Descent. Hence, in most scenarios, SGD is preferred over Batch Gradient Descent for optimizing a learning algorithm.
Pseudocode for SGD in Python:
Python3
def SGD(f, theta0, alpha, num_iters): """ Arguments: f -- the function to optimize, it takes a single argument and yield two outputs, a cost and the gradient with respect to the arguments theta0 -- the initial point to start SGD from num_iters -- total iterations to run SGD for Return: theta -- the parameter value after SGD finishes """ start_iter = 0 theta = theta0 for iter in xrange(start_iter + 1, num_iters + 1): _, grad = f(theta) # there is NO dot product ! return theta theta = theta - (alpha * grad)
This cycle of taking the values and adjusting them based on different parameters in order to reduce the loss function is called back-propagation.
philhersh
tanwarsinghvaibhav
Advanced Computer Subject
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
System Design Tutorial
Copying Files to and from Docker Containers
ML | Underfitting and Overfitting
Clustering in Machine Learning
Docker - COPY Instruction
Agents in Artificial Intelligence
Activation functions in Neural Networks
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
ML | Underfitting and Overfitting | [
{
"code": null,
"e": 25761,
"s": 25733,
"text": "\n13 Sep, 2021"
},
{
"code": null,
"e": 26363,
"s": 25761,
"text": "What is Gradient Descent? Before explaining Stochastic Gradient Descent (SGD), let’s first describe what Gradient Descent is. Gradient Descent is a popular optimization technique in Machine Learning and Deep Learning, and it can be used with most, if not all, of the learning algorithms. A gradient is the slope of a function. It measures the degree of change of a variable in response to the changes of another variable. Mathematically, Gradient Descent is a convex function whose output is the partial derivative of a set of parameters of its inputs. The greater the gradient, the steeper the slope."
},
{
"code": null,
"e": 26539,
"s": 26363,
"text": "Starting from an initial value, Gradient Descent is run iteratively to find the optimal values of the parameters to find the minimum possible value of the given cost function."
},
{
"code": null,
"e": 26622,
"s": 26539,
"text": "Types of Gradient Descent: Typically, there are three types of Gradient Descent: "
},
{
"code": null,
"e": 26699,
"s": 26622,
"text": "Batch Gradient DescentStochastic Gradient DescentMini-batch Gradient Descent"
},
{
"code": null,
"e": 26722,
"s": 26699,
"text": "Batch Gradient Descent"
},
{
"code": null,
"e": 26750,
"s": 26722,
"text": "Stochastic Gradient Descent"
},
{
"code": null,
"e": 26778,
"s": 26750,
"text": "Mini-batch Gradient Descent"
},
{
"code": null,
"e": 26854,
"s": 26778,
"text": "In this article, we will be discussing Stochastic Gradient Descent or SGD. "
},
{
"code": null,
"e": 28116,
"s": 26854,
"text": "The word ‘stochastic‘ means a system or a process that is linked with a random probability. Hence, in Stochastic Gradient Descent, a few samples are selected randomly instead of the whole data set for each iteration. In Gradient Descent, there is a term called “batch” which denotes the total number of samples from a dataset that is used for calculating the gradient for each iteration. In typical Gradient Descent optimization, like Batch Gradient Descent, the batch is taken to be the whole dataset. Although, using the whole dataset is really useful for getting to the minima in a less noisy and less random manner, but the problem arises when our datasets get big. Suppose, you have a million samples in your dataset, so if you use a typical Gradient Descent optimization technique, you will have to use all of the one million samples for completing one iteration while performing the Gradient Descent, and it has to be done for every iteration until the minima are reached. Hence, it becomes computationally very expensive to perform.This problem is solved by Stochastic Gradient Descent. In SGD, it uses only a single sample, i.e., a batch size of one, to perform each iteration. The sample is randomly shuffled and selected for performing the iteration."
},
{
"code": null,
"e": 28304,
"s": 28116,
"text": "SGD algorithm: So, in SGD, we find out the gradient of the cost function of a single example at each iteration instead of the sum of the gradient of the cost function of all the examples."
},
{
"code": null,
"e": 28682,
"s": 28304,
"text": "In SGD, since only one sample from the dataset is chosen at random for each iteration, the path taken by the algorithm to reach the minima is usually noisier than your typical Gradient Descent algorithm. But that doesn’t matter all that much because the path taken by the algorithm does not matter, as long as we reach the minima and with a significantly shorter training time."
},
{
"code": null,
"e": 28726,
"s": 28682,
"text": "The path took by Batch Gradient Descent – "
},
{
"code": null,
"e": 28783,
"s": 28726,
"text": "A path has been taken by Stochastic Gradient Descent – "
},
{
"code": null,
"e": 29274,
"s": 28783,
"text": "One thing to be noted is that, as SGD is generally noisier than typical Gradient Descent, it usually took a higher number of iterations to reach the minima, because of its randomness in its descent. Even though it requires a higher number of iterations to reach the minima than typical Gradient Descent, it is still computationally much less expensive than typical Gradient Descent. Hence, in most scenarios, SGD is preferred over Batch Gradient Descent for optimizing a learning algorithm."
},
{
"code": null,
"e": 29305,
"s": 29274,
"text": "Pseudocode for SGD in Python: "
},
{
"code": null,
"e": 29313,
"s": 29305,
"text": "Python3"
},
{
"code": "def SGD(f, theta0, alpha, num_iters): \"\"\" Arguments: f -- the function to optimize, it takes a single argument and yield two outputs, a cost and the gradient with respect to the arguments theta0 -- the initial point to start SGD from num_iters -- total iterations to run SGD for Return: theta -- the parameter value after SGD finishes \"\"\" start_iter = 0 theta = theta0 for iter in xrange(start_iter + 1, num_iters + 1): _, grad = f(theta) # there is NO dot product ! return theta theta = theta - (alpha * grad)",
"e": 29920,
"s": 29313,
"text": null
},
{
"code": null,
"e": 30067,
"s": 29920,
"text": "This cycle of taking the values and adjusting them based on different parameters in order to reduce the loss function is called back-propagation. "
},
{
"code": null,
"e": 30077,
"s": 30067,
"text": "philhersh"
},
{
"code": null,
"e": 30096,
"s": 30077,
"text": "tanwarsinghvaibhav"
},
{
"code": null,
"e": 30122,
"s": 30096,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 30139,
"s": 30122,
"text": "Machine Learning"
},
{
"code": null,
"e": 30156,
"s": 30139,
"text": "Machine Learning"
},
{
"code": null,
"e": 30254,
"s": 30156,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30277,
"s": 30254,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 30321,
"s": 30277,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 30355,
"s": 30321,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 30386,
"s": 30355,
"text": "Clustering in Machine Learning"
},
{
"code": null,
"e": 30412,
"s": 30386,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 30446,
"s": 30412,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 30486,
"s": 30446,
"text": "Activation functions in Neural Networks"
},
{
"code": null,
"e": 30527,
"s": 30486,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 30560,
"s": 30527,
"text": "Support Vector Machine Algorithm"
}
] |
Python | os._exit() method - GeeksforGeeks | 10 May, 2022
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os._exit() method in Python is used to exit the process with specified status without calling cleanup handlers, flushing stdio buffers, etc. Note: This method is normally used in child process after os.fork() system call. The standard way to exit the process is sys.exit(n) method.
Syntax: os._exit(status)
Parameter: status: An integer value or above defined values representing the exit status.
Return type: This method does not return any value in the calling process.
Code: Use of os._exit() method
Python3
# Python program to explain os._exit() method # importing os module import os # Create a child process# using os.fork() methodpid = os.fork() # pid greater than 0# indicates the parent processif pid > 0: print("\nIn parent process") # Wait for the completion # of child process and # get its pid and # exit status indication using # os.wait() method info = os.waitpid(pid, 0) # os.waitpid() method returns a tuple # first attribute represents child's pid # while second one represents # exit status indication # Get the Exit code # used by the child process # in os._exit() method # firstly check if # os.WIFEXITED() is True or not if os.WIFEXITED(info[1]) : code = os.WEXITSTATUS(info[1]) print("Child's exit code:", code) else : print("In child process") print("Process ID:", os.getpid()) print("Hello ! Geeks") print("Child exiting..") # Exit with status os.EX_OK # using os._exit() method # The value of os.EX_OK is 0 os._exit(os.EX_OK)
In child process
Process ID: 15240
Hello! Geeks
Child exiting..
In parent process
Child's exit code: 0
References: https://docs.python.org/3/library/os.html#os._exit
surinderdawra388
python-os-module
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": 25833,
"s": 25805,
"text": "\n10 May, 2022"
},
{
"code": null,
"e": 26334,
"s": 25833,
"text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os._exit() method in Python is used to exit the process with specified status without calling cleanup handlers, flushing stdio buffers, etc. Note: This method is normally used in child process after os.fork() system call. The standard way to exit the process is sys.exit(n) method."
},
{
"code": null,
"e": 26360,
"s": 26334,
"text": "Syntax: os._exit(status) "
},
{
"code": null,
"e": 26451,
"s": 26360,
"text": "Parameter: status: An integer value or above defined values representing the exit status. "
},
{
"code": null,
"e": 26526,
"s": 26451,
"text": "Return type: This method does not return any value in the calling process."
},
{
"code": null,
"e": 26558,
"s": 26526,
"text": "Code: Use of os._exit() method "
},
{
"code": null,
"e": 26566,
"s": 26558,
"text": "Python3"
},
{
"code": "# Python program to explain os._exit() method # importing os module import os # Create a child process# using os.fork() methodpid = os.fork() # pid greater than 0# indicates the parent processif pid > 0: print(\"\\nIn parent process\") # Wait for the completion # of child process and # get its pid and # exit status indication using # os.wait() method info = os.waitpid(pid, 0) # os.waitpid() method returns a tuple # first attribute represents child's pid # while second one represents # exit status indication # Get the Exit code # used by the child process # in os._exit() method # firstly check if # os.WIFEXITED() is True or not if os.WIFEXITED(info[1]) : code = os.WEXITSTATUS(info[1]) print(\"Child's exit code:\", code) else : print(\"In child process\") print(\"Process ID:\", os.getpid()) print(\"Hello ! Geeks\") print(\"Child exiting..\") # Exit with status os.EX_OK # using os._exit() method # The value of os.EX_OK is 0 os._exit(os.EX_OK)",
"e": 27625,
"s": 26566,
"text": null
},
{
"code": null,
"e": 27730,
"s": 27625,
"text": "In child process\nProcess ID: 15240\nHello! Geeks\nChild exiting..\n\n\nIn parent process\nChild's exit code: 0"
},
{
"code": null,
"e": 27793,
"s": 27730,
"text": "References: https://docs.python.org/3/library/os.html#os._exit"
},
{
"code": null,
"e": 27810,
"s": 27793,
"text": "surinderdawra388"
},
{
"code": null,
"e": 27827,
"s": 27810,
"text": "python-os-module"
},
{
"code": null,
"e": 27834,
"s": 27827,
"text": "Python"
},
{
"code": null,
"e": 27932,
"s": 27834,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27950,
"s": 27932,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27985,
"s": 27950,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28017,
"s": 27985,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28039,
"s": 28017,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28081,
"s": 28039,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28111,
"s": 28081,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28137,
"s": 28111,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28166,
"s": 28137,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28210,
"s": 28166,
"text": "Reading and Writing to text files in Python"
}
] |
How to set the Size of the GroupBox in C#? - GeeksforGeeks | 29 Jul, 2019
In Windows form, GroupBox is a container which contains multiple controls in it and the controls are related to each other. Or in other words, GroupBox is a frame display around a group of controls with a suitable optional title. Or a GroupBox is used to categorize the related controls in a group. In GroupBox, you can set the size of the GroupBox in the form using the Size Property.This property represents both the height and width of the GroupBox in pixels. You can set this property in two different ways:
1. Design-Time: It is the easiest way to set the size of the GroupBox as shown in the following steps:
Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp
Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Next, drag and drop the GroupBox from the toolbox to the form as shown in the below image:
Step 3: After drag and drop you will go to the properties of the GroupBox and set the size of the GroupBox as shown in the below image:Output:
Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the size of the GroupBox programmatically with the help of given syntax:
public System.Drawing.Size Size { get; set; }
Here, Size indicates the height and width of the GroupBox in pixels. The following steps show how to set the size of the GroupBox dynamically:
Step 1: Create a GroupBox using the GroupBox() constructor is provided by the GroupBox class.// Creating a GroupBox
GroupBox gbox = new GroupBox();
// Creating a GroupBox
GroupBox gbox = new GroupBox();
Step 2: After creating GroupBox, set the Size property of the GroupBox provided by the GroupBox class.// Setting the size
gbox.Size = new Size(329, 94);
// Setting the size
gbox.Size = new Size(329, 94);
Step 3: And last add this GroupBox control to the form and also add other controls on the GroupBox using the following statements:// Adding groupbox in the form
this.Controls.Add(gbox);
and
// Adding this control
// to the GroupBox
gbox.Controls.Add(c2);
Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp45 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting properties // of the GroupBox GroupBox gbox = new GroupBox(); gbox.Location = new Point(179, 145); gbox.Size = new Size(329, 94); gbox.Text = "Select Gender"; gbox.Name = "Mybox"; // Adding groupbox in the form this.Controls.Add(gbox); // Creating and setting // properties of the CheckBox CheckBox c1 = new CheckBox(); c1.Location = new Point(40, 42); c1.Size = new Size(49, 20); c1.Text = "Male"; // Adding this control // to the GroupBox gbox.Controls.Add(c1); // Creating and setting // properties of the CheckBox CheckBox c2 = new CheckBox(); c2.Location = new Point(183, 39); c2.Size = new Size(69, 20); c2.Text = "Female"; // Adding this control // to the GroupBox gbox.Controls.Add(c2); }}}Output:
// Adding groupbox in the form
this.Controls.Add(gbox);
and
// Adding this control
// to the GroupBox
gbox.Controls.Add(c2);
Example:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp45 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting properties // of the GroupBox GroupBox gbox = new GroupBox(); gbox.Location = new Point(179, 145); gbox.Size = new Size(329, 94); gbox.Text = "Select Gender"; gbox.Name = "Mybox"; // Adding groupbox in the form this.Controls.Add(gbox); // Creating and setting // properties of the CheckBox CheckBox c1 = new CheckBox(); c1.Location = new Point(40, 42); c1.Size = new Size(49, 20); c1.Text = "Male"; // Adding this control // to the GroupBox gbox.Controls.Add(c1); // Creating and setting // properties of the CheckBox CheckBox c2 = new CheckBox(); c2.Location = new Point(183, 39); c2.Size = new Size(69, 20); c2.Text = "Female"; // Adding this control // to the GroupBox gbox.Controls.Add(c2); }}}
Output:
CSharp-Windows-Forms-Namespace
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
C# | Method Overriding
C# | Abstract Classes
Difference between Ref and Out keywords in C#
C# | Class and Object
C# | Constructors
Extension Method in C#
Introduction to .NET Framework
C# | String.IndexOf( ) Method | Set - 1 | [
{
"code": null,
"e": 25449,
"s": 25421,
"text": "\n29 Jul, 2019"
},
{
"code": null,
"e": 25961,
"s": 25449,
"text": "In Windows form, GroupBox is a container which contains multiple controls in it and the controls are related to each other. Or in other words, GroupBox is a frame display around a group of controls with a suitable optional title. Or a GroupBox is used to categorize the related controls in a group. In GroupBox, you can set the size of the GroupBox in the form using the Size Property.This property represents both the height and width of the GroupBox in pixels. You can set this property in two different ways:"
},
{
"code": null,
"e": 26064,
"s": 25961,
"text": "1. Design-Time: It is the easiest way to set the size of the GroupBox as shown in the following steps:"
},
{
"code": null,
"e": 26180,
"s": 26064,
"text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp"
},
{
"code": null,
"e": 26238,
"s": 26180,
"text": "Visual Studio -> File -> New -> Project -> WindowsFormApp"
},
{
"code": null,
"e": 26337,
"s": 26238,
"text": "Step 2: Next, drag and drop the GroupBox from the toolbox to the form as shown in the below image:"
},
{
"code": null,
"e": 26480,
"s": 26337,
"text": "Step 3: After drag and drop you will go to the properties of the GroupBox and set the size of the GroupBox as shown in the below image:Output:"
},
{
"code": null,
"e": 26488,
"s": 26480,
"text": "Output:"
},
{
"code": null,
"e": 26653,
"s": 26488,
"text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the size of the GroupBox programmatically with the help of given syntax:"
},
{
"code": null,
"e": 26699,
"s": 26653,
"text": "public System.Drawing.Size Size { get; set; }"
},
{
"code": null,
"e": 26842,
"s": 26699,
"text": "Here, Size indicates the height and width of the GroupBox in pixels. The following steps show how to set the size of the GroupBox dynamically:"
},
{
"code": null,
"e": 26992,
"s": 26842,
"text": "Step 1: Create a GroupBox using the GroupBox() constructor is provided by the GroupBox class.// Creating a GroupBox\nGroupBox gbox = new GroupBox(); \n"
},
{
"code": null,
"e": 27049,
"s": 26992,
"text": "// Creating a GroupBox\nGroupBox gbox = new GroupBox(); \n"
},
{
"code": null,
"e": 27203,
"s": 27049,
"text": "Step 2: After creating GroupBox, set the Size property of the GroupBox provided by the GroupBox class.// Setting the size\ngbox.Size = new Size(329, 94);\n"
},
{
"code": null,
"e": 27255,
"s": 27203,
"text": "// Setting the size\ngbox.Size = new Size(329, 94);\n"
},
{
"code": null,
"e": 28853,
"s": 27255,
"text": "Step 3: And last add this GroupBox control to the form and also add other controls on the GroupBox using the following statements:// Adding groupbox in the form\nthis.Controls.Add(gbox);\n\nand \n\n// Adding this control \n// to the GroupBox\ngbox.Controls.Add(c2);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp45 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting properties // of the GroupBox GroupBox gbox = new GroupBox(); gbox.Location = new Point(179, 145); gbox.Size = new Size(329, 94); gbox.Text = \"Select Gender\"; gbox.Name = \"Mybox\"; // Adding groupbox in the form this.Controls.Add(gbox); // Creating and setting // properties of the CheckBox CheckBox c1 = new CheckBox(); c1.Location = new Point(40, 42); c1.Size = new Size(49, 20); c1.Text = \"Male\"; // Adding this control // to the GroupBox gbox.Controls.Add(c1); // Creating and setting // properties of the CheckBox CheckBox c2 = new CheckBox(); c2.Location = new Point(183, 39); c2.Size = new Size(69, 20); c2.Text = \"Female\"; // Adding this control // to the GroupBox gbox.Controls.Add(c2); }}}Output:"
},
{
"code": null,
"e": 28983,
"s": 28853,
"text": "// Adding groupbox in the form\nthis.Controls.Add(gbox);\n\nand \n\n// Adding this control \n// to the GroupBox\ngbox.Controls.Add(c2);\n"
},
{
"code": null,
"e": 28992,
"s": 28983,
"text": "Example:"
},
{
"code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp45 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting properties // of the GroupBox GroupBox gbox = new GroupBox(); gbox.Location = new Point(179, 145); gbox.Size = new Size(329, 94); gbox.Text = \"Select Gender\"; gbox.Name = \"Mybox\"; // Adding groupbox in the form this.Controls.Add(gbox); // Creating and setting // properties of the CheckBox CheckBox c1 = new CheckBox(); c1.Location = new Point(40, 42); c1.Size = new Size(49, 20); c1.Text = \"Male\"; // Adding this control // to the GroupBox gbox.Controls.Add(c1); // Creating and setting // properties of the CheckBox CheckBox c2 = new CheckBox(); c2.Location = new Point(183, 39); c2.Size = new Size(69, 20); c2.Text = \"Female\"; // Adding this control // to the GroupBox gbox.Controls.Add(c2); }}}",
"e": 30316,
"s": 28992,
"text": null
},
{
"code": null,
"e": 30324,
"s": 30316,
"text": "Output:"
},
{
"code": null,
"e": 30355,
"s": 30324,
"text": "CSharp-Windows-Forms-Namespace"
},
{
"code": null,
"e": 30358,
"s": 30355,
"text": "C#"
},
{
"code": null,
"e": 30456,
"s": 30358,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30484,
"s": 30456,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 30499,
"s": 30484,
"text": "C# | Delegates"
},
{
"code": null,
"e": 30522,
"s": 30499,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 30544,
"s": 30522,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 30590,
"s": 30544,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 30612,
"s": 30590,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 30630,
"s": 30612,
"text": "C# | Constructors"
},
{
"code": null,
"e": 30653,
"s": 30630,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 30684,
"s": 30653,
"text": "Introduction to .NET Framework"
}
] |
Matplotlib.pyplot.hist() in Python - GeeksforGeeks | 21 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface.
The hist() function in pyplot module of matplotlib library is used to plot a histogram.
Syntax: matplotlib.pyplot.hist(x, bins=None, range=None, density=False, weights=None, cumulative=False, bottom=None, histtype=’bar’, align=’mid’, orientation=’vertical’, rwidth=None, log=False, color=None, label=None, stacked=False, \*, data=None, \*\*kwargs)
Parameters: This method accept the following parameters that are described below:
x : This parameter are the sequence of data.
bins : This parameter is an optional parameter and it contains the integer or sequence or string.
range : This parameter is an optional parameter and it the lower and upper range of the bins.
density : This parameter is an optional parameter and it contains the boolean values.
weights : This parameter is an optional parameter and it is an array of weights, of the same shape as x.
bottom : This parameter is the location of the bottom baseline of each bin.
histtype : This parameter is an optional parameter and it is used to draw type of histogram. {‘bar’, ‘barstacked’, ‘step’, ‘stepfilled’}
align : This parameter is an optional parameter and it controls how the histogram is plotted. {‘left’, ‘mid’, ‘right’}
rwidth : This parameter is an optional parameter and it is a relative width of the bars as a fraction of the bin width
log : This parameter is an optional parameter and it is used to set histogram axis to a log scale
color : This parameter is an optional parameter and it is a color spec or sequence of color specs, one per dataset.
label : This parameter is an optional parameter and it is a string, or sequence of strings to match multiple datasets.
normed : This parameter is an optional parameter and it contains the boolean values.It uses the density keyword argument instead.
Returns: This returns the following:
n :This returns the values of the histogram bins.
bins :This returns the edges of the bins.
patches :This returns the list of individual patches used to create the histogram.
Below examples illustrate the matplotlib.pyplot.hist() function in matplotlib.pyplot:
Example #1:
# Implementation of matplotlib functionimport matplotlibimport numpy as npimport matplotlib.pyplot as plt np.random.seed(10**7)mu = 121 sigma = 21x = mu + sigma * np.random.randn(1000) num_bins = 100 n, bins, patches = plt.hist(x, num_bins, density = 1, color ='green', alpha = 0.7) y = ((1 / (np.sqrt(2 * np.pi) * sigma)) * np.exp(-0.5 * (1 / sigma * (bins - mu))**2)) plt.plot(bins, y, '--', color ='black') plt.xlabel('X-Axis')plt.ylabel('Y-Axis') plt.title('matplotlib.pyplot.hist() function Example\n\n', fontweight ="bold") plt.show()
Output:
Example #2:
# Implementation of matplotlib functionimport matplotlibimport numpy as npimport matplotlib.pyplot as plt np.random.seed(10**7)n_bins = 20x = np.random.randn(10000, 3) colors = ['green', 'blue', 'lime'] plt.hist(x, n_bins, density = True, histtype ='bar', color = colors, label = colors) plt.legend(prop ={'size': 10}) plt.title('matplotlib.pyplot.hist() function Example\n\n', fontweight ="bold") plt.show()
Output:
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 ?
Enumerate() in Python
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Convert integer to string in Python
sum() function in Python
isupper(), islower(), lower(), upper() in Python and their applications | [
{
"code": null,
"e": 25927,
"s": 25899,
"text": "\n21 Apr, 2020"
},
{
"code": null,
"e": 26122,
"s": 25927,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface."
},
{
"code": null,
"e": 26210,
"s": 26122,
"text": "The hist() function in pyplot module of matplotlib library is used to plot a histogram."
},
{
"code": null,
"e": 26470,
"s": 26210,
"text": "Syntax: matplotlib.pyplot.hist(x, bins=None, range=None, density=False, weights=None, cumulative=False, bottom=None, histtype=’bar’, align=’mid’, orientation=’vertical’, rwidth=None, log=False, color=None, label=None, stacked=False, \\*, data=None, \\*\\*kwargs)"
},
{
"code": null,
"e": 26552,
"s": 26470,
"text": "Parameters: This method accept the following parameters that are described below:"
},
{
"code": null,
"e": 26597,
"s": 26552,
"text": "x : This parameter are the sequence of data."
},
{
"code": null,
"e": 26695,
"s": 26597,
"text": "bins : This parameter is an optional parameter and it contains the integer or sequence or string."
},
{
"code": null,
"e": 26789,
"s": 26695,
"text": "range : This parameter is an optional parameter and it the lower and upper range of the bins."
},
{
"code": null,
"e": 26875,
"s": 26789,
"text": "density : This parameter is an optional parameter and it contains the boolean values."
},
{
"code": null,
"e": 26980,
"s": 26875,
"text": "weights : This parameter is an optional parameter and it is an array of weights, of the same shape as x."
},
{
"code": null,
"e": 27056,
"s": 26980,
"text": "bottom : This parameter is the location of the bottom baseline of each bin."
},
{
"code": null,
"e": 27193,
"s": 27056,
"text": "histtype : This parameter is an optional parameter and it is used to draw type of histogram. {‘bar’, ‘barstacked’, ‘step’, ‘stepfilled’}"
},
{
"code": null,
"e": 27312,
"s": 27193,
"text": "align : This parameter is an optional parameter and it controls how the histogram is plotted. {‘left’, ‘mid’, ‘right’}"
},
{
"code": null,
"e": 27431,
"s": 27312,
"text": "rwidth : This parameter is an optional parameter and it is a relative width of the bars as a fraction of the bin width"
},
{
"code": null,
"e": 27529,
"s": 27431,
"text": "log : This parameter is an optional parameter and it is used to set histogram axis to a log scale"
},
{
"code": null,
"e": 27645,
"s": 27529,
"text": "color : This parameter is an optional parameter and it is a color spec or sequence of color specs, one per dataset."
},
{
"code": null,
"e": 27764,
"s": 27645,
"text": "label : This parameter is an optional parameter and it is a string, or sequence of strings to match multiple datasets."
},
{
"code": null,
"e": 27894,
"s": 27764,
"text": "normed : This parameter is an optional parameter and it contains the boolean values.It uses the density keyword argument instead."
},
{
"code": null,
"e": 27931,
"s": 27894,
"text": "Returns: This returns the following:"
},
{
"code": null,
"e": 27981,
"s": 27931,
"text": "n :This returns the values of the histogram bins."
},
{
"code": null,
"e": 28023,
"s": 27981,
"text": "bins :This returns the edges of the bins."
},
{
"code": null,
"e": 28106,
"s": 28023,
"text": "patches :This returns the list of individual patches used to create the histogram."
},
{
"code": null,
"e": 28192,
"s": 28106,
"text": "Below examples illustrate the matplotlib.pyplot.hist() function in matplotlib.pyplot:"
},
{
"code": null,
"e": 28204,
"s": 28192,
"text": "Example #1:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlibimport numpy as npimport matplotlib.pyplot as plt np.random.seed(10**7)mu = 121 sigma = 21x = mu + sigma * np.random.randn(1000) num_bins = 100 n, bins, patches = plt.hist(x, num_bins, density = 1, color ='green', alpha = 0.7) y = ((1 / (np.sqrt(2 * np.pi) * sigma)) * np.exp(-0.5 * (1 / sigma * (bins - mu))**2)) plt.plot(bins, y, '--', color ='black') plt.xlabel('X-Axis')plt.ylabel('Y-Axis') plt.title('matplotlib.pyplot.hist() function Example\\n\\n', fontweight =\"bold\") plt.show()",
"e": 28853,
"s": 28204,
"text": null
},
{
"code": null,
"e": 28861,
"s": 28853,
"text": "Output:"
},
{
"code": null,
"e": 28873,
"s": 28861,
"text": "Example #2:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlibimport numpy as npimport matplotlib.pyplot as plt np.random.seed(10**7)n_bins = 20x = np.random.randn(10000, 3) colors = ['green', 'blue', 'lime'] plt.hist(x, n_bins, density = True, histtype ='bar', color = colors, label = colors) plt.legend(prop ={'size': 10}) plt.title('matplotlib.pyplot.hist() function Example\\n\\n', fontweight =\"bold\") plt.show()",
"e": 29326,
"s": 28873,
"text": null
},
{
"code": null,
"e": 29334,
"s": 29326,
"text": "Output:"
},
{
"code": null,
"e": 29352,
"s": 29334,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 29359,
"s": 29352,
"text": "Python"
},
{
"code": null,
"e": 29457,
"s": 29359,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29489,
"s": 29457,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29511,
"s": 29489,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29553,
"s": 29511,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29582,
"s": 29553,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 29619,
"s": 29582,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 29661,
"s": 29619,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29703,
"s": 29661,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29739,
"s": 29703,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 29764,
"s": 29739,
"text": "sum() function in Python"
}
] |
Attribute Closure Algorithm and its Utilization - GeeksforGeeks | 18 Sep, 2020
Closure of a set F of FDs is the set F+ of all FDs that can be inferred from F. It is also known as complete set of Functional Dependency. It is denoted by F+.
Algorithm : Attribute Closure set
Algorithm to compute a+, the closure of a under F
Result:= a;
while (changes to Result) do
for each B → Y in F do
Begin
if B ⊆ Result then Result := Result ∪ Y
End
Utilization of Attribute Closure –
To test given attribute(s) is superkey/candidate key or not.
We can check if FD X → Y holds.
An alternative way to find out F+.
Test whether attribute is superkey or not.Example :Let R = (A, B, C, G, H, I) and set of FD are F = { A → B, A → C, CG → H, CG → I, B → H}Find out (AG)+.Result = {A, G}First loop :A → B includes B in the Result as A⊆ Result (which is AG), so Result := Result ∪ B.
Hence Result = {A, G, B}
A → C causes Result to become ABCG.
CG → H causes the Result to become ABCGH.
CG → I causes the Result to become ABCGHI.
B → H causes Result to become ABCGHI.Second loop :A → B causes the Result to be unchanged i.e. ABCGHI (B is already part of the Result).
A → C causes Result to be unchanged.
CG → H causes the Result to be unchanged.
CG → I causes the Result to be unchanged.
B → H causes Result to be unchanged.At the end of the second loop, the Result does not change so exit from the loop.(AG)+ = {A, B, C, G, H, I}Conclusion: AG is a super key as all other attributes can be determined by it.Check whether Fd exists :Example :Let R = (A, B, C, G, H, I) and set of FD are F = { A →B, A → C, CG → H, CG → I, B → H}Check HB → I holds or notResult = {H, B}First loop :In A → B as A ⊆ Result (which is HB) so nothing will be added.
In A → C nothing added.
CG → H (CG ⊆ Result (which is HB) so nothing added)
CG → I nothing added.
B → H nothing added.At the end of the first loop, the Result does not change so exit from the loop.Conclusion: HB → I does not hold.An alternate way to find Closure of FDs (F+).Example :Given a relation R (A, B, C, D, E, F) and set of FDs F: {A → BC, E → CF, B → E, CD → EF}Find out closure of {A, B}+Step-1: Result = ABStep-2: First loopResult = ABC for A → BC, A ⊆ Result so Result = Result ∪ BC.
Result = ABC for E→ CF, E ∉ Result so Result = Result.
Result = ABCE for B → E, B ⊆Result so Result = Result ∪ E.
Result = ABCE for CD → EF, CD ∉ Result so Result = Result.The Result before step2 is AB and after step 2 is ABCE which is different so repeat the same as step 2.Step-3: Second loopResult = ABCE for A → BC, A ⊆ Result so Result = Result ∪ BC.
Result = ABCEF for E → CF, E ⊆ Result so Result = Result ∪ CF.
Result = ABCEF for B → E, B ⊆ Result so Result = Result ∪ E.
Result = ABCEF for CD → EF, CD ∉ Result so Result = Result.The Result before step 3 is ABCE and that after step 3 is ABCEF which is different, so repeat the same as step 3.Step-4: Third loopResult = ABCEF for A → BC, A ⊆ Result so Result = Result ∪ BC.
Result = ABCEF for E → CF, E ⊆ Result so Result = Result ∪ CF.
Result = ABCEF for B → E, B ⊆ Result so Result = Result ∪ E.
Result = ABCEF for CD → EF, CD ∉ Result so Result = Result.The Result before step4 is ABCEF and after step 3 is ABCEF which is the same so stop.So Closure of {A, B}+ is {A, B, C, E, F}.Conclusion: For every attribute/set of attributes we can find closure. This Results in F+.My Personal Notes
arrow_drop_upSave
Test whether attribute is superkey or not.Example :Let R = (A, B, C, G, H, I) and set of FD are F = { A → B, A → C, CG → H, CG → I, B → H}Find out (AG)+.Result = {A, G}First loop :A → B includes B in the Result as A⊆ Result (which is AG), so Result := Result ∪ B.
Hence Result = {A, G, B}
A → C causes Result to become ABCG.
CG → H causes the Result to become ABCGH.
CG → I causes the Result to become ABCGHI.
B → H causes Result to become ABCGHI.Second loop :A → B causes the Result to be unchanged i.e. ABCGHI (B is already part of the Result).
A → C causes Result to be unchanged.
CG → H causes the Result to be unchanged.
CG → I causes the Result to be unchanged.
B → H causes Result to be unchanged.At the end of the second loop, the Result does not change so exit from the loop.(AG)+ = {A, B, C, G, H, I}Conclusion: AG is a super key as all other attributes can be determined by it.
Example :Let R = (A, B, C, G, H, I) and set of FD are F = { A → B, A → C, CG → H, CG → I, B → H}
Find out (AG)+.
Result = {A, G}
First loop :
A → B includes B in the Result as A⊆ Result (which is AG), so Result := Result ∪ B.
Hence Result = {A, G, B}
A → C causes Result to become ABCG.
CG → H causes the Result to become ABCGH.
CG → I causes the Result to become ABCGHI.
B → H causes Result to become ABCGHI.
Second loop :
A → B causes the Result to be unchanged i.e. ABCGHI (B is already part of the Result).
A → C causes Result to be unchanged.
CG → H causes the Result to be unchanged.
CG → I causes the Result to be unchanged.
B → H causes Result to be unchanged.
At the end of the second loop, the Result does not change so exit from the loop.
(AG)+ = {A, B, C, G, H, I}
Conclusion: AG is a super key as all other attributes can be determined by it.
Check whether Fd exists :Example :Let R = (A, B, C, G, H, I) and set of FD are F = { A →B, A → C, CG → H, CG → I, B → H}Check HB → I holds or notResult = {H, B}First loop :In A → B as A ⊆ Result (which is HB) so nothing will be added.
In A → C nothing added.
CG → H (CG ⊆ Result (which is HB) so nothing added)
CG → I nothing added.
B → H nothing added.At the end of the first loop, the Result does not change so exit from the loop.Conclusion: HB → I does not hold.
Example :Let R = (A, B, C, G, H, I) and set of FD are F = { A →B, A → C, CG → H, CG → I, B → H}
Check HB → I holds or not
Result = {H, B}
First loop :
In A → B as A ⊆ Result (which is HB) so nothing will be added.
In A → C nothing added.
CG → H (CG ⊆ Result (which is HB) so nothing added)
CG → I nothing added.
B → H nothing added.
At the end of the first loop, the Result does not change so exit from the loop.
Conclusion: HB → I does not hold.
An alternate way to find Closure of FDs (F+).Example :Given a relation R (A, B, C, D, E, F) and set of FDs F: {A → BC, E → CF, B → E, CD → EF}Find out closure of {A, B}+Step-1: Result = ABStep-2: First loopResult = ABC for A → BC, A ⊆ Result so Result = Result ∪ BC.
Result = ABC for E→ CF, E ∉ Result so Result = Result.
Result = ABCE for B → E, B ⊆Result so Result = Result ∪ E.
Result = ABCE for CD → EF, CD ∉ Result so Result = Result.The Result before step2 is AB and after step 2 is ABCE which is different so repeat the same as step 2.Step-3: Second loopResult = ABCE for A → BC, A ⊆ Result so Result = Result ∪ BC.
Result = ABCEF for E → CF, E ⊆ Result so Result = Result ∪ CF.
Result = ABCEF for B → E, B ⊆ Result so Result = Result ∪ E.
Result = ABCEF for CD → EF, CD ∉ Result so Result = Result.The Result before step 3 is ABCE and that after step 3 is ABCEF which is different, so repeat the same as step 3.Step-4: Third loopResult = ABCEF for A → BC, A ⊆ Result so Result = Result ∪ BC.
Result = ABCEF for E → CF, E ⊆ Result so Result = Result ∪ CF.
Result = ABCEF for B → E, B ⊆ Result so Result = Result ∪ E.
Result = ABCEF for CD → EF, CD ∉ Result so Result = Result.The Result before step4 is ABCEF and after step 3 is ABCEF which is the same so stop.So Closure of {A, B}+ is {A, B, C, E, F}.Conclusion: For every attribute/set of attributes we can find closure. This Results in F+.My Personal Notes
arrow_drop_upSave
Example :Given a relation R (A, B, C, D, E, F) and set of FDs F: {A → BC, E → CF, B → E, CD → EF}
Find out closure of {A, B}+
Step-1: Result = AB
Step-2: First loop
Result = ABC for A → BC, A ⊆ Result so Result = Result ∪ BC.
Result = ABC for E→ CF, E ∉ Result so Result = Result.
Result = ABCE for B → E, B ⊆Result so Result = Result ∪ E.
Result = ABCE for CD → EF, CD ∉ Result so Result = Result.
The Result before step2 is AB and after step 2 is ABCE which is different so repeat the same as step 2.
Step-3: Second loop
Result = ABCE for A → BC, A ⊆ Result so Result = Result ∪ BC.
Result = ABCEF for E → CF, E ⊆ Result so Result = Result ∪ CF.
Result = ABCEF for B → E, B ⊆ Result so Result = Result ∪ E.
Result = ABCEF for CD → EF, CD ∉ Result so Result = Result.
The Result before step 3 is ABCE and that after step 3 is ABCEF which is different, so repeat the same as step 3.
Step-4: Third loop
Result = ABCEF for A → BC, A ⊆ Result so Result = Result ∪ BC.
Result = ABCEF for E → CF, E ⊆ Result so Result = Result ∪ CF.
Result = ABCEF for B → E, B ⊆ Result so Result = Result ∪ E.
Result = ABCEF for CD → EF, CD ∉ Result so Result = Result.
The Result before step4 is ABCEF and after step 3 is ABCEF which is the same so stop.
So Closure of {A, B}+ is {A, B, C, E, F}.
Conclusion: For every attribute/set of attributes we can find closure. This Results in F+.
DBMS
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Deadlock in DBMS
Types of Functional dependencies in DBMS
KDD Process in Data Mining
Conflict Serializability in DBMS
Two Phase Locking Protocol
Layers of OSI Model
TCP/IP Model
Types of Operating Systems
Page Replacement Algorithms in Operating Systems
Differences between TCP and UDP | [
{
"code": null,
"e": 25573,
"s": 25545,
"text": "\n18 Sep, 2020"
},
{
"code": null,
"e": 25733,
"s": 25573,
"text": "Closure of a set F of FDs is the set F+ of all FDs that can be inferred from F. It is also known as complete set of Functional Dependency. It is denoted by F+."
},
{
"code": null,
"e": 25767,
"s": 25733,
"text": "Algorithm : Attribute Closure set"
},
{
"code": null,
"e": 25971,
"s": 25767,
"text": "Algorithm to compute a+, the closure of a under F\nResult:= a;\nwhile (changes to Result) do \n for each B → Y in F do\n Begin\n if B ⊆ Result then Result := Result ∪ Y \n End"
},
{
"code": null,
"e": 26006,
"s": 25971,
"text": "Utilization of Attribute Closure –"
},
{
"code": null,
"e": 26067,
"s": 26006,
"text": "To test given attribute(s) is superkey/candidate key or not."
},
{
"code": null,
"e": 26099,
"s": 26067,
"text": "We can check if FD X → Y holds."
},
{
"code": null,
"e": 26134,
"s": 26099,
"text": "An alternative way to find out F+."
},
{
"code": null,
"e": 28927,
"s": 26134,
"text": "Test whether attribute is superkey or not.Example :Let R = (A, B, C, G, H, I) and set of FD are F = { A → B, A → C, CG → H, CG → I, B → H}Find out (AG)+.Result = {A, G}First loop :A → B includes B in the Result as A⊆ Result (which is AG), so Result := Result ∪ B. \nHence Result = {A, G, B}\nA → C causes Result to become ABCG.\nCG → H causes the Result to become ABCGH.\nCG → I causes the Result to become ABCGHI.\nB → H causes Result to become ABCGHI.Second loop :A → B causes the Result to be unchanged i.e. ABCGHI (B is already part of the Result).\nA → C causes Result to be unchanged.\nCG → H causes the Result to be unchanged.\nCG → I causes the Result to be unchanged.\nB → H causes Result to be unchanged.At the end of the second loop, the Result does not change so exit from the loop.(AG)+ = {A, B, C, G, H, I}Conclusion: AG is a super key as all other attributes can be determined by it.Check whether Fd exists :Example :Let R = (A, B, C, G, H, I) and set of FD are F = { A →B, A → C, CG → H, CG → I, B → H}Check HB → I holds or notResult = {H, B}First loop :In A → B as A ⊆ Result (which is HB) so nothing will be added.\nIn A → C nothing added.\nCG → H (CG ⊆ Result (which is HB) so nothing added)\nCG → I nothing added.\nB → H nothing added.At the end of the first loop, the Result does not change so exit from the loop.Conclusion: HB → I does not hold.An alternate way to find Closure of FDs (F+).Example :Given a relation R (A, B, C, D, E, F) and set of FDs F: {A → BC, E → CF, B → E, CD → EF}Find out closure of {A, B}+Step-1: Result = ABStep-2: First loopResult = ABC for A → BC, A ⊆ Result so Result = Result ∪ BC.\nResult = ABC for E→ CF, E ∉ Result so Result = Result.\nResult = ABCE for B → E, B ⊆Result so Result = Result ∪ E.\nResult = ABCE for CD → EF, CD ∉ Result so Result = Result.The Result before step2 is AB and after step 2 is ABCE which is different so repeat the same as step 2.Step-3: Second loopResult = ABCE for A → BC, A ⊆ Result so Result = Result ∪ BC.\nResult = ABCEF for E → CF, E ⊆ Result so Result = Result ∪ CF.\nResult = ABCEF for B → E, B ⊆ Result so Result = Result ∪ E.\nResult = ABCEF for CD → EF, CD ∉ Result so Result = Result.The Result before step 3 is ABCE and that after step 3 is ABCEF which is different, so repeat the same as step 3.Step-4: Third loopResult = ABCEF for A → BC, A ⊆ Result so Result = Result ∪ BC.\nResult = ABCEF for E → CF, E ⊆ Result so Result = Result ∪ CF.\nResult = ABCEF for B → E, B ⊆ Result so Result = Result ∪ E.\nResult = ABCEF for CD → EF, CD ∉ Result so Result = Result.The Result before step4 is ABCEF and after step 3 is ABCEF which is the same so stop.So Closure of {A, B}+ is {A, B, C, E, F}.Conclusion: For every attribute/set of attributes we can find closure. This Results in F+.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 29817,
"s": 28927,
"text": "Test whether attribute is superkey or not.Example :Let R = (A, B, C, G, H, I) and set of FD are F = { A → B, A → C, CG → H, CG → I, B → H}Find out (AG)+.Result = {A, G}First loop :A → B includes B in the Result as A⊆ Result (which is AG), so Result := Result ∪ B. \nHence Result = {A, G, B}\nA → C causes Result to become ABCG.\nCG → H causes the Result to become ABCGH.\nCG → I causes the Result to become ABCGHI.\nB → H causes Result to become ABCGHI.Second loop :A → B causes the Result to be unchanged i.e. ABCGHI (B is already part of the Result).\nA → C causes Result to be unchanged.\nCG → H causes the Result to be unchanged.\nCG → I causes the Result to be unchanged.\nB → H causes Result to be unchanged.At the end of the second loop, the Result does not change so exit from the loop.(AG)+ = {A, B, C, G, H, I}Conclusion: AG is a super key as all other attributes can be determined by it."
},
{
"code": null,
"e": 29914,
"s": 29817,
"text": "Example :Let R = (A, B, C, G, H, I) and set of FD are F = { A → B, A → C, CG → H, CG → I, B → H}"
},
{
"code": null,
"e": 29930,
"s": 29914,
"text": "Find out (AG)+."
},
{
"code": null,
"e": 29946,
"s": 29930,
"text": "Result = {A, G}"
},
{
"code": null,
"e": 29959,
"s": 29946,
"text": "First loop :"
},
{
"code": null,
"e": 30228,
"s": 29959,
"text": "A → B includes B in the Result as A⊆ Result (which is AG), so Result := Result ∪ B. \nHence Result = {A, G, B}\nA → C causes Result to become ABCG.\nCG → H causes the Result to become ABCGH.\nCG → I causes the Result to become ABCGHI.\nB → H causes Result to become ABCGHI."
},
{
"code": null,
"e": 30242,
"s": 30228,
"text": "Second loop :"
},
{
"code": null,
"e": 30487,
"s": 30242,
"text": "A → B causes the Result to be unchanged i.e. ABCGHI (B is already part of the Result).\nA → C causes Result to be unchanged.\nCG → H causes the Result to be unchanged.\nCG → I causes the Result to be unchanged.\nB → H causes Result to be unchanged."
},
{
"code": null,
"e": 30568,
"s": 30487,
"text": "At the end of the second loop, the Result does not change so exit from the loop."
},
{
"code": null,
"e": 30595,
"s": 30568,
"text": "(AG)+ = {A, B, C, G, H, I}"
},
{
"code": null,
"e": 30674,
"s": 30595,
"text": "Conclusion: AG is a super key as all other attributes can be determined by it."
},
{
"code": null,
"e": 31140,
"s": 30674,
"text": "Check whether Fd exists :Example :Let R = (A, B, C, G, H, I) and set of FD are F = { A →B, A → C, CG → H, CG → I, B → H}Check HB → I holds or notResult = {H, B}First loop :In A → B as A ⊆ Result (which is HB) so nothing will be added.\nIn A → C nothing added.\nCG → H (CG ⊆ Result (which is HB) so nothing added)\nCG → I nothing added.\nB → H nothing added.At the end of the first loop, the Result does not change so exit from the loop.Conclusion: HB → I does not hold."
},
{
"code": null,
"e": 31236,
"s": 31140,
"text": "Example :Let R = (A, B, C, G, H, I) and set of FD are F = { A →B, A → C, CG → H, CG → I, B → H}"
},
{
"code": null,
"e": 31262,
"s": 31236,
"text": "Check HB → I holds or not"
},
{
"code": null,
"e": 31278,
"s": 31262,
"text": "Result = {H, B}"
},
{
"code": null,
"e": 31291,
"s": 31278,
"text": "First loop :"
},
{
"code": null,
"e": 31473,
"s": 31291,
"text": "In A → B as A ⊆ Result (which is HB) so nothing will be added.\nIn A → C nothing added.\nCG → H (CG ⊆ Result (which is HB) so nothing added)\nCG → I nothing added.\nB → H nothing added."
},
{
"code": null,
"e": 31553,
"s": 31473,
"text": "At the end of the first loop, the Result does not change so exit from the loop."
},
{
"code": null,
"e": 31587,
"s": 31553,
"text": "Conclusion: HB → I does not hold."
},
{
"code": null,
"e": 33026,
"s": 31587,
"text": "An alternate way to find Closure of FDs (F+).Example :Given a relation R (A, B, C, D, E, F) and set of FDs F: {A → BC, E → CF, B → E, CD → EF}Find out closure of {A, B}+Step-1: Result = ABStep-2: First loopResult = ABC for A → BC, A ⊆ Result so Result = Result ∪ BC.\nResult = ABC for E→ CF, E ∉ Result so Result = Result.\nResult = ABCE for B → E, B ⊆Result so Result = Result ∪ E.\nResult = ABCE for CD → EF, CD ∉ Result so Result = Result.The Result before step2 is AB and after step 2 is ABCE which is different so repeat the same as step 2.Step-3: Second loopResult = ABCE for A → BC, A ⊆ Result so Result = Result ∪ BC.\nResult = ABCEF for E → CF, E ⊆ Result so Result = Result ∪ CF.\nResult = ABCEF for B → E, B ⊆ Result so Result = Result ∪ E.\nResult = ABCEF for CD → EF, CD ∉ Result so Result = Result.The Result before step 3 is ABCE and that after step 3 is ABCEF which is different, so repeat the same as step 3.Step-4: Third loopResult = ABCEF for A → BC, A ⊆ Result so Result = Result ∪ BC.\nResult = ABCEF for E → CF, E ⊆ Result so Result = Result ∪ CF.\nResult = ABCEF for B → E, B ⊆ Result so Result = Result ∪ E.\nResult = ABCEF for CD → EF, CD ∉ Result so Result = Result.The Result before step4 is ABCEF and after step 3 is ABCEF which is the same so stop.So Closure of {A, B}+ is {A, B, C, E, F}.Conclusion: For every attribute/set of attributes we can find closure. This Results in F+.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 33124,
"s": 33026,
"text": "Example :Given a relation R (A, B, C, D, E, F) and set of FDs F: {A → BC, E → CF, B → E, CD → EF}"
},
{
"code": null,
"e": 33152,
"s": 33124,
"text": "Find out closure of {A, B}+"
},
{
"code": null,
"e": 33172,
"s": 33152,
"text": "Step-1: Result = AB"
},
{
"code": null,
"e": 33191,
"s": 33172,
"text": "Step-2: First loop"
},
{
"code": null,
"e": 33427,
"s": 33191,
"text": "Result = ABC for A → BC, A ⊆ Result so Result = Result ∪ BC.\nResult = ABC for E→ CF, E ∉ Result so Result = Result.\nResult = ABCE for B → E, B ⊆Result so Result = Result ∪ E.\nResult = ABCE for CD → EF, CD ∉ Result so Result = Result."
},
{
"code": null,
"e": 33531,
"s": 33427,
"text": "The Result before step2 is AB and after step 2 is ABCE which is different so repeat the same as step 2."
},
{
"code": null,
"e": 33551,
"s": 33531,
"text": "Step-3: Second loop"
},
{
"code": null,
"e": 33798,
"s": 33551,
"text": "Result = ABCE for A → BC, A ⊆ Result so Result = Result ∪ BC.\nResult = ABCEF for E → CF, E ⊆ Result so Result = Result ∪ CF.\nResult = ABCEF for B → E, B ⊆ Result so Result = Result ∪ E.\nResult = ABCEF for CD → EF, CD ∉ Result so Result = Result."
},
{
"code": null,
"e": 33912,
"s": 33798,
"text": "The Result before step 3 is ABCE and that after step 3 is ABCEF which is different, so repeat the same as step 3."
},
{
"code": null,
"e": 33931,
"s": 33912,
"text": "Step-4: Third loop"
},
{
"code": null,
"e": 34179,
"s": 33931,
"text": "Result = ABCEF for A → BC, A ⊆ Result so Result = Result ∪ BC.\nResult = ABCEF for E → CF, E ⊆ Result so Result = Result ∪ CF.\nResult = ABCEF for B → E, B ⊆ Result so Result = Result ∪ E.\nResult = ABCEF for CD → EF, CD ∉ Result so Result = Result."
},
{
"code": null,
"e": 34265,
"s": 34179,
"text": "The Result before step4 is ABCEF and after step 3 is ABCEF which is the same so stop."
},
{
"code": null,
"e": 34307,
"s": 34265,
"text": "So Closure of {A, B}+ is {A, B, C, E, F}."
},
{
"code": null,
"e": 34398,
"s": 34307,
"text": "Conclusion: For every attribute/set of attributes we can find closure. This Results in F+."
},
{
"code": null,
"e": 34403,
"s": 34398,
"text": "DBMS"
},
{
"code": null,
"e": 34411,
"s": 34403,
"text": "GATE CS"
},
{
"code": null,
"e": 34416,
"s": 34411,
"text": "DBMS"
},
{
"code": null,
"e": 34514,
"s": 34416,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34531,
"s": 34514,
"text": "Deadlock in DBMS"
},
{
"code": null,
"e": 34572,
"s": 34531,
"text": "Types of Functional dependencies in DBMS"
},
{
"code": null,
"e": 34599,
"s": 34572,
"text": "KDD Process in Data Mining"
},
{
"code": null,
"e": 34632,
"s": 34599,
"text": "Conflict Serializability in DBMS"
},
{
"code": null,
"e": 34659,
"s": 34632,
"text": "Two Phase Locking Protocol"
},
{
"code": null,
"e": 34679,
"s": 34659,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 34692,
"s": 34679,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 34719,
"s": 34692,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 34768,
"s": 34719,
"text": "Page Replacement Algorithms in Operating Systems"
}
] |
Minimization of ER Diagrams - GeeksforGeeks | 04 Mar, 2022
Entity-Relationship (ER) Diagram is a diagrammatic representation of data in databases, it shows how data is related.
Note: This article is for those who already know what is ER diagram and how to draw ER diagram.
1) When there are Many to One cardinalities in the ER diagram. For example, a student can be enrolled only in one course, but a course can be enrolled by many students.
For Student(SID, Name), SID is the primary key. For Course(CID, C_name ), CID is the primary key
Student Course
(SID Name) ( CID C_name )
-------------- -----------------
1 A c1 Z
2 B c2 Y
3 C c3 X
4 D
Enroll
(SID CID)
----------
1 C1
2 C1
3 c3
4 C2
Now the question is, what should be the primary key for Enroll? Should it be SID or CID or both combined into one. We can’t have CID as the primary key because a CID can have multiple SIDs. (SID, CID) can distinguish table uniquely, but it is not minimum. So SID is the primary key for the relation enrollment.
For the above ER diagram, we considered three tables in the database
Student
Enroll
Course
But we can combine Student and Enroll table renamed as Student_enroll.
Student_Enroll
( SID Name CID )
---------------------
1 A c1
2 B c1
3 C c3
4 D c2
Student and enroll tables are merged now.
So require a minimum of two DBMS tables for Student_enroll and Course.
Note: In One to Many relationships we can have a minimum of two tables.
2. When there are Many to Many cardinalities in ER Diagram. Let us consider the above example with the change that now a student can enroll in more than 1 course.
Student Course
( SID Name) ( CID C_name )
-------------- -----------------
1 A c1 Z
2 B c2 Y
3 C c3 X
4 D
Enroll
( SID CID )
----------
1 C1
1 C2
2 C1
2 C2
3 c3
4 C2
Now, the same question arises. What is the primary key of Enroll relation? If we carefully analyze, the primary key for Enroll table is ( SID, CID ).
But in this case, we can’t merge Enroll table with any one of the Student and Course. If we try to merge Enroll with any one of the Student and Course it will create redundant data.
Note: Minimum of three tables are required in the Many to Many relationships.
3. One to One Relationship
There are two possibilities A) If we have One to One relationship and we have total participation at at-least one end.
For example, consider the below ER diagram.
A1 and B1 are primary keys of E1 and E2 respectively.
In the above diagram, we have total participation at the E1 end.
Only a single table is required in this case having the primary key of E1 as its primary key.
Since E1 is in total participation, each entry in E1 is related to only one entry in E2, but not all entries in E2 are related to an entry in E1.
The primary key of E1 should be allowed as the primary key of the reduced table since if the primary key of E2 is used, it might have null values for many of its entries in the reduced table.
Note: Only 1 table required.
B) One to One relationship with no total participation.
A1 and B1 are primary keys of E1 and E2 respectively.
The primary key of R can be A1 or B1, but we can’t still combine all three tables into one. if we do so, some entries in the combined table may have NULL entries. So the idea of merging all three tables into one is not good.
But we can merge R into E1 or E2. So a minimum of 2 tables is required.
Below is the Gate Previous Year Question. https://www.geeksforgeeks.org/gate-gate-cs-2008-question-82/ https://www.geeksforgeeks.org/gate-gate-cs-2008-question-83/
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
PremSwarupPradhan
vishaltennyson
liza06
vaibhavsinghtanwar
Abe10
sahilvaidya13
DBMS-ER model
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL | WITH clause
SQL | Join (Inner, Left, Right and Full Joins)
SQL query to find second highest salary?
SQL Interview Questions
CTE in SQL
SQL Trigger | Student Database
Difference between Clustered and Non-clustered index
Data Preprocessing in Data Mining
Difference between SQL and NoSQL
Difference between DDL and DML in DBMS | [
{
"code": null,
"e": 30871,
"s": 30843,
"text": "\n04 Mar, 2022"
},
{
"code": null,
"e": 30990,
"s": 30871,
"text": "Entity-Relationship (ER) Diagram is a diagrammatic representation of data in databases, it shows how data is related. "
},
{
"code": null,
"e": 31087,
"s": 30990,
"text": "Note: This article is for those who already know what is ER diagram and how to draw ER diagram. "
},
{
"code": null,
"e": 31256,
"s": 31087,
"text": "1) When there are Many to One cardinalities in the ER diagram. For example, a student can be enrolled only in one course, but a course can be enrolled by many students."
},
{
"code": null,
"e": 31358,
"s": 31258,
"text": "For Student(SID, Name), SID is the primary key. For Course(CID, C_name ), CID is the primary key "
},
{
"code": null,
"e": 31868,
"s": 31358,
"text": " Student Course \n (SID Name) ( CID C_name )\n -------------- -----------------\n 1 A c1 Z\n 2 B c2 Y\n 3 C c3 X\n 4 D\n\n Enroll \n (SID CID)\n ----------\n 1 C1\n 2 C1\n 3 c3\n 4 C2"
},
{
"code": null,
"e": 32181,
"s": 31868,
"text": "Now the question is, what should be the primary key for Enroll? Should it be SID or CID or both combined into one. We can’t have CID as the primary key because a CID can have multiple SIDs. (SID, CID) can distinguish table uniquely, but it is not minimum. So SID is the primary key for the relation enrollment. "
},
{
"code": null,
"e": 32252,
"s": 32181,
"text": "For the above ER diagram, we considered three tables in the database "
},
{
"code": null,
"e": 32275,
"s": 32252,
"text": "Student \nEnroll\nCourse"
},
{
"code": null,
"e": 32348,
"s": 32275,
"text": "But we can combine Student and Enroll table renamed as Student_enroll. "
},
{
"code": null,
"e": 32596,
"s": 32348,
"text": " Student_Enroll \n ( SID Name CID )\n ---------------------\n 1 A c1\n 2 B c1\n 3 C c3\n 4 D c2"
},
{
"code": null,
"e": 32639,
"s": 32596,
"text": "Student and enroll tables are merged now. "
},
{
"code": null,
"e": 32711,
"s": 32639,
"text": "So require a minimum of two DBMS tables for Student_enroll and Course. "
},
{
"code": null,
"e": 32784,
"s": 32711,
"text": "Note: In One to Many relationships we can have a minimum of two tables. "
},
{
"code": null,
"e": 32951,
"s": 32787,
"text": "2. When there are Many to Many cardinalities in ER Diagram. Let us consider the above example with the change that now a student can enroll in more than 1 course. "
},
{
"code": null,
"e": 33462,
"s": 32955,
"text": " Student Course\n( SID Name) ( CID C_name )\n-------------- -----------------\n 1 A c1 Z\n 2 B c2 Y\n 3 C c3 X\n 4 D\n\n Enroll \n ( SID CID )\n ----------\n 1 C1\n 1 C2\n 2 C1\n 2 C2\n 3 c3\n 4 C2"
},
{
"code": null,
"e": 33613,
"s": 33462,
"text": "Now, the same question arises. What is the primary key of Enroll relation? If we carefully analyze, the primary key for Enroll table is ( SID, CID ). "
},
{
"code": null,
"e": 33796,
"s": 33613,
"text": "But in this case, we can’t merge Enroll table with any one of the Student and Course. If we try to merge Enroll with any one of the Student and Course it will create redundant data. "
},
{
"code": null,
"e": 33875,
"s": 33796,
"text": "Note: Minimum of three tables are required in the Many to Many relationships. "
},
{
"code": null,
"e": 33906,
"s": 33878,
"text": "3. One to One Relationship "
},
{
"code": null,
"e": 34026,
"s": 33906,
"text": "There are two possibilities A) If we have One to One relationship and we have total participation at at-least one end. "
},
{
"code": null,
"e": 34071,
"s": 34026,
"text": "For example, consider the below ER diagram. "
},
{
"code": null,
"e": 34128,
"s": 34073,
"text": "A1 and B1 are primary keys of E1 and E2 respectively. "
},
{
"code": null,
"e": 34194,
"s": 34128,
"text": "In the above diagram, we have total participation at the E1 end. "
},
{
"code": null,
"e": 34289,
"s": 34194,
"text": "Only a single table is required in this case having the primary key of E1 as its primary key. "
},
{
"code": null,
"e": 34436,
"s": 34289,
"text": "Since E1 is in total participation, each entry in E1 is related to only one entry in E2, but not all entries in E2 are related to an entry in E1. "
},
{
"code": null,
"e": 34629,
"s": 34436,
"text": "The primary key of E1 should be allowed as the primary key of the reduced table since if the primary key of E2 is used, it might have null values for many of its entries in the reduced table. "
},
{
"code": null,
"e": 34659,
"s": 34629,
"text": "Note: Only 1 table required. "
},
{
"code": null,
"e": 34719,
"s": 34662,
"text": "B) One to One relationship with no total participation. "
},
{
"code": null,
"e": 34776,
"s": 34721,
"text": "A1 and B1 are primary keys of E1 and E2 respectively. "
},
{
"code": null,
"e": 35002,
"s": 34776,
"text": "The primary key of R can be A1 or B1, but we can’t still combine all three tables into one. if we do so, some entries in the combined table may have NULL entries. So the idea of merging all three tables into one is not good. "
},
{
"code": null,
"e": 35076,
"s": 35002,
"text": "But we can merge R into E1 or E2. So a minimum of 2 tables is required. "
},
{
"code": null,
"e": 35243,
"s": 35076,
"text": " Below is the Gate Previous Year Question. https://www.geeksforgeeks.org/gate-gate-cs-2008-question-82/ https://www.geeksforgeeks.org/gate-gate-cs-2008-question-83/ "
},
{
"code": null,
"e": 35368,
"s": 35243,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 35386,
"s": 35368,
"text": "PremSwarupPradhan"
},
{
"code": null,
"e": 35401,
"s": 35386,
"text": "vishaltennyson"
},
{
"code": null,
"e": 35408,
"s": 35401,
"text": "liza06"
},
{
"code": null,
"e": 35427,
"s": 35408,
"text": "vaibhavsinghtanwar"
},
{
"code": null,
"e": 35433,
"s": 35427,
"text": "Abe10"
},
{
"code": null,
"e": 35447,
"s": 35433,
"text": "sahilvaidya13"
},
{
"code": null,
"e": 35461,
"s": 35447,
"text": "DBMS-ER model"
},
{
"code": null,
"e": 35466,
"s": 35461,
"text": "DBMS"
},
{
"code": null,
"e": 35471,
"s": 35466,
"text": "DBMS"
},
{
"code": null,
"e": 35569,
"s": 35471,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35587,
"s": 35569,
"text": "SQL | WITH clause"
},
{
"code": null,
"e": 35634,
"s": 35587,
"text": "SQL | Join (Inner, Left, Right and Full Joins)"
},
{
"code": null,
"e": 35675,
"s": 35634,
"text": "SQL query to find second highest salary?"
},
{
"code": null,
"e": 35699,
"s": 35675,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 35710,
"s": 35699,
"text": "CTE in SQL"
},
{
"code": null,
"e": 35741,
"s": 35710,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 35794,
"s": 35741,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 35828,
"s": 35794,
"text": "Data Preprocessing in Data Mining"
},
{
"code": null,
"e": 35861,
"s": 35828,
"text": "Difference between SQL and NoSQL"
}
] |
Python Exception Base Classes | Like other high-level languages, there are some exceptions in python also. When a problem occurs, it raises an exception. There are different kind of exceptions like ZeroDivisionError, AssertionError etc. All exception classes are derived from the BaseException class.
The code can run built in exceptions, or we can also raise these exceptions in the code. User can derive their own exception from the Exception class, or from any other child class of Exception class.
The BaseException is the base class of all other exceptions. User defined classes cannot be directly derived from this class, to derive user defied class, we need to use Exception class.
The Python Exception Hierarchy is like below.
BaseException
ExceptionArithmeticErrorFloatingPointErrorOverflowErrorZeroDivisionErrorAssertionErrorAttributeErrorBufferErrorEOFErrorImportErrorModuleNotFoundErrorLookupErrorIndexErrorKeyErrorMemoryErrorNameErrorUnboundLocalErrorOSErrorBlockingIOErrorChildProcessErrorConnectionErrorBrokenPipeErrorConnectionAbortedErrorConnectionRefusedErrorConnectionResetErrorFileExistsErrorFileNotFoundErrorInterruptedErrorIsADirectoryErrorNotADirectoryErrorPermissionErrorProcessLookupErrorTimeoutError
ArithmeticErrorFloatingPointErrorOverflowErrorZeroDivisionError
FloatingPointError
OverflowError
ZeroDivisionError
AssertionError
AttributeError
BufferError
EOFError
ImportErrorModuleNotFoundError
ModuleNotFoundError
LookupErrorIndexErrorKeyError
IndexError
KeyError
MemoryError
NameErrorUnboundLocalError
UnboundLocalError
OSErrorBlockingIOErrorChildProcessErrorConnectionErrorBrokenPipeErrorConnectionAbortedErrorConnectionRefusedErrorConnectionResetError
BlockingIOError
ChildProcessError
ConnectionErrorBrokenPipeErrorConnectionAbortedErrorConnectionRefusedErrorConnectionResetError
BrokenPipeError
ConnectionAbortedError
ConnectionRefusedError
ConnectionResetError
FileExistsError
FileNotFoundError
InterruptedError
IsADirectoryError
NotADirectoryError
PermissionError
ProcessLookupError
TimeoutError
ReferenceError
RuntimeErrorNotImplementedErrorRecursionError
NotImplementedError
RecursionError
StopIteration
StopAsyncIteration
SyntaxErrorIndentationErrorTabError
IndentationErrorTabError
TabError
SystemError
TypeError
ValueErrorUnicodeErrorUnicodeDecodeErrorUnicodeEncodeErrorUnicodeTranslateError
UnicodeErrorUnicodeDecodeErrorUnicodeEncodeErrorUnicodeTranslateError
UnicodeDecodeError
UnicodeEncodeError
UnicodeTranslateError
WarningBytesWarningDeprecationWarningFutureWarningImportWarningPendingDeprecationWarningResourceWarningRuntimeWarningSyntaxWarningUnicodeWarningUserWarning
BytesWarning
DeprecationWarning
FutureWarning
ImportWarning
PendingDeprecationWarning
ResourceWarning
RuntimeWarning
SyntaxWarning
UnicodeWarning
UserWarning
GeneratorExit
KeyboardInterrupt
SystemExit
Problem − In this problem there is a class of employees. The condition is, the age of employee must be greater than 18.
We should create one user defined exception class, which is a child class of the Exception class.
Live Demo
class LowAgeError(Exception):
def __init__(self):
pass
def __str__(self):
return 'The age must be greater than 18 years'
class Employee:
def __init__(self, name, age):
self.name = name
if age < 18:
raise LowAgeError
else:
self.age = age
def display(self):
print('The name of the employee: ' + self.name + ', Age: ' + str(self.age) +' Years')
try:
e1 = Employee('Subhas', 25)
e1.display()
e2 = Employee('Anupam', 12)
e1.display()
except LowAgeError as e:
print('Error Occurred: ' + str(e))
The name of the employee: Subhas, Age: 25 Years
Error OccurredThe age must be greater than 18 years | [
{
"code": null,
"e": 1331,
"s": 1062,
"text": "Like other high-level languages, there are some exceptions in python also. When a problem occurs, it raises an exception. There are different kind of exceptions like ZeroDivisionError, AssertionError etc. All exception classes are derived from the BaseException class."
},
{
"code": null,
"e": 1532,
"s": 1331,
"text": "The code can run built in exceptions, or we can also raise these exceptions in the code. User can derive their own exception from the Exception class, or from any other child class of Exception class."
},
{
"code": null,
"e": 1719,
"s": 1532,
"text": "The BaseException is the base class of all other exceptions. User defined classes cannot be directly derived from this class, to derive user defied class, we need to use Exception class."
},
{
"code": null,
"e": 1765,
"s": 1719,
"text": "The Python Exception Hierarchy is like below."
},
{
"code": null,
"e": 1779,
"s": 1765,
"text": "BaseException"
},
{
"code": null,
"e": 2256,
"s": 1779,
"text": "ExceptionArithmeticErrorFloatingPointErrorOverflowErrorZeroDivisionErrorAssertionErrorAttributeErrorBufferErrorEOFErrorImportErrorModuleNotFoundErrorLookupErrorIndexErrorKeyErrorMemoryErrorNameErrorUnboundLocalErrorOSErrorBlockingIOErrorChildProcessErrorConnectionErrorBrokenPipeErrorConnectionAbortedErrorConnectionRefusedErrorConnectionResetErrorFileExistsErrorFileNotFoundErrorInterruptedErrorIsADirectoryErrorNotADirectoryErrorPermissionErrorProcessLookupErrorTimeoutError"
},
{
"code": null,
"e": 2320,
"s": 2256,
"text": "ArithmeticErrorFloatingPointErrorOverflowErrorZeroDivisionError"
},
{
"code": null,
"e": 2339,
"s": 2320,
"text": "FloatingPointError"
},
{
"code": null,
"e": 2353,
"s": 2339,
"text": "OverflowError"
},
{
"code": null,
"e": 2371,
"s": 2353,
"text": "ZeroDivisionError"
},
{
"code": null,
"e": 2386,
"s": 2371,
"text": "AssertionError"
},
{
"code": null,
"e": 2401,
"s": 2386,
"text": "AttributeError"
},
{
"code": null,
"e": 2413,
"s": 2401,
"text": "BufferError"
},
{
"code": null,
"e": 2422,
"s": 2413,
"text": "EOFError"
},
{
"code": null,
"e": 2453,
"s": 2422,
"text": "ImportErrorModuleNotFoundError"
},
{
"code": null,
"e": 2473,
"s": 2453,
"text": "ModuleNotFoundError"
},
{
"code": null,
"e": 2503,
"s": 2473,
"text": "LookupErrorIndexErrorKeyError"
},
{
"code": null,
"e": 2514,
"s": 2503,
"text": "IndexError"
},
{
"code": null,
"e": 2523,
"s": 2514,
"text": "KeyError"
},
{
"code": null,
"e": 2535,
"s": 2523,
"text": "MemoryError"
},
{
"code": null,
"e": 2562,
"s": 2535,
"text": "NameErrorUnboundLocalError"
},
{
"code": null,
"e": 2580,
"s": 2562,
"text": "UnboundLocalError"
},
{
"code": null,
"e": 2714,
"s": 2580,
"text": "OSErrorBlockingIOErrorChildProcessErrorConnectionErrorBrokenPipeErrorConnectionAbortedErrorConnectionRefusedErrorConnectionResetError"
},
{
"code": null,
"e": 2730,
"s": 2714,
"text": "BlockingIOError"
},
{
"code": null,
"e": 2748,
"s": 2730,
"text": "ChildProcessError"
},
{
"code": null,
"e": 2843,
"s": 2748,
"text": "ConnectionErrorBrokenPipeErrorConnectionAbortedErrorConnectionRefusedErrorConnectionResetError"
},
{
"code": null,
"e": 2859,
"s": 2843,
"text": "BrokenPipeError"
},
{
"code": null,
"e": 2882,
"s": 2859,
"text": "ConnectionAbortedError"
},
{
"code": null,
"e": 2905,
"s": 2882,
"text": "ConnectionRefusedError"
},
{
"code": null,
"e": 2926,
"s": 2905,
"text": "ConnectionResetError"
},
{
"code": null,
"e": 2942,
"s": 2926,
"text": "FileExistsError"
},
{
"code": null,
"e": 2960,
"s": 2942,
"text": "FileNotFoundError"
},
{
"code": null,
"e": 2977,
"s": 2960,
"text": "InterruptedError"
},
{
"code": null,
"e": 2995,
"s": 2977,
"text": "IsADirectoryError"
},
{
"code": null,
"e": 3014,
"s": 2995,
"text": "NotADirectoryError"
},
{
"code": null,
"e": 3030,
"s": 3014,
"text": "PermissionError"
},
{
"code": null,
"e": 3049,
"s": 3030,
"text": "ProcessLookupError"
},
{
"code": null,
"e": 3062,
"s": 3049,
"text": "TimeoutError"
},
{
"code": null,
"e": 3077,
"s": 3062,
"text": "ReferenceError"
},
{
"code": null,
"e": 3123,
"s": 3077,
"text": "RuntimeErrorNotImplementedErrorRecursionError"
},
{
"code": null,
"e": 3143,
"s": 3123,
"text": "NotImplementedError"
},
{
"code": null,
"e": 3158,
"s": 3143,
"text": "RecursionError"
},
{
"code": null,
"e": 3172,
"s": 3158,
"text": "StopIteration"
},
{
"code": null,
"e": 3191,
"s": 3172,
"text": "StopAsyncIteration"
},
{
"code": null,
"e": 3227,
"s": 3191,
"text": "SyntaxErrorIndentationErrorTabError"
},
{
"code": null,
"e": 3252,
"s": 3227,
"text": "IndentationErrorTabError"
},
{
"code": null,
"e": 3261,
"s": 3252,
"text": "TabError"
},
{
"code": null,
"e": 3273,
"s": 3261,
"text": "SystemError"
},
{
"code": null,
"e": 3283,
"s": 3273,
"text": "TypeError"
},
{
"code": null,
"e": 3363,
"s": 3283,
"text": "ValueErrorUnicodeErrorUnicodeDecodeErrorUnicodeEncodeErrorUnicodeTranslateError"
},
{
"code": null,
"e": 3433,
"s": 3363,
"text": "UnicodeErrorUnicodeDecodeErrorUnicodeEncodeErrorUnicodeTranslateError"
},
{
"code": null,
"e": 3452,
"s": 3433,
"text": "UnicodeDecodeError"
},
{
"code": null,
"e": 3471,
"s": 3452,
"text": "UnicodeEncodeError"
},
{
"code": null,
"e": 3493,
"s": 3471,
"text": "UnicodeTranslateError"
},
{
"code": null,
"e": 3649,
"s": 3493,
"text": "WarningBytesWarningDeprecationWarningFutureWarningImportWarningPendingDeprecationWarningResourceWarningRuntimeWarningSyntaxWarningUnicodeWarningUserWarning"
},
{
"code": null,
"e": 3662,
"s": 3649,
"text": "BytesWarning"
},
{
"code": null,
"e": 3681,
"s": 3662,
"text": "DeprecationWarning"
},
{
"code": null,
"e": 3695,
"s": 3681,
"text": "FutureWarning"
},
{
"code": null,
"e": 3709,
"s": 3695,
"text": "ImportWarning"
},
{
"code": null,
"e": 3735,
"s": 3709,
"text": "PendingDeprecationWarning"
},
{
"code": null,
"e": 3751,
"s": 3735,
"text": "ResourceWarning"
},
{
"code": null,
"e": 3766,
"s": 3751,
"text": "RuntimeWarning"
},
{
"code": null,
"e": 3780,
"s": 3766,
"text": "SyntaxWarning"
},
{
"code": null,
"e": 3795,
"s": 3780,
"text": "UnicodeWarning"
},
{
"code": null,
"e": 3807,
"s": 3795,
"text": "UserWarning"
},
{
"code": null,
"e": 3821,
"s": 3807,
"text": "GeneratorExit"
},
{
"code": null,
"e": 3839,
"s": 3821,
"text": "KeyboardInterrupt"
},
{
"code": null,
"e": 3850,
"s": 3839,
"text": "SystemExit"
},
{
"code": null,
"e": 3970,
"s": 3850,
"text": "Problem − In this problem there is a class of employees. The condition is, the age of employee must be greater than 18."
},
{
"code": null,
"e": 4068,
"s": 3970,
"text": "We should create one user defined exception class, which is a child class of the Exception class."
},
{
"code": null,
"e": 4079,
"s": 4068,
"text": " Live Demo"
},
{
"code": null,
"e": 4666,
"s": 4079,
"text": "class LowAgeError(Exception):\n def __init__(self):\n pass\n\n def __str__(self):\n return 'The age must be greater than 18 years'\n\nclass Employee:\n def __init__(self, name, age):\n self.name = name\n if age < 18:\n raise LowAgeError\n else:\n self.age = age\n\n def display(self):\n print('The name of the employee: ' + self.name + ', Age: ' + str(self.age) +' Years')\n\n try:\n e1 = Employee('Subhas', 25)\n e1.display()\n\n e2 = Employee('Anupam', 12)\n e1.display()\nexcept LowAgeError as e:\n print('Error Occurred: ' + str(e))"
},
{
"code": null,
"e": 4766,
"s": 4666,
"text": "The name of the employee: Subhas, Age: 25 Years\nError OccurredThe age must be greater than 18 years"
}
] |
Abundant Number - GeeksforGeeks | 24 Jan, 2022
A number n is said to be Abundant Number if sum of all the proper divisors of the number denoted by sum(n) is greater than the value of the number n. And the difference between these two values is called the abundance. Mathematically, if below condition holds the number is said to be Abundant number:
sum(n)> n
abundance = sum(n) - n
sum(n): aliquot sum - The sum of all proper divisors of n
Given a number n, our task is to find if this number is Abundant number or not. The first few Abundant Numbers are: 12, 18, 20, 24, 30, 36, 40, 42, 48, 54, 56, 60, 66 .....
Examples :
Input: 21
Output: NO
Input: 12
Output: YES
Input: 17
Output: NO
Method 1
A Simple solution is to iterate all the numbers from 1 to n-1 and check if the number divides n and calculate the sum. Check if this sum is greater than n or not.Time Complexity of this approach: O(n)
Optimized Solution:
If we observe carefully, the divisors of the number n are present in pairs. For example if n = 100, then all the pairs of divisors are: (1,100), (2,50), (4,25), (5,20), (10,10)Using this fact we can speed up our program. While checking divisors we will have to be careful if there are two equal divisors as in case of (10, 10). In such case we will take only one of them in calculation of sum. Subtract the number n from the sum of all divisors to get the sum of proper divisors.
C++
Java
Python3
C#
PHP
Javascript
// An Optimized Solution to check Abundant Number#include <bits/stdc++.h>using namespace std; // Function to calculate sum of divisorsint getSum(int n){ int sum = 0; // Note that this loop runs till square root // of n for (int i=1; i<=sqrt(n); i++) { if (n%i==0) { // If divisors are equal,take only one // of them if (n/i == i) sum = sum + i; else // Otherwise take both { sum = sum + i; sum = sum + (n / i); } } } // calculate sum of all proper divisors only sum = sum - n; return sum;} // Function to check Abundant Numberbool checkAbundant(int n){ // Return true if sum of divisors is greater // than n. return (getSum(n) > n);} /* Driver program to test above function */int main(){ checkAbundant(12)? cout << "YES\n" : cout << "NO\n"; checkAbundant(15)? cout << "YES\n" : cout << "NO\n"; return 0;}
// An Optimized Solution to check Abundant Number// in JAVAimport java.io.*;import java.math.*; // Function to calculate sum of divisorsclass GFG{ static int getSum(int n) { int sum = 0; // Note that this loop runs till square // root of n for (int i=1; i<=(Math.sqrt(n)); i++) { if (n%i==0) { // If divisors are equal,take only // one of them if (n/i == i) sum = sum + i; else // Otherwise take both { sum = sum + i; sum = sum + (n / i); } } } // calculate sum of all proper divisors // only sum = sum - n; return sum; } // Function to check Abundant Number static boolean checkAbundant(int n) { // Return true if sum of divisors is // greater than n. return (getSum(n) > n); } /* Driver program to test above function */ public static void main(String args[])throws IOException { if(checkAbundant(12)) System.out.println("YES"); else System.out.println("NO"); if(checkAbundant(15)) System.out.println("YES"); else System.out.println("NO"); }} // This code is contributed by Nikita Tiwari.
# An Optimized Solution to check Abundant Number# in PYTHONimport math # Function to calculate sum of divisorsdef getSum(n) : sum = 0 # Note that this loop runs till square root # of n i = 1 while i <= (math.sqrt(n)) : if n%i == 0 : # If divisors are equal,take only one # of them if n//i == i : sum = sum + i else : # Otherwise take both sum = sum + i sum = sum + (n // i ) i = i + 1 # calculate sum of all proper divisors only sum = sum - n return sum # Function to check Abundant Numberdef checkAbundant(n) : # Return true if sum of divisors is greater # than n. if (getSum(n) > n) : return 1 else : return 0 # Driver program to test above function */if(checkAbundant(12) == 1) : print ("YES")else : print ("NO") if(checkAbundant(15) == 1) : print ("YES")else : print ("NO") # This code is contributed by Nikita Tiwari.
// An Optimized Solution to check Abundant Number// in C#// Function to calculate sum of divisorsusing System; class GFG { // Function to calculate sum of divisors static int getSum(int n) { int sum = 0; // Note that this loop runs till square // root of n for (int i = 1; i <= (Math.Sqrt(n)); i++) { if (n % i == 0) { // If divisors are equal, take only // one of them if (n / i == i) sum = sum + i; else // Otherwise take both { sum = sum + i; sum = sum + (n / i); } } } // calculate sum of all proper divisors // only sum = sum - n; return sum; } // Function to check Abundant Number static bool checkAbundant(int n) { // Return true if sum of divisors is // greater than n. return (getSum(n) > n); } /* Driver program to test above function */ public static void Main() { if (checkAbundant(12)) Console.WriteLine("YES"); else Console.WriteLine("NO"); if (checkAbundant(15)) Console.WriteLine("YES"); else Console.WriteLine("NO"); }} // This code is contributed by vt_m.
<?php// PHP program for an Optimized// solution to check Abundant Number // Function to calculate// sum of divisorsfunction getSum($n){ $sum = 0; // Note that this loop runs // till square root of n for ($i = 1; $i <= sqrt($n); $i++) { if ($n % $i == 0) { // If divisors are equal,take // only one of them if ($n / $i == $i) $sum = $sum + $i; // Otherwise take both else { $sum = $sum + $i; $sum = $sum + ($n / $i); } } } // calculate sum of all // proper divisors only $sum = $sum - $n; return $sum;} // Function to check Abundant Numberfunction checkAbundant($n){ // Return true if sum of // divisors is greater than n. return (getSum($n) > $n);} // Driver Code$k = checkAbundant(12) ? "YES\n" : "NO\n";echo($k); $k = checkAbundant(15) ? "YES\n" : "NO\n";echo($k); // This code is contributed by Ajit.?>
<script>// Javascript program for an Optimized// solution to check Abundant Number // Function to calculate// sum of divisorsfunction getSum(n){ let sum = 0; // Note that this loop runs // till square root of n for (let i = 1; i <= Math.sqrt(n); i++) { if (n % i == 0) { // If divisors are equal,take // only one of them if (n / i == i) sum = sum + i; // Otherwise take both else { sum = sum + i; sum = sum + (n / i); } } } // calculate sum of all // proper divisors only sum = sum - n; return sum;} // Function to check Abundant Numberfunction checkAbundant(n){ // Return true if sum of // divisors is greater than n. return (getSum(n) > n);} // Driver Codelet k = checkAbundant(12) ? "YES<br>" : "NO<br>";document.write(k); k = checkAbundant(15) ? "YES<br>" : "NO<br>";document.write(k); // This code is contributed by _saurabh_jaiswal</script>
Output :
YES
NO
Time Complexity: O(sqrt(n)) Auxiliary Space: O(1)References: https://en.wikipedia.org/wiki/Abundant_numberThis article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.-Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.”
jit_t
_saurabh_jaiswal
amartyaghoshgfg
series
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find sum of elements in a given array
Program for factorial of a number
Operators in C / C++
Euclidean algorithms (Basic and Extended)
The Knight's tour problem | Backtracking-1
Efficient program to print all prime factors of a given number
Find minimum number of coins that make a given value | [
{
"code": null,
"e": 25072,
"s": 25044,
"text": "\n24 Jan, 2022"
},
{
"code": null,
"e": 25375,
"s": 25072,
"text": "A number n is said to be Abundant Number if sum of all the proper divisors of the number denoted by sum(n) is greater than the value of the number n. And the difference between these two values is called the abundance. Mathematically, if below condition holds the number is said to be Abundant number: "
},
{
"code": null,
"e": 25467,
"s": 25375,
"text": "sum(n)> n\nabundance = sum(n) - n\nsum(n): aliquot sum - The sum of all proper divisors of n"
},
{
"code": null,
"e": 25642,
"s": 25467,
"text": "Given a number n, our task is to find if this number is Abundant number or not. The first few Abundant Numbers are: 12, 18, 20, 24, 30, 36, 40, 42, 48, 54, 56, 60, 66 ..... "
},
{
"code": null,
"e": 25655,
"s": 25642,
"text": "Examples : "
},
{
"code": null,
"e": 25721,
"s": 25655,
"text": "Input: 21\nOutput: NO\n\nInput: 12\nOutput: YES\n\nInput: 17\nOutput: NO"
},
{
"code": null,
"e": 25734,
"s": 25725,
"text": "Method 1"
},
{
"code": null,
"e": 25936,
"s": 25734,
"text": "A Simple solution is to iterate all the numbers from 1 to n-1 and check if the number divides n and calculate the sum. Check if this sum is greater than n or not.Time Complexity of this approach: O(n) "
},
{
"code": null,
"e": 25956,
"s": 25936,
"text": "Optimized Solution:"
},
{
"code": null,
"e": 26437,
"s": 25956,
"text": "If we observe carefully, the divisors of the number n are present in pairs. For example if n = 100, then all the pairs of divisors are: (1,100), (2,50), (4,25), (5,20), (10,10)Using this fact we can speed up our program. While checking divisors we will have to be careful if there are two equal divisors as in case of (10, 10). In such case we will take only one of them in calculation of sum. Subtract the number n from the sum of all divisors to get the sum of proper divisors. "
},
{
"code": null,
"e": 26441,
"s": 26437,
"text": "C++"
},
{
"code": null,
"e": 26446,
"s": 26441,
"text": "Java"
},
{
"code": null,
"e": 26454,
"s": 26446,
"text": "Python3"
},
{
"code": null,
"e": 26457,
"s": 26454,
"text": "C#"
},
{
"code": null,
"e": 26461,
"s": 26457,
"text": "PHP"
},
{
"code": null,
"e": 26472,
"s": 26461,
"text": "Javascript"
},
{
"code": "// An Optimized Solution to check Abundant Number#include <bits/stdc++.h>using namespace std; // Function to calculate sum of divisorsint getSum(int n){ int sum = 0; // Note that this loop runs till square root // of n for (int i=1; i<=sqrt(n); i++) { if (n%i==0) { // If divisors are equal,take only one // of them if (n/i == i) sum = sum + i; else // Otherwise take both { sum = sum + i; sum = sum + (n / i); } } } // calculate sum of all proper divisors only sum = sum - n; return sum;} // Function to check Abundant Numberbool checkAbundant(int n){ // Return true if sum of divisors is greater // than n. return (getSum(n) > n);} /* Driver program to test above function */int main(){ checkAbundant(12)? cout << \"YES\\n\" : cout << \"NO\\n\"; checkAbundant(15)? cout << \"YES\\n\" : cout << \"NO\\n\"; return 0;}",
"e": 27458,
"s": 26472,
"text": null
},
{
"code": "// An Optimized Solution to check Abundant Number// in JAVAimport java.io.*;import java.math.*; // Function to calculate sum of divisorsclass GFG{ static int getSum(int n) { int sum = 0; // Note that this loop runs till square // root of n for (int i=1; i<=(Math.sqrt(n)); i++) { if (n%i==0) { // If divisors are equal,take only // one of them if (n/i == i) sum = sum + i; else // Otherwise take both { sum = sum + i; sum = sum + (n / i); } } } // calculate sum of all proper divisors // only sum = sum - n; return sum; } // Function to check Abundant Number static boolean checkAbundant(int n) { // Return true if sum of divisors is // greater than n. return (getSum(n) > n); } /* Driver program to test above function */ public static void main(String args[])throws IOException { if(checkAbundant(12)) System.out.println(\"YES\"); else System.out.println(\"NO\"); if(checkAbundant(15)) System.out.println(\"YES\"); else System.out.println(\"NO\"); }} // This code is contributed by Nikita Tiwari.",
"e": 28841,
"s": 27458,
"text": null
},
{
"code": "# An Optimized Solution to check Abundant Number# in PYTHONimport math # Function to calculate sum of divisorsdef getSum(n) : sum = 0 # Note that this loop runs till square root # of n i = 1 while i <= (math.sqrt(n)) : if n%i == 0 : # If divisors are equal,take only one # of them if n//i == i : sum = sum + i else : # Otherwise take both sum = sum + i sum = sum + (n // i ) i = i + 1 # calculate sum of all proper divisors only sum = sum - n return sum # Function to check Abundant Numberdef checkAbundant(n) : # Return true if sum of divisors is greater # than n. if (getSum(n) > n) : return 1 else : return 0 # Driver program to test above function */if(checkAbundant(12) == 1) : print (\"YES\")else : print (\"NO\") if(checkAbundant(15) == 1) : print (\"YES\")else : print (\"NO\") # This code is contributed by Nikita Tiwari.",
"e": 29865,
"s": 28841,
"text": null
},
{
"code": "// An Optimized Solution to check Abundant Number// in C#// Function to calculate sum of divisorsusing System; class GFG { // Function to calculate sum of divisors static int getSum(int n) { int sum = 0; // Note that this loop runs till square // root of n for (int i = 1; i <= (Math.Sqrt(n)); i++) { if (n % i == 0) { // If divisors are equal, take only // one of them if (n / i == i) sum = sum + i; else // Otherwise take both { sum = sum + i; sum = sum + (n / i); } } } // calculate sum of all proper divisors // only sum = sum - n; return sum; } // Function to check Abundant Number static bool checkAbundant(int n) { // Return true if sum of divisors is // greater than n. return (getSum(n) > n); } /* Driver program to test above function */ public static void Main() { if (checkAbundant(12)) Console.WriteLine(\"YES\"); else Console.WriteLine(\"NO\"); if (checkAbundant(15)) Console.WriteLine(\"YES\"); else Console.WriteLine(\"NO\"); }} // This code is contributed by vt_m.",
"e": 31249,
"s": 29865,
"text": null
},
{
"code": "<?php// PHP program for an Optimized// solution to check Abundant Number // Function to calculate// sum of divisorsfunction getSum($n){ $sum = 0; // Note that this loop runs // till square root of n for ($i = 1; $i <= sqrt($n); $i++) { if ($n % $i == 0) { // If divisors are equal,take // only one of them if ($n / $i == $i) $sum = $sum + $i; // Otherwise take both else { $sum = $sum + $i; $sum = $sum + ($n / $i); } } } // calculate sum of all // proper divisors only $sum = $sum - $n; return $sum;} // Function to check Abundant Numberfunction checkAbundant($n){ // Return true if sum of // divisors is greater than n. return (getSum($n) > $n);} // Driver Code$k = checkAbundant(12) ? \"YES\\n\" : \"NO\\n\";echo($k); $k = checkAbundant(15) ? \"YES\\n\" : \"NO\\n\";echo($k); // This code is contributed by Ajit.?>",
"e": 32240,
"s": 31249,
"text": null
},
{
"code": "<script>// Javascript program for an Optimized// solution to check Abundant Number // Function to calculate// sum of divisorsfunction getSum(n){ let sum = 0; // Note that this loop runs // till square root of n for (let i = 1; i <= Math.sqrt(n); i++) { if (n % i == 0) { // If divisors are equal,take // only one of them if (n / i == i) sum = sum + i; // Otherwise take both else { sum = sum + i; sum = sum + (n / i); } } } // calculate sum of all // proper divisors only sum = sum - n; return sum;} // Function to check Abundant Numberfunction checkAbundant(n){ // Return true if sum of // divisors is greater than n. return (getSum(n) > n);} // Driver Codelet k = checkAbundant(12) ? \"YES<br>\" : \"NO<br>\";document.write(k); k = checkAbundant(15) ? \"YES<br>\" : \"NO<br>\";document.write(k); // This code is contributed by _saurabh_jaiswal</script>",
"e": 33272,
"s": 32240,
"text": null
},
{
"code": null,
"e": 33283,
"s": 33272,
"text": "Output : "
},
{
"code": null,
"e": 33290,
"s": 33283,
"text": "YES\nNO"
},
{
"code": null,
"e": 33820,
"s": 33290,
"text": "Time Complexity: O(sqrt(n)) Auxiliary Space: O(1)References: https://en.wikipedia.org/wiki/Abundant_numberThis article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.-Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.” "
},
{
"code": null,
"e": 33826,
"s": 33820,
"text": "jit_t"
},
{
"code": null,
"e": 33843,
"s": 33826,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 33859,
"s": 33843,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 33866,
"s": 33859,
"text": "series"
},
{
"code": null,
"e": 33879,
"s": 33866,
"text": "Mathematical"
},
{
"code": null,
"e": 33892,
"s": 33879,
"text": "Mathematical"
},
{
"code": null,
"e": 33899,
"s": 33892,
"text": "series"
},
{
"code": null,
"e": 33997,
"s": 33899,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34021,
"s": 33997,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 34064,
"s": 34021,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 34078,
"s": 34064,
"text": "Prime Numbers"
},
{
"code": null,
"e": 34127,
"s": 34078,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 34161,
"s": 34127,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 34182,
"s": 34161,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 34224,
"s": 34182,
"text": "Euclidean algorithms (Basic and Extended)"
},
{
"code": null,
"e": 34267,
"s": 34224,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 34330,
"s": 34267,
"text": "Efficient program to print all prime factors of a given number"
}
] |
How to convert binary to Hex by using C language? | Binary numbers are represented in 1’s and 0’s.
Hexadecimal number system with 16 digits is {0,1,2,3.....9, A(10), B(11),......F(15)}
To convert from binary to hex representation, the bit string id is grouped in blocks of 4-bits which are called as nibbles from the least significant side. Each block is replaced by the corresponding hex digit.
Let’s see an example to get the clarity on hexadecimal and binary number representation.
0011 1110 0101 1011 0001 1101
3 E 5 B 1 D
We write 0X3E5B1D for a hex constant in C language.
Another example which What iss how to convert decimal to binary and then to hexadecimal is as follows −
7529D = 0000 0000 0000 0000 0001 1101 0110 1001B
= 0x00001D69 = 0x1D69
Following is the C program which What is how the binary number is converted into its equivalent hexadecimal number by using while loop −
Live Demo
#include <stdio.h>
int main(){
long int binaryval, hexadecimalval = 0, i = 1, remainder;
printf("Enter the binary number: ");
scanf("%ld", &binaryval);
while (binaryval != 0){
remainder = binaryval % 10;
hexadecimalval = hexadecimalval + remainder * i;
i = i * 2;
binaryval = binaryval / 10;
}
printf("Equivalent hexadecimal value: %lX", hexadecimalval);
return 0;
}
When the above program is executed, it produces the following result −
Enter the binary number: 11100
Equivalent hexadecimal value: 1C | [
{
"code": null,
"e": 1109,
"s": 1062,
"text": "Binary numbers are represented in 1’s and 0’s."
},
{
"code": null,
"e": 1195,
"s": 1109,
"text": "Hexadecimal number system with 16 digits is {0,1,2,3.....9, A(10), B(11),......F(15)}"
},
{
"code": null,
"e": 1406,
"s": 1195,
"text": "To convert from binary to hex representation, the bit string id is grouped in blocks of 4-bits which are called as nibbles from the least significant side. Each block is replaced by the corresponding hex digit."
},
{
"code": null,
"e": 1495,
"s": 1406,
"text": "Let’s see an example to get the clarity on hexadecimal and binary number representation."
},
{
"code": null,
"e": 1553,
"s": 1495,
"text": "0011 1110 0101 1011 0001 1101\n 3 E 5 B 1 D"
},
{
"code": null,
"e": 1605,
"s": 1553,
"text": "We write 0X3E5B1D for a hex constant in C language."
},
{
"code": null,
"e": 1709,
"s": 1605,
"text": "Another example which What iss how to convert decimal to binary and then to hexadecimal is as follows −"
},
{
"code": null,
"e": 1786,
"s": 1709,
"text": "7529D = 0000 0000 0000 0000 0001 1101 0110 1001B\n = 0x00001D69 = 0x1D69"
},
{
"code": null,
"e": 1923,
"s": 1786,
"text": "Following is the C program which What is how the binary number is converted into its equivalent hexadecimal number by using while loop −"
},
{
"code": null,
"e": 1934,
"s": 1923,
"text": " Live Demo"
},
{
"code": null,
"e": 2346,
"s": 1934,
"text": "#include <stdio.h>\nint main(){\n long int binaryval, hexadecimalval = 0, i = 1, remainder;\n printf(\"Enter the binary number: \");\n scanf(\"%ld\", &binaryval);\n while (binaryval != 0){\n remainder = binaryval % 10;\n hexadecimalval = hexadecimalval + remainder * i;\n i = i * 2;\n binaryval = binaryval / 10;\n }\n printf(\"Equivalent hexadecimal value: %lX\", hexadecimalval);\n return 0;\n}"
},
{
"code": null,
"e": 2417,
"s": 2346,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 2481,
"s": 2417,
"text": "Enter the binary number: 11100\nEquivalent hexadecimal value: 1C"
}
] |
Get the summary of dataset in R using Dply - GeeksforGeeks | 23 Aug, 2021
In this article, we will discuss how to get a summary of the dataset in the R programming language using Dplyr package. To get the summary of a dataset summarize() function of this module is used. This function basically gives the summary based on some required action for a group or ungrouped data, which in turn helps summarize the dataset.
Syntax: summarize(action)
The dataset in use: bestsellers3
Here, action can be any operation to be performed on grouped data, it can be frequency count, mean, average, etc.
Example: Summarize the dataset using summarize()
R
library(dplyr) data<-read.csv("bestsellers.csv")data %>% group_by(Genre) %>% summarize(n())
Output:
# A tibble: 2 x 2
Genre `n()`
<fct> <int>
1 Fiction 82
2 Non Fiction 117
It is also possible to summarize ungrouped data. There are three possible functions that can be used for this.
summarize_all().
summarize_at().
summarize_if().
summarize_all() function summarizes all the columns based on the action to be performed.
Syntax: summarize_all(action)
R
library(dplyr) data<-read.csv("bestsellers.csv")data %>% group_by(Genre) %>% summarize_all(mean)
Output:
summarize_at() function is used to apply a required action to some specific columns and generate a summary based on that
Syntax: summarize_at(vector_of_columns,action)
R
library(dplyr) data<-read.csv("bestsellers.csv")data %>% group_by(Genre) %>% summarize_at(c('User.Rating','Price'),mean)
Output:
summarize_if() function is used to get dataset summary if a certain condition is specified.
Syntax: summarize_if(condition, action)
R
library(dplyr) data<-read.csv("bestsellers.csv")data %>% group_by(Genre) %>% summarize_if(is.numeric, mean)
Output:
Picked
R Dplyr
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 Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
Time Series Analysis in R
R - if statement | [
{
"code": null,
"e": 25242,
"s": 25214,
"text": "\n23 Aug, 2021"
},
{
"code": null,
"e": 25585,
"s": 25242,
"text": "In this article, we will discuss how to get a summary of the dataset in the R programming language using Dplyr package. To get the summary of a dataset summarize() function of this module is used. This function basically gives the summary based on some required action for a group or ungrouped data, which in turn helps summarize the dataset."
},
{
"code": null,
"e": 25611,
"s": 25585,
"text": "Syntax: summarize(action)"
},
{
"code": null,
"e": 25644,
"s": 25611,
"text": "The dataset in use: bestsellers3"
},
{
"code": null,
"e": 25758,
"s": 25644,
"text": "Here, action can be any operation to be performed on grouped data, it can be frequency count, mean, average, etc."
},
{
"code": null,
"e": 25807,
"s": 25758,
"text": "Example: Summarize the dataset using summarize()"
},
{
"code": null,
"e": 25809,
"s": 25807,
"text": "R"
},
{
"code": "library(dplyr) data<-read.csv(\"bestsellers.csv\")data %>% group_by(Genre) %>% summarize(n())",
"e": 25903,
"s": 25809,
"text": null
},
{
"code": null,
"e": 25911,
"s": 25903,
"text": "Output:"
},
{
"code": null,
"e": 26007,
"s": 25911,
"text": "# A tibble: 2 x 2\n Genre `n()`\n <fct> <int>\n1 Fiction 82\n2 Non Fiction 117"
},
{
"code": null,
"e": 26118,
"s": 26007,
"text": "It is also possible to summarize ungrouped data. There are three possible functions that can be used for this."
},
{
"code": null,
"e": 26135,
"s": 26118,
"text": "summarize_all()."
},
{
"code": null,
"e": 26151,
"s": 26135,
"text": "summarize_at()."
},
{
"code": null,
"e": 26167,
"s": 26151,
"text": "summarize_if()."
},
{
"code": null,
"e": 26256,
"s": 26167,
"text": "summarize_all() function summarizes all the columns based on the action to be performed."
},
{
"code": null,
"e": 26286,
"s": 26256,
"text": "Syntax: summarize_all(action)"
},
{
"code": null,
"e": 26288,
"s": 26286,
"text": "R"
},
{
"code": "library(dplyr) data<-read.csv(\"bestsellers.csv\")data %>% group_by(Genre) %>% summarize_all(mean)",
"e": 26387,
"s": 26288,
"text": null
},
{
"code": null,
"e": 26395,
"s": 26387,
"text": "Output:"
},
{
"code": null,
"e": 26516,
"s": 26395,
"text": "summarize_at() function is used to apply a required action to some specific columns and generate a summary based on that"
},
{
"code": null,
"e": 26563,
"s": 26516,
"text": "Syntax: summarize_at(vector_of_columns,action)"
},
{
"code": null,
"e": 26565,
"s": 26563,
"text": "R"
},
{
"code": "library(dplyr) data<-read.csv(\"bestsellers.csv\")data %>% group_by(Genre) %>% summarize_at(c('User.Rating','Price'),mean)",
"e": 26688,
"s": 26565,
"text": null
},
{
"code": null,
"e": 26696,
"s": 26688,
"text": "Output:"
},
{
"code": null,
"e": 26788,
"s": 26696,
"text": "summarize_if() function is used to get dataset summary if a certain condition is specified."
},
{
"code": null,
"e": 26828,
"s": 26788,
"text": "Syntax: summarize_if(condition, action)"
},
{
"code": null,
"e": 26830,
"s": 26828,
"text": "R"
},
{
"code": "library(dplyr) data<-read.csv(\"bestsellers.csv\")data %>% group_by(Genre) %>% summarize_if(is.numeric, mean)",
"e": 26940,
"s": 26830,
"text": null
},
{
"code": null,
"e": 26948,
"s": 26940,
"text": "Output:"
},
{
"code": null,
"e": 26955,
"s": 26948,
"text": "Picked"
},
{
"code": null,
"e": 26963,
"s": 26955,
"text": "R Dplyr"
},
{
"code": null,
"e": 26974,
"s": 26963,
"text": "R Language"
},
{
"code": null,
"e": 27072,
"s": 26974,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27124,
"s": 27072,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 27162,
"s": 27124,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 27197,
"s": 27162,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 27255,
"s": 27197,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 27304,
"s": 27255,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 27341,
"s": 27304,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 27391,
"s": 27341,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 27434,
"s": 27391,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 27460,
"s": 27434,
"text": "Time Series Analysis in R"
}
] |
Can we initialize static variables in a default constructor in Java? | Class/static variables belong to a class, just like instance variables they are declared within a class, outside any method, but, with the static keyword.
They are available to access at the compile time, you can access them before/without instantiating the class, there is only one copy of the static field available throughout the class i.e. the value of the static field will be same in all objects. You can define a static field using the static keyword.
If you declare a static variable in a class, if you haven’t initialized it, just like with instance variables compiler initializes these with default values in the default constructor.
Yes, you can also initialize these values using the constructor.
Live Demo
public class DefaultExample {
static String name;
static int age;
DefaultExample() {
name = "Krishna";
age = 25;
}
public static void main(String args[]) {
new DefaultExample();
System.out.println(DefaultExample.name); System.out.println(DefaultExample.age);
}
}
Krishna
25
But if you declare an instance variable static and final Java compiler will not initialize it in the default constructor therefore, it is mandatory to initialize static and final variables. If you don’t a compile time error is generated.
Live Demo
public class DefaultExample {
static final String name;
static final int age;
public static void main(String args[]) {
new DefaultExample();
System.out.println(DefaultExample.name); System.out.println(DefaultExample.age);
}
}
DefaultExample.java:2: error: variable name not initialized in the default constructor
static final String name;
^
DefaultExample.java:3: error: variable age not initialized in the default constructor
static final int age;
^
2 errors
But, if you try to initialize a variable which is declared final and static, compiler considers it as an attempt to initialize the variable and a compile time error will be generated.
Live Demo
public class DefaultExample {
static final String name;
static final int age;
DefaultExample() {
name = "Krishna";
age = 25;
}
public static void main(String args[]) {
new DefaultExample();
System.out.println(DefaultExample.name);
System.out.println(DefaultExample.age);
}
}
OutputDeviceAssignedDefaultExample.java:5: error: cannot assign a value to final variable name
name = "Krishna";
^
DefaultExample.java:6: error: cannot assign a value to final variable age
age = 25;
^
2 errors | [
{
"code": null,
"e": 1217,
"s": 1062,
"text": "Class/static variables belong to a class, just like instance variables they are declared within a class, outside any method, but, with the static keyword."
},
{
"code": null,
"e": 1521,
"s": 1217,
"text": "They are available to access at the compile time, you can access them before/without instantiating the class, there is only one copy of the static field available throughout the class i.e. the value of the static field will be same in all objects. You can define a static field using the static keyword."
},
{
"code": null,
"e": 1706,
"s": 1521,
"text": "If you declare a static variable in a class, if you haven’t initialized it, just like with instance variables compiler initializes these with default values in the default constructor."
},
{
"code": null,
"e": 1771,
"s": 1706,
"text": "Yes, you can also initialize these values using the constructor."
},
{
"code": null,
"e": 1782,
"s": 1771,
"text": " Live Demo"
},
{
"code": null,
"e": 2087,
"s": 1782,
"text": "public class DefaultExample {\n static String name;\n static int age;\n DefaultExample() {\n name = \"Krishna\";\n age = 25;\n }\n public static void main(String args[]) {\n new DefaultExample();\n System.out.println(DefaultExample.name); System.out.println(DefaultExample.age);\n }\n}"
},
{
"code": null,
"e": 2098,
"s": 2087,
"text": "Krishna\n25"
},
{
"code": null,
"e": 2336,
"s": 2098,
"text": "But if you declare an instance variable static and final Java compiler will not initialize it in the default constructor therefore, it is mandatory to initialize static and final variables. If you don’t a compile time error is generated."
},
{
"code": null,
"e": 2347,
"s": 2336,
"text": " Live Demo"
},
{
"code": null,
"e": 2597,
"s": 2347,
"text": "public class DefaultExample {\n static final String name;\n static final int age;\n public static void main(String args[]) {\n new DefaultExample();\n System.out.println(DefaultExample.name); System.out.println(DefaultExample.age);\n }\n}"
},
{
"code": null,
"e": 2849,
"s": 2597,
"text": "DefaultExample.java:2: error: variable name not initialized in the default constructor\n static final String name;\n ^\nDefaultExample.java:3: error: variable age not initialized in the default constructor\n static final int age;\n^\n2 errors"
},
{
"code": null,
"e": 3033,
"s": 2849,
"text": "But, if you try to initialize a variable which is declared final and static, compiler considers it as an attempt to initialize the variable and a compile time error will be generated."
},
{
"code": null,
"e": 3044,
"s": 3033,
"text": " Live Demo"
},
{
"code": null,
"e": 3367,
"s": 3044,
"text": "public class DefaultExample {\n static final String name;\n static final int age;\n DefaultExample() {\n name = \"Krishna\";\n age = 25;\n }\n public static void main(String args[]) {\n new DefaultExample();\n System.out.println(DefaultExample.name);\n System.out.println(DefaultExample.age);\n }\n}"
},
{
"code": null,
"e": 3589,
"s": 3367,
"text": "OutputDeviceAssignedDefaultExample.java:5: error: cannot assign a value to final variable name\n name = \"Krishna\";\n ^\nDefaultExample.java:6: error: cannot assign a value to final variable age\n age = 25;\n ^\n2 errors"
}
] |
How can we disable cut, copy and paste functionality of a JTextArea in Java? | A JTextArea is a subclass of the JTextComponent class and it is a multi-line text component to display the text or allow a user to enter the text. A JTextArea can generate a CaretListener interface when we are trying to implement the functionality of the JTextArea. By default, the JTextArea class can support cut, copy and paste functionality, we can also disable or turn off the functionality of cut, copy and paste by using the getInputMap().put() method of JTextArea class. We can use KeyStroke.getKeyStroke("control X") for cut, KeyStroke.getKeyStroke("control C") for copy and KeyStroke.getKeyStroke("control V") for paste.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTextAreaCutCopyPasteDisableTest extends JFrame {
private JTextArea textArea;
private JButton cut, copy, paste;
private JPanel panel;
public JTextAreaCutCopyPasteDisableTest() {
setTitle("JTextAreaCutCopyPasteDisable Test");
setLayout(new BorderLayout());
panel = new JPanel();
textArea = new JTextArea();
cut = new JButton("Cut");
cut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
textArea.getInputMap().put(KeyStroke.getKeyStroke("control X"), "none");// disable cut
}
});
panel.add(cut);
copy = new JButton("Copy");
copy.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
textArea.getInputMap().put(KeyStroke.getKeyStroke("control C"), "none"); // disable copy
}
});
panel.add(copy);
paste = new JButton("Paste");
paste.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
textArea.getInputMap().put(KeyStroke.getKeyStroke("control V"), "none"); // disable paste
}
});
panel.add(paste);
add(panel, BorderLayout.NORTH);
add(new JScrollPane(textArea), BorderLayout.CENTER);
setSize(400, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String []args) {
new JTextAreaCutCopyPasteDisableTest();
}
} | [
{
"code": null,
"e": 1692,
"s": 1062,
"text": "A JTextArea is a subclass of the JTextComponent class and it is a multi-line text component to display the text or allow a user to enter the text. A JTextArea can generate a CaretListener interface when we are trying to implement the functionality of the JTextArea. By default, the JTextArea class can support cut, copy and paste functionality, we can also disable or turn off the functionality of cut, copy and paste by using the getInputMap().put() method of JTextArea class. We can use KeyStroke.getKeyStroke(\"control X\") for cut, KeyStroke.getKeyStroke(\"control C\") for copy and KeyStroke.getKeyStroke(\"control V\") for paste."
},
{
"code": null,
"e": 3308,
"s": 1692,
"text": "import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\npublic class JTextAreaCutCopyPasteDisableTest extends JFrame {\n private JTextArea textArea;\n private JButton cut, copy, paste;\n private JPanel panel;\n public JTextAreaCutCopyPasteDisableTest() {\n setTitle(\"JTextAreaCutCopyPasteDisable Test\");\n setLayout(new BorderLayout());\n panel = new JPanel();\n textArea = new JTextArea();\n cut = new JButton(\"Cut\");\n cut.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent ae) {\n textArea.getInputMap().put(KeyStroke.getKeyStroke(\"control X\"), \"none\");// disable cut \n }\n });\n panel.add(cut);\n copy = new JButton(\"Copy\");\n copy.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent ae) {\n textArea.getInputMap().put(KeyStroke.getKeyStroke(\"control C\"), \"none\"); // disable copy\n }\n });\n panel.add(copy);\n paste = new JButton(\"Paste\");\n paste.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent ae) {\n textArea.getInputMap().put(KeyStroke.getKeyStroke(\"control V\"), \"none\"); // disable paste\n }\n });\n panel.add(paste);\n add(panel, BorderLayout.NORTH);\n add(new JScrollPane(textArea), BorderLayout.CENTER);\n setSize(400, 250);\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setLocationRelativeTo(null);\n setVisible(true);\n }\n public static void main(String []args) {\n new JTextAreaCutCopyPasteDisableTest();\n }\n}"
}
] |
Data Science Project — Marketing Analytics & Data-Driven Solutions | by John Chen (Yueh-Han) | Towards Data Science | “I’m a data analyst, and the Chief Marketing Officer has told me that previous marketing campaigns have not been as effective as they were expected to be. I need to analyze the data set to understand this problem and propose data-driven solutions.”- The context was paraphrased and adjusted from Here.
(Clarification: the above context was quoted and adjusted from this Kaggle Data set. I want to credit the context, idea, and many inspirations of this project back to this Kaggle dataset provider. Thank you for sharing this amazing project idea and background information related to it!)
The dataset for this project is provided by Dr. Omar Romero-Hernandez. It is licensed as CC0: Public Domain, which states, “You can copy, modify, distribute and perform the work, even for commercial purposes, all without asking permission” You can also see the license status and download this dataset on this Kaggle page.
1. Assessing and Cleaning the data
2. Exploratory data analysis
3. Performing Statistical Analysis
4. Data Visualization and Further Analysis
5. Forming Data-Driven Solutions
6. Give an 8-Minute Presentation to Chief Marketing Officer in the company
Note: This article is not meant to explain every line of code but the most important part of each analysis step. Therefore, you may find some parts that are just descriptions of the results. If you are interested in the code itself, please check here.
Let’s first look at the feature Information:
ID: Customer’s unique identifier
Year_Birth: Customer’s birth year
Education: Customer’s education level
Marital_Status: Customer’s marital status
Income: Customer’s yearly household income
Kidhome: Number of children in customer’s household
Tennhome: Number of teenagers in customer’s household
Dt_Customer: Date of customer’s enrollment with the company
Recency: Number of days since customer’s last purchase
MntWines: Amount spent on wine in the last 2 years
MntFruits: Amount spent on fruits in the last 2 years
MntMeatProducts: Amount spent on meat in the last 2 years
MntFishProducts: Amount spent on fish in the last 2 years
MntSweetProducts: Amount spent on sweets in the last 2 years
MntGoldProds: Amount spent on gold in the last 2 years
NumDealsPurchase: Number of purchases made with a discount
NumWebPurchase: Number of purchases made through the company’s website
NumCatalogPurchase: Number of purchases made using a catalog
NumStorePurchase: Number of purchases made directly in stores
NumWebVisitsMonth: Number of visits to company’s website in the last month
AcceptedCmp3: 1 if customer accepted the offer in the 3rd campaign, 0 otherwise
AcceptedCmp4: 1 if customer accepted the offer in the 4th campaign, 0 otherwise
AcceptedCmp5: 1 if customer accepted the offer in the 5th campaign, 0 otherwise
AcceptedCmp1: 1 if customer accepted the offer in the 1st campaign, 0 otherwise
AcceptedCmp2: 2 if customer accepted the offer in the 1st campaign, 0 otherwise
Response: 1 if customer accepted the offer in the last campaign, 0 otherwise
Complain: 1 if a customer complained in the last 2 years, 0 otherwise
Country: Customer’s location
This dataset has 28 columns, 2240 rows, and 0 duplicated rows.
After assessing the data, I found that several issues:
1. There is a space in front of the income’s column name
2. There are dollar signs is the values of Income column
3. The “Income” column has 23 missing values
4. Income’s type is string
5. Dt_Customer’s type is string
Since data cleaning is not the main part of this project, let’s move forward to the next step. (You can find the codes on cleaning these issues here)
In this dataset’s Kaggle page, there are some EDA directions that the data publisher suggested following, and I decided to choose the following three questions to explore:
Are there any outliers? How will you wrangle/handle them?
Are there any useful variables that you can engineer with the given data?
Do you notice any patterns or anomalies in the data? Can you plot them?
Now let’s look at the questions one by one.
1. Are there any outliers? How will you wrangle/handle them?
I used the boxplots to visualize all the numerical features, and it will show the 5 numbers of the data: the lowest number that is not an outlier, Q1(25th percentile), Q2(50th percentile), Q3(75th percentile), and the highest number that is not an outlier.
Many columns have outliers, but most of them seem like natural outliers that came from the population. In contrast, the outliers in Year_birth seem like entry errors since it’s impossible that people born before 1900 still alive. Therefore, I will remove the outliers in Year_birth.
Outliers mean they are below or above 3 standard deviations from the mean.
2. Are there any useful variables that you can engineer with the given data?
After assessing the dataset, I list the new features that I think can be useful for the last analysis. For example, if we know the average month and the day of the week that the average person became a customer, then when we build a campaign on that day or in that month, it might help boost more first-time customers.
Join_month: The month that person became a customer, which can be engineered from “Dt_Customer”
Join_weekday: The day of the week that person became a customer, which can be engineered from “Dt_Customer”
Minorhome: The total number of minors in their family, which can be acquired by summing up by Kidhome and Teenhome.
Total_Mnt: Total amount spent in the last two years, which can be acquired by summing up all the “Mnt”-related columns
Total_num_purchase: Total number of purchases in the last two years, which can be acquired by summing up all the “Num”-related columns
Total_accept: Total amount a customer accepted the offer in all the marketing campaigns, which can be acquired by summing up all the “Accepted”-related columns and the “Response” column
“AOV”: AOV stands for the average order volume of each customer, which can be engineered by dividing Total_Mnt by Total_num_purchase
3. Do you notice any patterns or anomalies in the data? Can you plot them?
We can use a heatmap to see the correlations between each variable. When it gets bluer, they are more positively correlated, and when it gets redder, they are more negatively correlated.
Findings:
Patterns: 1. High-Income People — tend to spend more and purchase more. — tend to visit the company’s website less frequently than other people. — tend to has few numbers of purchases made with a discount
2. People having kids at home — tend to spend less and purchase less. — tend to has a high number of purchases made with a discount
3. People who purchased with high average order volume — tend to buy more wines and meat products — tend to make a high number of purchases made using a catalog — tend not to visit the company’s website.
Anomalies:1. Intuitively, I’d think the more complaints a customer has, the less they may spend on our store, but the number of complaints in the last two years has almost no correlation with the total amount spent in the last two years. => After further investigating the data, I found that it is because we only have 20 customers who complained in the last two years, but we have 2200 customers in total. So, because of the imbalanced ratio, they don’t correlate. The customer service department in the company has done a wonderful job in the last two years.
In this dataset’s Kaggle page, there are some statistical analysis questions that the data publisher suggested answering, and I decided to choose the following three questions to explore:
What factors are significantly related to the number of store purchases?
Your supervisor insists that people who buy gold are more conservative. Therefore, people who spent an above-average amount on gold in the last 2 years would have more in-store purchases. Justify or refute this statement using an appropriate statistical test
Fish has Omega 3 fatty acids, which are good for the brain. Accordingly, do “Married Ph.D. candidates” have a significant relation with the amount spent on fish?
Now let’s look at the questions one by one.
1. What factors are significantly related to the number of store purchases?
We can use the random forest to predict store purchases and then utilize the model’s feature importance score to rank the factors.
Result:
Mean Absolute Error: 0.78703125Mean Squared Error: 1.4546007812500001Root Mean Squared Error: 1.2060683153329252
The range of NumStorePurchases is 13, and the Root Mean Squared Error is only 1.2(less than 10% of the range), which means it is a reliable model.
Now, let’s use random forest’s feature importance score to see which factors most contribute to the NumStorePurchase.
We can now see that the top 7 factors are
1. Average order volume2. Total amount spent in the last two years3. Total number of purchases in the last two years4. Amount spent on wine in the last 2 years5. Number of purchases made using a catalog6. Number of visits to company's web site in the last month7. Total number of purchases through website in the last two years
However, we can’t tell whether each factor is positively or negatively correlated to the number of store purchases. We can use SHAP to explain it.
There is a famous article by Samuele Mazzanti explaining what SHAP is. Please check out here.
Finding:
The number of store purchases increases with the higher total amount spent(Total_Mnt), higher total purchase amount(Total_num_purchase), higher AOV, and higher amount of wines purchases(MntWines).The number of store purchases decreases with more website visits(NumWebVisitsMonth), a higher number of purchases through the catalog(NumCatalogPurchases), and a higher number of purchases through websites(NumWebPurchases).
The number of store purchases increases with the higher total amount spent(Total_Mnt), higher total purchase amount(Total_num_purchase), higher AOV, and higher amount of wines purchases(MntWines).
The number of store purchases decreases with more website visits(NumWebVisitsMonth), a higher number of purchases through the catalog(NumCatalogPurchases), and a higher number of purchases through websites(NumWebPurchases).
Summary: People who mostly shop at stores tend to buy more wines, have a higher average order volume, and shop less through the internet or catalog.
2. Your supervisor insists that people who buy gold are more conservative. Therefore, people who spent an above average amount on gold in the last 2 years would have more in store purchases. Justify or refute this statement using an appropriate statistical test.
To statistically verify this claim, we need to use a correlation test to see if MntGoldProds and NumStorePurchases are positively correlated. First, let’s look at the scatterplot of the two variables.
As we can see, there is a very vague trend that says as MntGoldProds increases, NumStorePurchases also increases. Now, let’s look at the correlation test.
Pearson correlation (r): 0.38326418634704296Pearson p-value: 3.4668974417790955e-79
We got a Pearson correlation of 0.38 and a p-value of almost zero, which states that they are statistically significant and have a positive correlation. (If the p-value is > 0.05, we will fail to reject the null hypothesis, where they do not correlate.)
3. Fish has Omega 3 fatty acids which are good for the brain. Accordingly, do “Married PhD candidates” have a significant relation with amount spent on fish?
To statistically verify these, I first divide the data into two groups. One is the married Ph.D. group and the rest. And then, we can use a boxplot to visualize these two groups to see if they are different. Lastly, we can use a t-test to test whether their mean is similar.
This plot shows that the rest of the customers spent more on fish products as its 50th percentile is higher than the married Ph.D. group. Now, let’s look at the t-test.
T-test p-value: 0.005297012242158541
Since the p-value is less than 0.05, I concluded that we reject the null hypothesis, meaning that their means are different, but the Married Ph.D.’s mean is lower than the rest, as we can see from the graph.
Here are the questions that I’d be exploring using data visualization:
Which marketing campaign is most successful?
What does the average customer look like for this company? Which products are performing best?
Investigate the differences in the customer characteristics and purchases behaviors between the most successful campaign and the rest.
Now let’s look at the questions one by one.
1. Which marketing campaign is most successful?
Response means the last marketing campaign, which is the most successful one. It performed nearly twice as well as the previous campaigns, except campaign 2.
2. What does the average customer look like for this company? Which products are performing best?
After using .mean(), I found that an average customer...
has an annual income of 52200 dollars
had purchased 49 days ago
has an AOV of 26.8 dollars
has spent 605 dollars
has purchased 20 times
became a customer in mid-June
became a customer on Thursday
spent most on wines(300 dollars) and then meat products(165 dollars)
spent least on fruit(26 dollars) and sweet products(27 dollars)
3. Investigate the differences in the customer characteristics and purchases behaviors between the most successful campaign and the rest.
Now that we know the last campaign is the most successful one, we can further investigate the differences in the customer characteristics and purchases behaviors(listed below) between the most successful campaign, the last one, and the rest of the campaigns, campaign 1–5.
The last campaign attracted more valuable customers in terms of AOV, the total amount spent, and the total number of purchases compared to the customers attracted by the previous campaigns.
In terms of product categories, the customers in the last campaign spent nearly two times more money on meat products and wines compared to the customers in the previous campaigns.
Regarding purchasing channels, the customers in the last campaign purchased more evenly through stores, websites, and catalogs, whereas the customers in the previous campaigns mostly purchased through stores and websites.
The customers in the last campaign earned 20% more salary than the customers in the previous campaigns.
Let’s look at the proportion change of each country from the previous campaigns to the most successful campaign.
Spain has relatively more customers (+4%), and India has fewer customers (-3%) attracted to the last campaign.
I’m a data analyst, and the Chief Marketing Officer has told me that previous marketing campaigns have not been as effective as they were expected to be. I need to analyze the data set to understand this problem and propose data-driven solutions.
To form data-driven solutions, I first summarize all the insights I got from the analytics, then I use those insights to form actionable strategies.
Summaries of insights:
1. The last campaign performed nearly twice as good as the previous campaigns
The last campaign attracted more valuable customers in terms of AOV, the total amount spent, and the total number of purchases, compared to the customers who were attracted by the previous campaigns.
Spain has relatively more customers (+4%) and India has fewer customers (-3%) that were attracted to the last campaign
In terms of product categories, the customers in the last campaign spent nearly two times more money on meat products and wines compared to the customers in the previous campaigns.
In terms of purchasing channels, the customers in the last campaign purchased more evenly through stores, websites, and catalogs, whereas the customers in the previous campaigns mostly purchased through stores and websites.
The customers in the last campaign earned 20% more salary than the customers in the previous campaigns.
2. Most customers purchase through physical stores, where people tend to spend more amount per purchase. The reason might be the customers had more impulsive purchases when they saw other similar products in stores.
3. People having kids at home are less valuable customers as they...
tend to purchase less
tend to has a high number of purchases made with a discount
4. The average customer...
became a customer on Thursdays
became a customer in Mid-June
On Acquisition:
Keep using the same marketing techniques in the last campaign, but with a focus on promoting meat products and winesSpend more marketing budget in Spain, and less in IndiaHave a brand discount day on Thursday or a brand discount month in June to attract new customers
Keep using the same marketing techniques in the last campaign, but with a focus on promoting meat products and wines
Spend more marketing budget in Spain, and less in India
Have a brand discount day on Thursday or a brand discount month in June to attract new customers
On Increasing revenue:
Have marketing campaigns to convert customers who shop mostly on a website or catalog to in-store purchasers because most in-store purchases have a high average order volume.Build a loyalty program to make high-income customers loyal as long as possible
Have marketing campaigns to convert customers who shop mostly on a website or catalog to in-store purchasers because most in-store purchases have a high average order volume.
Build a loyalty program to make high-income customers loyal as long as possible
I also explained the context and the basic information of this dataset in this video, so if you want to see the presentation, please jump to 2:20.
Thank you for reading to the end! If you are interested in the full code of this project, please check out my Github. Besides, I love feedback. If any part is unclear or should be done better, please reach out to me. Here is my LinkedIn or contact me through my email([email protected]) | [
{
"code": null,
"e": 474,
"s": 172,
"text": "“I’m a data analyst, and the Chief Marketing Officer has told me that previous marketing campaigns have not been as effective as they were expected to be. I need to analyze the data set to understand this problem and propose data-driven solutions.”- The context was paraphrased and adjusted from Here."
},
{
"code": null,
"e": 762,
"s": 474,
"text": "(Clarification: the above context was quoted and adjusted from this Kaggle Data set. I want to credit the context, idea, and many inspirations of this project back to this Kaggle dataset provider. Thank you for sharing this amazing project idea and background information related to it!)"
},
{
"code": null,
"e": 1085,
"s": 762,
"text": "The dataset for this project is provided by Dr. Omar Romero-Hernandez. It is licensed as CC0: Public Domain, which states, “You can copy, modify, distribute and perform the work, even for commercial purposes, all without asking permission” You can also see the license status and download this dataset on this Kaggle page."
},
{
"code": null,
"e": 1120,
"s": 1085,
"text": "1. Assessing and Cleaning the data"
},
{
"code": null,
"e": 1149,
"s": 1120,
"text": "2. Exploratory data analysis"
},
{
"code": null,
"e": 1184,
"s": 1149,
"text": "3. Performing Statistical Analysis"
},
{
"code": null,
"e": 1227,
"s": 1184,
"text": "4. Data Visualization and Further Analysis"
},
{
"code": null,
"e": 1260,
"s": 1227,
"text": "5. Forming Data-Driven Solutions"
},
{
"code": null,
"e": 1335,
"s": 1260,
"text": "6. Give an 8-Minute Presentation to Chief Marketing Officer in the company"
},
{
"code": null,
"e": 1587,
"s": 1335,
"text": "Note: This article is not meant to explain every line of code but the most important part of each analysis step. Therefore, you may find some parts that are just descriptions of the results. If you are interested in the code itself, please check here."
},
{
"code": null,
"e": 1632,
"s": 1587,
"text": "Let’s first look at the feature Information:"
},
{
"code": null,
"e": 1665,
"s": 1632,
"text": "ID: Customer’s unique identifier"
},
{
"code": null,
"e": 1699,
"s": 1665,
"text": "Year_Birth: Customer’s birth year"
},
{
"code": null,
"e": 1737,
"s": 1699,
"text": "Education: Customer’s education level"
},
{
"code": null,
"e": 1779,
"s": 1737,
"text": "Marital_Status: Customer’s marital status"
},
{
"code": null,
"e": 1822,
"s": 1779,
"text": "Income: Customer’s yearly household income"
},
{
"code": null,
"e": 1874,
"s": 1822,
"text": "Kidhome: Number of children in customer’s household"
},
{
"code": null,
"e": 1928,
"s": 1874,
"text": "Tennhome: Number of teenagers in customer’s household"
},
{
"code": null,
"e": 1988,
"s": 1928,
"text": "Dt_Customer: Date of customer’s enrollment with the company"
},
{
"code": null,
"e": 2043,
"s": 1988,
"text": "Recency: Number of days since customer’s last purchase"
},
{
"code": null,
"e": 2094,
"s": 2043,
"text": "MntWines: Amount spent on wine in the last 2 years"
},
{
"code": null,
"e": 2148,
"s": 2094,
"text": "MntFruits: Amount spent on fruits in the last 2 years"
},
{
"code": null,
"e": 2206,
"s": 2148,
"text": "MntMeatProducts: Amount spent on meat in the last 2 years"
},
{
"code": null,
"e": 2264,
"s": 2206,
"text": "MntFishProducts: Amount spent on fish in the last 2 years"
},
{
"code": null,
"e": 2325,
"s": 2264,
"text": "MntSweetProducts: Amount spent on sweets in the last 2 years"
},
{
"code": null,
"e": 2380,
"s": 2325,
"text": "MntGoldProds: Amount spent on gold in the last 2 years"
},
{
"code": null,
"e": 2439,
"s": 2380,
"text": "NumDealsPurchase: Number of purchases made with a discount"
},
{
"code": null,
"e": 2510,
"s": 2439,
"text": "NumWebPurchase: Number of purchases made through the company’s website"
},
{
"code": null,
"e": 2571,
"s": 2510,
"text": "NumCatalogPurchase: Number of purchases made using a catalog"
},
{
"code": null,
"e": 2633,
"s": 2571,
"text": "NumStorePurchase: Number of purchases made directly in stores"
},
{
"code": null,
"e": 2708,
"s": 2633,
"text": "NumWebVisitsMonth: Number of visits to company’s website in the last month"
},
{
"code": null,
"e": 2788,
"s": 2708,
"text": "AcceptedCmp3: 1 if customer accepted the offer in the 3rd campaign, 0 otherwise"
},
{
"code": null,
"e": 2868,
"s": 2788,
"text": "AcceptedCmp4: 1 if customer accepted the offer in the 4th campaign, 0 otherwise"
},
{
"code": null,
"e": 2948,
"s": 2868,
"text": "AcceptedCmp5: 1 if customer accepted the offer in the 5th campaign, 0 otherwise"
},
{
"code": null,
"e": 3028,
"s": 2948,
"text": "AcceptedCmp1: 1 if customer accepted the offer in the 1st campaign, 0 otherwise"
},
{
"code": null,
"e": 3108,
"s": 3028,
"text": "AcceptedCmp2: 2 if customer accepted the offer in the 1st campaign, 0 otherwise"
},
{
"code": null,
"e": 3185,
"s": 3108,
"text": "Response: 1 if customer accepted the offer in the last campaign, 0 otherwise"
},
{
"code": null,
"e": 3255,
"s": 3185,
"text": "Complain: 1 if a customer complained in the last 2 years, 0 otherwise"
},
{
"code": null,
"e": 3284,
"s": 3255,
"text": "Country: Customer’s location"
},
{
"code": null,
"e": 3347,
"s": 3284,
"text": "This dataset has 28 columns, 2240 rows, and 0 duplicated rows."
},
{
"code": null,
"e": 3402,
"s": 3347,
"text": "After assessing the data, I found that several issues:"
},
{
"code": null,
"e": 3459,
"s": 3402,
"text": "1. There is a space in front of the income’s column name"
},
{
"code": null,
"e": 3516,
"s": 3459,
"text": "2. There are dollar signs is the values of Income column"
},
{
"code": null,
"e": 3561,
"s": 3516,
"text": "3. The “Income” column has 23 missing values"
},
{
"code": null,
"e": 3588,
"s": 3561,
"text": "4. Income’s type is string"
},
{
"code": null,
"e": 3620,
"s": 3588,
"text": "5. Dt_Customer’s type is string"
},
{
"code": null,
"e": 3770,
"s": 3620,
"text": "Since data cleaning is not the main part of this project, let’s move forward to the next step. (You can find the codes on cleaning these issues here)"
},
{
"code": null,
"e": 3942,
"s": 3770,
"text": "In this dataset’s Kaggle page, there are some EDA directions that the data publisher suggested following, and I decided to choose the following three questions to explore:"
},
{
"code": null,
"e": 4000,
"s": 3942,
"text": "Are there any outliers? How will you wrangle/handle them?"
},
{
"code": null,
"e": 4074,
"s": 4000,
"text": "Are there any useful variables that you can engineer with the given data?"
},
{
"code": null,
"e": 4146,
"s": 4074,
"text": "Do you notice any patterns or anomalies in the data? Can you plot them?"
},
{
"code": null,
"e": 4190,
"s": 4146,
"text": "Now let’s look at the questions one by one."
},
{
"code": null,
"e": 4251,
"s": 4190,
"text": "1. Are there any outliers? How will you wrangle/handle them?"
},
{
"code": null,
"e": 4508,
"s": 4251,
"text": "I used the boxplots to visualize all the numerical features, and it will show the 5 numbers of the data: the lowest number that is not an outlier, Q1(25th percentile), Q2(50th percentile), Q3(75th percentile), and the highest number that is not an outlier."
},
{
"code": null,
"e": 4791,
"s": 4508,
"text": "Many columns have outliers, but most of them seem like natural outliers that came from the population. In contrast, the outliers in Year_birth seem like entry errors since it’s impossible that people born before 1900 still alive. Therefore, I will remove the outliers in Year_birth."
},
{
"code": null,
"e": 4866,
"s": 4791,
"text": "Outliers mean they are below or above 3 standard deviations from the mean."
},
{
"code": null,
"e": 4943,
"s": 4866,
"text": "2. Are there any useful variables that you can engineer with the given data?"
},
{
"code": null,
"e": 5262,
"s": 4943,
"text": "After assessing the dataset, I list the new features that I think can be useful for the last analysis. For example, if we know the average month and the day of the week that the average person became a customer, then when we build a campaign on that day or in that month, it might help boost more first-time customers."
},
{
"code": null,
"e": 5358,
"s": 5262,
"text": "Join_month: The month that person became a customer, which can be engineered from “Dt_Customer”"
},
{
"code": null,
"e": 5466,
"s": 5358,
"text": "Join_weekday: The day of the week that person became a customer, which can be engineered from “Dt_Customer”"
},
{
"code": null,
"e": 5582,
"s": 5466,
"text": "Minorhome: The total number of minors in their family, which can be acquired by summing up by Kidhome and Teenhome."
},
{
"code": null,
"e": 5701,
"s": 5582,
"text": "Total_Mnt: Total amount spent in the last two years, which can be acquired by summing up all the “Mnt”-related columns"
},
{
"code": null,
"e": 5836,
"s": 5701,
"text": "Total_num_purchase: Total number of purchases in the last two years, which can be acquired by summing up all the “Num”-related columns"
},
{
"code": null,
"e": 6022,
"s": 5836,
"text": "Total_accept: Total amount a customer accepted the offer in all the marketing campaigns, which can be acquired by summing up all the “Accepted”-related columns and the “Response” column"
},
{
"code": null,
"e": 6155,
"s": 6022,
"text": "“AOV”: AOV stands for the average order volume of each customer, which can be engineered by dividing Total_Mnt by Total_num_purchase"
},
{
"code": null,
"e": 6230,
"s": 6155,
"text": "3. Do you notice any patterns or anomalies in the data? Can you plot them?"
},
{
"code": null,
"e": 6417,
"s": 6230,
"text": "We can use a heatmap to see the correlations between each variable. When it gets bluer, they are more positively correlated, and when it gets redder, they are more negatively correlated."
},
{
"code": null,
"e": 6427,
"s": 6417,
"text": "Findings:"
},
{
"code": null,
"e": 6633,
"s": 6427,
"text": "Patterns: 1. High-Income People — tend to spend more and purchase more. — tend to visit the company’s website less frequently than other people. — tend to has few numbers of purchases made with a discount"
},
{
"code": null,
"e": 6765,
"s": 6633,
"text": "2. People having kids at home — tend to spend less and purchase less. — tend to has a high number of purchases made with a discount"
},
{
"code": null,
"e": 6970,
"s": 6765,
"text": "3. People who purchased with high average order volume — tend to buy more wines and meat products — tend to make a high number of purchases made using a catalog — tend not to visit the company’s website."
},
{
"code": null,
"e": 7531,
"s": 6970,
"text": "Anomalies:1. Intuitively, I’d think the more complaints a customer has, the less they may spend on our store, but the number of complaints in the last two years has almost no correlation with the total amount spent in the last two years. => After further investigating the data, I found that it is because we only have 20 customers who complained in the last two years, but we have 2200 customers in total. So, because of the imbalanced ratio, they don’t correlate. The customer service department in the company has done a wonderful job in the last two years."
},
{
"code": null,
"e": 7719,
"s": 7531,
"text": "In this dataset’s Kaggle page, there are some statistical analysis questions that the data publisher suggested answering, and I decided to choose the following three questions to explore:"
},
{
"code": null,
"e": 7792,
"s": 7719,
"text": "What factors are significantly related to the number of store purchases?"
},
{
"code": null,
"e": 8051,
"s": 7792,
"text": "Your supervisor insists that people who buy gold are more conservative. Therefore, people who spent an above-average amount on gold in the last 2 years would have more in-store purchases. Justify or refute this statement using an appropriate statistical test"
},
{
"code": null,
"e": 8213,
"s": 8051,
"text": "Fish has Omega 3 fatty acids, which are good for the brain. Accordingly, do “Married Ph.D. candidates” have a significant relation with the amount spent on fish?"
},
{
"code": null,
"e": 8257,
"s": 8213,
"text": "Now let’s look at the questions one by one."
},
{
"code": null,
"e": 8333,
"s": 8257,
"text": "1. What factors are significantly related to the number of store purchases?"
},
{
"code": null,
"e": 8464,
"s": 8333,
"text": "We can use the random forest to predict store purchases and then utilize the model’s feature importance score to rank the factors."
},
{
"code": null,
"e": 8472,
"s": 8464,
"text": "Result:"
},
{
"code": null,
"e": 8585,
"s": 8472,
"text": "Mean Absolute Error: 0.78703125Mean Squared Error: 1.4546007812500001Root Mean Squared Error: 1.2060683153329252"
},
{
"code": null,
"e": 8732,
"s": 8585,
"text": "The range of NumStorePurchases is 13, and the Root Mean Squared Error is only 1.2(less than 10% of the range), which means it is a reliable model."
},
{
"code": null,
"e": 8850,
"s": 8732,
"text": "Now, let’s use random forest’s feature importance score to see which factors most contribute to the NumStorePurchase."
},
{
"code": null,
"e": 8892,
"s": 8850,
"text": "We can now see that the top 7 factors are"
},
{
"code": null,
"e": 9220,
"s": 8892,
"text": "1. Average order volume2. Total amount spent in the last two years3. Total number of purchases in the last two years4. Amount spent on wine in the last 2 years5. Number of purchases made using a catalog6. Number of visits to company's web site in the last month7. Total number of purchases through website in the last two years"
},
{
"code": null,
"e": 9367,
"s": 9220,
"text": "However, we can’t tell whether each factor is positively or negatively correlated to the number of store purchases. We can use SHAP to explain it."
},
{
"code": null,
"e": 9461,
"s": 9367,
"text": "There is a famous article by Samuele Mazzanti explaining what SHAP is. Please check out here."
},
{
"code": null,
"e": 9470,
"s": 9461,
"text": "Finding:"
},
{
"code": null,
"e": 9890,
"s": 9470,
"text": "The number of store purchases increases with the higher total amount spent(Total_Mnt), higher total purchase amount(Total_num_purchase), higher AOV, and higher amount of wines purchases(MntWines).The number of store purchases decreases with more website visits(NumWebVisitsMonth), a higher number of purchases through the catalog(NumCatalogPurchases), and a higher number of purchases through websites(NumWebPurchases)."
},
{
"code": null,
"e": 10087,
"s": 9890,
"text": "The number of store purchases increases with the higher total amount spent(Total_Mnt), higher total purchase amount(Total_num_purchase), higher AOV, and higher amount of wines purchases(MntWines)."
},
{
"code": null,
"e": 10311,
"s": 10087,
"text": "The number of store purchases decreases with more website visits(NumWebVisitsMonth), a higher number of purchases through the catalog(NumCatalogPurchases), and a higher number of purchases through websites(NumWebPurchases)."
},
{
"code": null,
"e": 10460,
"s": 10311,
"text": "Summary: People who mostly shop at stores tend to buy more wines, have a higher average order volume, and shop less through the internet or catalog."
},
{
"code": null,
"e": 10723,
"s": 10460,
"text": "2. Your supervisor insists that people who buy gold are more conservative. Therefore, people who spent an above average amount on gold in the last 2 years would have more in store purchases. Justify or refute this statement using an appropriate statistical test."
},
{
"code": null,
"e": 10924,
"s": 10723,
"text": "To statistically verify this claim, we need to use a correlation test to see if MntGoldProds and NumStorePurchases are positively correlated. First, let’s look at the scatterplot of the two variables."
},
{
"code": null,
"e": 11079,
"s": 10924,
"text": "As we can see, there is a very vague trend that says as MntGoldProds increases, NumStorePurchases also increases. Now, let’s look at the correlation test."
},
{
"code": null,
"e": 11165,
"s": 11079,
"text": "Pearson correlation (r): 0.38326418634704296Pearson p-value: 3.4668974417790955e-79"
},
{
"code": null,
"e": 11419,
"s": 11165,
"text": "We got a Pearson correlation of 0.38 and a p-value of almost zero, which states that they are statistically significant and have a positive correlation. (If the p-value is > 0.05, we will fail to reject the null hypothesis, where they do not correlate.)"
},
{
"code": null,
"e": 11577,
"s": 11419,
"text": "3. Fish has Omega 3 fatty acids which are good for the brain. Accordingly, do “Married PhD candidates” have a significant relation with amount spent on fish?"
},
{
"code": null,
"e": 11852,
"s": 11577,
"text": "To statistically verify these, I first divide the data into two groups. One is the married Ph.D. group and the rest. And then, we can use a boxplot to visualize these two groups to see if they are different. Lastly, we can use a t-test to test whether their mean is similar."
},
{
"code": null,
"e": 12021,
"s": 11852,
"text": "This plot shows that the rest of the customers spent more on fish products as its 50th percentile is higher than the married Ph.D. group. Now, let’s look at the t-test."
},
{
"code": null,
"e": 12059,
"s": 12021,
"text": "T-test p-value: 0.005297012242158541"
},
{
"code": null,
"e": 12267,
"s": 12059,
"text": "Since the p-value is less than 0.05, I concluded that we reject the null hypothesis, meaning that their means are different, but the Married Ph.D.’s mean is lower than the rest, as we can see from the graph."
},
{
"code": null,
"e": 12338,
"s": 12267,
"text": "Here are the questions that I’d be exploring using data visualization:"
},
{
"code": null,
"e": 12383,
"s": 12338,
"text": "Which marketing campaign is most successful?"
},
{
"code": null,
"e": 12478,
"s": 12383,
"text": "What does the average customer look like for this company? Which products are performing best?"
},
{
"code": null,
"e": 12613,
"s": 12478,
"text": "Investigate the differences in the customer characteristics and purchases behaviors between the most successful campaign and the rest."
},
{
"code": null,
"e": 12657,
"s": 12613,
"text": "Now let’s look at the questions one by one."
},
{
"code": null,
"e": 12705,
"s": 12657,
"text": "1. Which marketing campaign is most successful?"
},
{
"code": null,
"e": 12863,
"s": 12705,
"text": "Response means the last marketing campaign, which is the most successful one. It performed nearly twice as well as the previous campaigns, except campaign 2."
},
{
"code": null,
"e": 12961,
"s": 12863,
"text": "2. What does the average customer look like for this company? Which products are performing best?"
},
{
"code": null,
"e": 13018,
"s": 12961,
"text": "After using .mean(), I found that an average customer..."
},
{
"code": null,
"e": 13056,
"s": 13018,
"text": "has an annual income of 52200 dollars"
},
{
"code": null,
"e": 13082,
"s": 13056,
"text": "had purchased 49 days ago"
},
{
"code": null,
"e": 13109,
"s": 13082,
"text": "has an AOV of 26.8 dollars"
},
{
"code": null,
"e": 13131,
"s": 13109,
"text": "has spent 605 dollars"
},
{
"code": null,
"e": 13154,
"s": 13131,
"text": "has purchased 20 times"
},
{
"code": null,
"e": 13184,
"s": 13154,
"text": "became a customer in mid-June"
},
{
"code": null,
"e": 13214,
"s": 13184,
"text": "became a customer on Thursday"
},
{
"code": null,
"e": 13283,
"s": 13214,
"text": "spent most on wines(300 dollars) and then meat products(165 dollars)"
},
{
"code": null,
"e": 13347,
"s": 13283,
"text": "spent least on fruit(26 dollars) and sweet products(27 dollars)"
},
{
"code": null,
"e": 13485,
"s": 13347,
"text": "3. Investigate the differences in the customer characteristics and purchases behaviors between the most successful campaign and the rest."
},
{
"code": null,
"e": 13758,
"s": 13485,
"text": "Now that we know the last campaign is the most successful one, we can further investigate the differences in the customer characteristics and purchases behaviors(listed below) between the most successful campaign, the last one, and the rest of the campaigns, campaign 1–5."
},
{
"code": null,
"e": 13948,
"s": 13758,
"text": "The last campaign attracted more valuable customers in terms of AOV, the total amount spent, and the total number of purchases compared to the customers attracted by the previous campaigns."
},
{
"code": null,
"e": 14129,
"s": 13948,
"text": "In terms of product categories, the customers in the last campaign spent nearly two times more money on meat products and wines compared to the customers in the previous campaigns."
},
{
"code": null,
"e": 14351,
"s": 14129,
"text": "Regarding purchasing channels, the customers in the last campaign purchased more evenly through stores, websites, and catalogs, whereas the customers in the previous campaigns mostly purchased through stores and websites."
},
{
"code": null,
"e": 14455,
"s": 14351,
"text": "The customers in the last campaign earned 20% more salary than the customers in the previous campaigns."
},
{
"code": null,
"e": 14568,
"s": 14455,
"text": "Let’s look at the proportion change of each country from the previous campaigns to the most successful campaign."
},
{
"code": null,
"e": 14679,
"s": 14568,
"text": "Spain has relatively more customers (+4%), and India has fewer customers (-3%) attracted to the last campaign."
},
{
"code": null,
"e": 14926,
"s": 14679,
"text": "I’m a data analyst, and the Chief Marketing Officer has told me that previous marketing campaigns have not been as effective as they were expected to be. I need to analyze the data set to understand this problem and propose data-driven solutions."
},
{
"code": null,
"e": 15075,
"s": 14926,
"text": "To form data-driven solutions, I first summarize all the insights I got from the analytics, then I use those insights to form actionable strategies."
},
{
"code": null,
"e": 15098,
"s": 15075,
"text": "Summaries of insights:"
},
{
"code": null,
"e": 15176,
"s": 15098,
"text": "1. The last campaign performed nearly twice as good as the previous campaigns"
},
{
"code": null,
"e": 15376,
"s": 15176,
"text": "The last campaign attracted more valuable customers in terms of AOV, the total amount spent, and the total number of purchases, compared to the customers who were attracted by the previous campaigns."
},
{
"code": null,
"e": 15495,
"s": 15376,
"text": "Spain has relatively more customers (+4%) and India has fewer customers (-3%) that were attracted to the last campaign"
},
{
"code": null,
"e": 15676,
"s": 15495,
"text": "In terms of product categories, the customers in the last campaign spent nearly two times more money on meat products and wines compared to the customers in the previous campaigns."
},
{
"code": null,
"e": 15900,
"s": 15676,
"text": "In terms of purchasing channels, the customers in the last campaign purchased more evenly through stores, websites, and catalogs, whereas the customers in the previous campaigns mostly purchased through stores and websites."
},
{
"code": null,
"e": 16004,
"s": 15900,
"text": "The customers in the last campaign earned 20% more salary than the customers in the previous campaigns."
},
{
"code": null,
"e": 16220,
"s": 16004,
"text": "2. Most customers purchase through physical stores, where people tend to spend more amount per purchase. The reason might be the customers had more impulsive purchases when they saw other similar products in stores."
},
{
"code": null,
"e": 16289,
"s": 16220,
"text": "3. People having kids at home are less valuable customers as they..."
},
{
"code": null,
"e": 16311,
"s": 16289,
"text": "tend to purchase less"
},
{
"code": null,
"e": 16371,
"s": 16311,
"text": "tend to has a high number of purchases made with a discount"
},
{
"code": null,
"e": 16398,
"s": 16371,
"text": "4. The average customer..."
},
{
"code": null,
"e": 16429,
"s": 16398,
"text": "became a customer on Thursdays"
},
{
"code": null,
"e": 16459,
"s": 16429,
"text": "became a customer in Mid-June"
},
{
"code": null,
"e": 16475,
"s": 16459,
"text": "On Acquisition:"
},
{
"code": null,
"e": 16743,
"s": 16475,
"text": "Keep using the same marketing techniques in the last campaign, but with a focus on promoting meat products and winesSpend more marketing budget in Spain, and less in IndiaHave a brand discount day on Thursday or a brand discount month in June to attract new customers"
},
{
"code": null,
"e": 16860,
"s": 16743,
"text": "Keep using the same marketing techniques in the last campaign, but with a focus on promoting meat products and wines"
},
{
"code": null,
"e": 16916,
"s": 16860,
"text": "Spend more marketing budget in Spain, and less in India"
},
{
"code": null,
"e": 17013,
"s": 16916,
"text": "Have a brand discount day on Thursday or a brand discount month in June to attract new customers"
},
{
"code": null,
"e": 17036,
"s": 17013,
"text": "On Increasing revenue:"
},
{
"code": null,
"e": 17290,
"s": 17036,
"text": "Have marketing campaigns to convert customers who shop mostly on a website or catalog to in-store purchasers because most in-store purchases have a high average order volume.Build a loyalty program to make high-income customers loyal as long as possible"
},
{
"code": null,
"e": 17465,
"s": 17290,
"text": "Have marketing campaigns to convert customers who shop mostly on a website or catalog to in-store purchasers because most in-store purchases have a high average order volume."
},
{
"code": null,
"e": 17545,
"s": 17465,
"text": "Build a loyalty program to make high-income customers loyal as long as possible"
},
{
"code": null,
"e": 17692,
"s": 17545,
"text": "I also explained the context and the basic information of this dataset in this video, so if you want to see the presentation, please jump to 2:20."
}
] |
Equation of circle when three points on the circle are given - GeeksforGeeks | 19 Jul, 2021
Given three coordinates that lie on a circle, (x1, y1), (x2, y2), and (x3, y3). The task is to find the equation of the circle and then print the centre and the radius of the circle. Equation of circle in general form is x2 + y2 + 2gx + 2fy + c = 0 and in radius form is (x – h)2 + (y -k)2 = r2, where (h, k) is the centre of the circle and r is the radius.Examples:
Input: x1 = 1, y1 = 0, x2 = -1, y2 = 0, x3 = 0, y3 = 1 Output: Centre = (0, 0) Radius = 1 The equation of the circle is x2 + y2 = 1.Input: x1 = 1, y1 = -6, x2 = 2, y2 = 1, x3 = 5, y3 = 2 Output: Centre = (5, -3) Radius = 5 Equation of the circle is x2 + y2 -10x + 6y + 9 = 0
Approach: As we know all three-point lie on the circle, so they will satisfy the equation of a circle and by putting them in the general equation we get three equations with three variables g, f, and c, and by further solving we can get the values. We can derive the formula to obtain the value of g, f, and c as:
Putting coordinates in eqn of circle, we get: x12 + y12 + 2gx1 + 2fy1 + c = 0 – (1) x22 + y22 + 2gx2 + 2fy2 + c = 0 – (2) x32 + y32 + 2gx3 + 2fy3 + c = 0 – (3)From (1) we get, 2gx1 = -x12 – y12 – 2fy1 – c – (4) From (1) we get, c = -x12 – y12 – 2gx1 – 2fy1 – (5) From (3) we get, 2fy3 = -x32 – y32 – 2gx3 – c – (6)Subtracting eqn (2) from eqn (1) we get, 2g( x1 – x2 ) = ( x22 -x12 ) + ( y22 – y12 ) + 2f( y2 – y1 ) – (A)Now putting eqn (5) in (6) we get, 2fy3 = -x32 – y32 – 2gx3 + x12 + y12 + 2gx1 + 2fy1 – (7)Now putting value of 2g from eqn (A) in (7) we get, 2f = ( ( x12 – x32 )( x1 – x2 ) +( y12 – y32 )( x1 – x2 ) + ( x22 – x12 )( x1 – x3 ) + ( y22 – y12 )( x1 – x3 ) ) / ( y3 – y1 )( x1 – x2 ) – ( y2 – y1 )( x1 – x3 )Similarly we can obtain the values of 2g : 2g = ( ( x12 – x32 )( y1 – x2 ) +( y12 – y32 )( y1 – y2 ) + ( x22 – x12 )( y1 – y3) + ( y22 – y12 )( y1 – y3 ) ) / ( x3 -x1 )( y1 – y2 ) – ( x2 – x1 )( y1 – y3 )Putting 2g and 2f in eqn (5) we get the value of c and know we had the equation of circle as x2 + y2 + 2gx + 2fy + c = 0
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to find the circle on// which the given three points lievoid findCircle(int x1, int y1, int x2, int y2, int x3, int y3){ int x12 = x1 - x2; int x13 = x1 - x3; int y12 = y1 - y2; int y13 = y1 - y3; int y31 = y3 - y1; int y21 = y2 - y1; int x31 = x3 - x1; int x21 = x2 - x1; // x1^2 - x3^2 int sx13 = pow(x1, 2) - pow(x3, 2); // y1^2 - y3^2 int sy13 = pow(y1, 2) - pow(y3, 2); int sx21 = pow(x2, 2) - pow(x1, 2); int sy21 = pow(y2, 2) - pow(y1, 2); int f = ((sx13) * (x12) + (sy13) * (x12) + (sx21) * (x13) + (sy21) * (x13)) / (2 * ((y31) * (x12) - (y21) * (x13))); int g = ((sx13) * (y12) + (sy13) * (y12) + (sx21) * (y13) + (sy21) * (y13)) / (2 * ((x31) * (y12) - (x21) * (y13))); int c = -pow(x1, 2) - pow(y1, 2) - 2 * g * x1 - 2 * f * y1; // eqn of circle be x^2 + y^2 + 2*g*x + 2*f*y + c = 0 // where centre is (h = -g, k = -f) and radius r // as r^2 = h^2 + k^2 - c int h = -g; int k = -f; int sqr_of_r = h * h + k * k - c; // r is the radius float r = sqrt(sqr_of_r); cout << "Centre = (" << h << ", " << k << ")" << endl; cout << "Radius = " << r;} // Driver codeint main(){ int x1 = 1, y1 = 1; int x2 = 2, y2 = 4; int x3 = 5, y3 = 3; findCircle(x1, y1, x2, y2, x3, y3); return 0;}
// Java implementation of the approachimport java.text.*; class GFG{ // Function to find the circle on// which the given three points liestatic void findCircle(int x1, int y1, int x2, int y2, int x3, int y3){ int x12 = x1 - x2; int x13 = x1 - x3; int y12 = y1 - y2; int y13 = y1 - y3; int y31 = y3 - y1; int y21 = y2 - y1; int x31 = x3 - x1; int x21 = x2 - x1; // x1^2 - x3^2 int sx13 = (int)(Math.pow(x1, 2) - Math.pow(x3, 2)); // y1^2 - y3^2 int sy13 = (int)(Math.pow(y1, 2) - Math.pow(y3, 2)); int sx21 = (int)(Math.pow(x2, 2) - Math.pow(x1, 2)); int sy21 = (int)(Math.pow(y2, 2) - Math.pow(y1, 2)); int f = ((sx13) * (x12) + (sy13) * (x12) + (sx21) * (x13) + (sy21) * (x13)) / (2 * ((y31) * (x12) - (y21) * (x13))); int g = ((sx13) * (y12) + (sy13) * (y12) + (sx21) * (y13) + (sy21) * (y13)) / (2 * ((x31) * (y12) - (x21) * (y13))); int c = -(int)Math.pow(x1, 2) - (int)Math.pow(y1, 2) - 2 * g * x1 - 2 * f * y1; // eqn of circle be x^2 + y^2 + 2*g*x + 2*f*y + c = 0 // where centre is (h = -g, k = -f) and radius r // as r^2 = h^2 + k^2 - c int h = -g; int k = -f; int sqr_of_r = h * h + k * k - c; // r is the radius double r = Math.sqrt(sqr_of_r); DecimalFormat df = new DecimalFormat("#.#####"); System.out.println("Centre = (" + h + "," + k + ")"); System.out.println("Radius = " + df.format(r));} // Driver codepublic static void main (String[] args){ int x1 = 1, y1 = 1; int x2 = 2, y2 = 4; int x3 = 5, y3 = 3; findCircle(x1, y1, x2, y2, x3, y3);}} // This code is contributed by chandan_jnu
# Python3 implementation of the approachfrom math import sqrt # Function to find the circle on# which the given three points liedef findCircle(x1, y1, x2, y2, x3, y3) : x12 = x1 - x2; x13 = x1 - x3; y12 = y1 - y2; y13 = y1 - y3; y31 = y3 - y1; y21 = y2 - y1; x31 = x3 - x1; x21 = x2 - x1; # x1^2 - x3^2 sx13 = pow(x1, 2) - pow(x3, 2); # y1^2 - y3^2 sy13 = pow(y1, 2) - pow(y3, 2); sx21 = pow(x2, 2) - pow(x1, 2); sy21 = pow(y2, 2) - pow(y1, 2); f = (((sx13) * (x12) + (sy13) * (x12) + (sx21) * (x13) + (sy21) * (x13)) // (2 * ((y31) * (x12) - (y21) * (x13)))); g = (((sx13) * (y12) + (sy13) * (y12) + (sx21) * (y13) + (sy21) * (y13)) // (2 * ((x31) * (y12) - (x21) * (y13)))); c = (-pow(x1, 2) - pow(y1, 2) - 2 * g * x1 - 2 * f * y1); # eqn of circle be x^2 + y^2 + 2*g*x + 2*f*y + c = 0 # where centre is (h = -g, k = -f) and # radius r as r^2 = h^2 + k^2 - c h = -g; k = -f; sqr_of_r = h * h + k * k - c; # r is the radius r = round(sqrt(sqr_of_r), 5); print("Centre = (", h, ", ", k, ")"); print("Radius = ", r); # Driver codeif __name__ == "__main__" : x1 = 1 ; y1 = 1; x2 = 2 ; y2 = 4; x3 = 5 ; y3 = 3; findCircle(x1, y1, x2, y2, x3, y3); # This code is contributed by Ryuga
// C# implementation of the approachusing System; class GFG{ // Function to find the circle on// which the given three points liestatic void findCircle(int x1, int y1, int x2, int y2, int x3, int y3){ int x12 = x1 - x2; int x13 = x1 - x3; int y12 = y1 - y2; int y13 = y1 - y3; int y31 = y3 - y1; int y21 = y2 - y1; int x31 = x3 - x1; int x21 = x2 - x1; // x1^2 - x3^2 int sx13 = (int)(Math.Pow(x1, 2) - Math.Pow(x3, 2)); // y1^2 - y3^2 int sy13 = (int)(Math.Pow(y1, 2) - Math.Pow(y3, 2)); int sx21 = (int)(Math.Pow(x2, 2) - Math.Pow(x1, 2)); int sy21 = (int)(Math.Pow(y2, 2) - Math.Pow(y1, 2)); int f = ((sx13) * (x12) + (sy13) * (x12) + (sx21) * (x13) + (sy21) * (x13)) / (2 * ((y31) * (x12) - (y21) * (x13))); int g = ((sx13) * (y12) + (sy13) * (y12) + (sx21) * (y13) + (sy21) * (y13)) / (2 * ((x31) * (y12) - (x21) * (y13))); int c = -(int)Math.Pow(x1, 2) - (int)Math.Pow(y1, 2) - 2 * g * x1 - 2 * f * y1; // eqn of circle be x^2 + y^2 + 2*g*x + 2*f*y + c = 0 // where centre is (h = -g, k = -f) and radius r // as r^2 = h^2 + k^2 - c int h = -g; int k = -f; int sqr_of_r = h * h + k * k - c; // r is the radius double r = Math.Round(Math.Sqrt(sqr_of_r), 5); Console.WriteLine("Centre = (" + h + "," + k + ")"); Console.WriteLine("Radius = " + r);} // Driver codestatic void Main(){ int x1 = 1, y1 = 1; int x2 = 2, y2 = 4; int x3 = 5, y3 = 3; findCircle(x1, y1, x2, y2, x3, y3);}} // This code is contributed by chandan_jnu
<script> // Function to find the circle on// which the given three points liefunction findCircle(x1, y1, x2, y2, x3, y3){ var x12 = (x1 - x2); var x13 = (x1 - x3); var y12 =( y1 - y2); var y13 = (y1 - y3); var y31 = (y3 - y1); var y21 = (y2 - y1); var x31 = (x3 - x1); var x21 = (x2 - x1); //x1^2 - x3^2 var sx13 = Math.pow(x1, 2) - Math.pow(x3, 2); // y1^2 - y3^2 var sy13 = Math.pow(y1, 2) - Math.pow(y3, 2); var sx21 = Math.pow(x2, 2) - Math.pow(x1, 2); var sy21 = Math.pow(y2, 2) - Math.pow(y1, 2); var f = ((sx13) * (x12) + (sy13) * (x12) + (sx21) * (x13) + (sy21) * (x13)) / (2 * ((y31) * (x12) - (y21) * (x13))); var g = ((sx13) * (y12) + (sy13) * (y12) + (sx21) * (y13) + (sy21) * (y13)) / (2 * ((x31) * (y12) - (x21) * (y13))); var c = -(Math.pow(x1, 2)) - Math.pow(y1, 2) - 2 * g * x1 - 2 * f * y1; // eqn of circle be // x^2 + y^2 + 2*g*x + 2*f*y + c = 0 // where centre is (h = -g, k = -f) and radius r // as r^2 = h^2 + k^2 - c var h = -g; var k = -f; var sqr_of_r = h * h + k * k - c; // r is the radius var r = Math.sqrt(sqr_of_r); document.write("Centre = (" + h + ", "+ k +")" + "<br>"); document.write( "Radius = " + r.toFixed(5));} var x1 = 1, y1 = 1; var x2 = 2, y2 = 4; var x3 = 5, y3 = 3; findCircle(x1, y1, x2, y2, x3, y3); </script>
Centre = (3, 2)
Radius = 2.23607
ankthon
Chandan_Kumar
akshitsaxenaa09
ysachin2314
sanketgandhi1
circle
Geometric
Mathematical
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)
Convex Hull | Set 2 (Graham Scan)
Given n line segments, find if any two segments intersect
Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
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": 25090,
"s": 25062,
"text": "\n19 Jul, 2021"
},
{
"code": null,
"e": 25459,
"s": 25090,
"text": "Given three coordinates that lie on a circle, (x1, y1), (x2, y2), and (x3, y3). The task is to find the equation of the circle and then print the centre and the radius of the circle. Equation of circle in general form is x2 + y2 + 2gx + 2fy + c = 0 and in radius form is (x – h)2 + (y -k)2 = r2, where (h, k) is the centre of the circle and r is the radius.Examples: "
},
{
"code": null,
"e": 25736,
"s": 25459,
"text": "Input: x1 = 1, y1 = 0, x2 = -1, y2 = 0, x3 = 0, y3 = 1 Output: Centre = (0, 0) Radius = 1 The equation of the circle is x2 + y2 = 1.Input: x1 = 1, y1 = -6, x2 = 2, y2 = 1, x3 = 5, y3 = 2 Output: Centre = (5, -3) Radius = 5 Equation of the circle is x2 + y2 -10x + 6y + 9 = 0 "
},
{
"code": null,
"e": 26054,
"s": 25738,
"text": "Approach: As we know all three-point lie on the circle, so they will satisfy the equation of a circle and by putting them in the general equation we get three equations with three variables g, f, and c, and by further solving we can get the values. We can derive the formula to obtain the value of g, f, and c as: "
},
{
"code": null,
"e": 27108,
"s": 26054,
"text": "Putting coordinates in eqn of circle, we get: x12 + y12 + 2gx1 + 2fy1 + c = 0 – (1) x22 + y22 + 2gx2 + 2fy2 + c = 0 – (2) x32 + y32 + 2gx3 + 2fy3 + c = 0 – (3)From (1) we get, 2gx1 = -x12 – y12 – 2fy1 – c – (4) From (1) we get, c = -x12 – y12 – 2gx1 – 2fy1 – (5) From (3) we get, 2fy3 = -x32 – y32 – 2gx3 – c – (6)Subtracting eqn (2) from eqn (1) we get, 2g( x1 – x2 ) = ( x22 -x12 ) + ( y22 – y12 ) + 2f( y2 – y1 ) – (A)Now putting eqn (5) in (6) we get, 2fy3 = -x32 – y32 – 2gx3 + x12 + y12 + 2gx1 + 2fy1 – (7)Now putting value of 2g from eqn (A) in (7) we get, 2f = ( ( x12 – x32 )( x1 – x2 ) +( y12 – y32 )( x1 – x2 ) + ( x22 – x12 )( x1 – x3 ) + ( y22 – y12 )( x1 – x3 ) ) / ( y3 – y1 )( x1 – x2 ) – ( y2 – y1 )( x1 – x3 )Similarly we can obtain the values of 2g : 2g = ( ( x12 – x32 )( y1 – x2 ) +( y12 – y32 )( y1 – y2 ) + ( x22 – x12 )( y1 – y3) + ( y22 – y12 )( y1 – y3 ) ) / ( x3 -x1 )( y1 – y2 ) – ( x2 – x1 )( y1 – y3 )Putting 2g and 2f in eqn (5) we get the value of c and know we had the equation of circle as x2 + y2 + 2gx + 2fy + c = 0 "
},
{
"code": null,
"e": 27161,
"s": 27108,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27165,
"s": 27161,
"text": "C++"
},
{
"code": null,
"e": 27170,
"s": 27165,
"text": "Java"
},
{
"code": null,
"e": 27178,
"s": 27170,
"text": "Python3"
},
{
"code": null,
"e": 27181,
"s": 27178,
"text": "C#"
},
{
"code": null,
"e": 27192,
"s": 27181,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to find the circle on// which the given three points lievoid findCircle(int x1, int y1, int x2, int y2, int x3, int y3){ int x12 = x1 - x2; int x13 = x1 - x3; int y12 = y1 - y2; int y13 = y1 - y3; int y31 = y3 - y1; int y21 = y2 - y1; int x31 = x3 - x1; int x21 = x2 - x1; // x1^2 - x3^2 int sx13 = pow(x1, 2) - pow(x3, 2); // y1^2 - y3^2 int sy13 = pow(y1, 2) - pow(y3, 2); int sx21 = pow(x2, 2) - pow(x1, 2); int sy21 = pow(y2, 2) - pow(y1, 2); int f = ((sx13) * (x12) + (sy13) * (x12) + (sx21) * (x13) + (sy21) * (x13)) / (2 * ((y31) * (x12) - (y21) * (x13))); int g = ((sx13) * (y12) + (sy13) * (y12) + (sx21) * (y13) + (sy21) * (y13)) / (2 * ((x31) * (y12) - (x21) * (y13))); int c = -pow(x1, 2) - pow(y1, 2) - 2 * g * x1 - 2 * f * y1; // eqn of circle be x^2 + y^2 + 2*g*x + 2*f*y + c = 0 // where centre is (h = -g, k = -f) and radius r // as r^2 = h^2 + k^2 - c int h = -g; int k = -f; int sqr_of_r = h * h + k * k - c; // r is the radius float r = sqrt(sqr_of_r); cout << \"Centre = (\" << h << \", \" << k << \")\" << endl; cout << \"Radius = \" << r;} // Driver codeint main(){ int x1 = 1, y1 = 1; int x2 = 2, y2 = 4; int x3 = 5, y3 = 3; findCircle(x1, y1, x2, y2, x3, y3); return 0;}",
"e": 28676,
"s": 27192,
"text": null
},
{
"code": "// Java implementation of the approachimport java.text.*; class GFG{ // Function to find the circle on// which the given three points liestatic void findCircle(int x1, int y1, int x2, int y2, int x3, int y3){ int x12 = x1 - x2; int x13 = x1 - x3; int y12 = y1 - y2; int y13 = y1 - y3; int y31 = y3 - y1; int y21 = y2 - y1; int x31 = x3 - x1; int x21 = x2 - x1; // x1^2 - x3^2 int sx13 = (int)(Math.pow(x1, 2) - Math.pow(x3, 2)); // y1^2 - y3^2 int sy13 = (int)(Math.pow(y1, 2) - Math.pow(y3, 2)); int sx21 = (int)(Math.pow(x2, 2) - Math.pow(x1, 2)); int sy21 = (int)(Math.pow(y2, 2) - Math.pow(y1, 2)); int f = ((sx13) * (x12) + (sy13) * (x12) + (sx21) * (x13) + (sy21) * (x13)) / (2 * ((y31) * (x12) - (y21) * (x13))); int g = ((sx13) * (y12) + (sy13) * (y12) + (sx21) * (y13) + (sy21) * (y13)) / (2 * ((x31) * (y12) - (x21) * (y13))); int c = -(int)Math.pow(x1, 2) - (int)Math.pow(y1, 2) - 2 * g * x1 - 2 * f * y1; // eqn of circle be x^2 + y^2 + 2*g*x + 2*f*y + c = 0 // where centre is (h = -g, k = -f) and radius r // as r^2 = h^2 + k^2 - c int h = -g; int k = -f; int sqr_of_r = h * h + k * k - c; // r is the radius double r = Math.sqrt(sqr_of_r); DecimalFormat df = new DecimalFormat(\"#.#####\"); System.out.println(\"Centre = (\" + h + \",\" + k + \")\"); System.out.println(\"Radius = \" + df.format(r));} // Driver codepublic static void main (String[] args){ int x1 = 1, y1 = 1; int x2 = 2, y2 = 4; int x3 = 5, y3 = 3; findCircle(x1, y1, x2, y2, x3, y3);}} // This code is contributed by chandan_jnu",
"e": 30551,
"s": 28676,
"text": null
},
{
"code": "# Python3 implementation of the approachfrom math import sqrt # Function to find the circle on# which the given three points liedef findCircle(x1, y1, x2, y2, x3, y3) : x12 = x1 - x2; x13 = x1 - x3; y12 = y1 - y2; y13 = y1 - y3; y31 = y3 - y1; y21 = y2 - y1; x31 = x3 - x1; x21 = x2 - x1; # x1^2 - x3^2 sx13 = pow(x1, 2) - pow(x3, 2); # y1^2 - y3^2 sy13 = pow(y1, 2) - pow(y3, 2); sx21 = pow(x2, 2) - pow(x1, 2); sy21 = pow(y2, 2) - pow(y1, 2); f = (((sx13) * (x12) + (sy13) * (x12) + (sx21) * (x13) + (sy21) * (x13)) // (2 * ((y31) * (x12) - (y21) * (x13)))); g = (((sx13) * (y12) + (sy13) * (y12) + (sx21) * (y13) + (sy21) * (y13)) // (2 * ((x31) * (y12) - (x21) * (y13)))); c = (-pow(x1, 2) - pow(y1, 2) - 2 * g * x1 - 2 * f * y1); # eqn of circle be x^2 + y^2 + 2*g*x + 2*f*y + c = 0 # where centre is (h = -g, k = -f) and # radius r as r^2 = h^2 + k^2 - c h = -g; k = -f; sqr_of_r = h * h + k * k - c; # r is the radius r = round(sqrt(sqr_of_r), 5); print(\"Centre = (\", h, \", \", k, \")\"); print(\"Radius = \", r); # Driver codeif __name__ == \"__main__\" : x1 = 1 ; y1 = 1; x2 = 2 ; y2 = 4; x3 = 5 ; y3 = 3; findCircle(x1, y1, x2, y2, x3, y3); # This code is contributed by Ryuga",
"e": 31906,
"s": 30551,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to find the circle on// which the given three points liestatic void findCircle(int x1, int y1, int x2, int y2, int x3, int y3){ int x12 = x1 - x2; int x13 = x1 - x3; int y12 = y1 - y2; int y13 = y1 - y3; int y31 = y3 - y1; int y21 = y2 - y1; int x31 = x3 - x1; int x21 = x2 - x1; // x1^2 - x3^2 int sx13 = (int)(Math.Pow(x1, 2) - Math.Pow(x3, 2)); // y1^2 - y3^2 int sy13 = (int)(Math.Pow(y1, 2) - Math.Pow(y3, 2)); int sx21 = (int)(Math.Pow(x2, 2) - Math.Pow(x1, 2)); int sy21 = (int)(Math.Pow(y2, 2) - Math.Pow(y1, 2)); int f = ((sx13) * (x12) + (sy13) * (x12) + (sx21) * (x13) + (sy21) * (x13)) / (2 * ((y31) * (x12) - (y21) * (x13))); int g = ((sx13) * (y12) + (sy13) * (y12) + (sx21) * (y13) + (sy21) * (y13)) / (2 * ((x31) * (y12) - (x21) * (y13))); int c = -(int)Math.Pow(x1, 2) - (int)Math.Pow(y1, 2) - 2 * g * x1 - 2 * f * y1; // eqn of circle be x^2 + y^2 + 2*g*x + 2*f*y + c = 0 // where centre is (h = -g, k = -f) and radius r // as r^2 = h^2 + k^2 - c int h = -g; int k = -f; int sqr_of_r = h * h + k * k - c; // r is the radius double r = Math.Round(Math.Sqrt(sqr_of_r), 5); Console.WriteLine(\"Centre = (\" + h + \",\" + k + \")\"); Console.WriteLine(\"Radius = \" + r);} // Driver codestatic void Main(){ int x1 = 1, y1 = 1; int x2 = 2, y2 = 4; int x3 = 5, y3 = 3; findCircle(x1, y1, x2, y2, x3, y3);}} // This code is contributed by chandan_jnu",
"e": 33703,
"s": 31906,
"text": null
},
{
"code": "<script> // Function to find the circle on// which the given three points liefunction findCircle(x1, y1, x2, y2, x3, y3){ var x12 = (x1 - x2); var x13 = (x1 - x3); var y12 =( y1 - y2); var y13 = (y1 - y3); var y31 = (y3 - y1); var y21 = (y2 - y1); var x31 = (x3 - x1); var x21 = (x2 - x1); //x1^2 - x3^2 var sx13 = Math.pow(x1, 2) - Math.pow(x3, 2); // y1^2 - y3^2 var sy13 = Math.pow(y1, 2) - Math.pow(y3, 2); var sx21 = Math.pow(x2, 2) - Math.pow(x1, 2); var sy21 = Math.pow(y2, 2) - Math.pow(y1, 2); var f = ((sx13) * (x12) + (sy13) * (x12) + (sx21) * (x13) + (sy21) * (x13)) / (2 * ((y31) * (x12) - (y21) * (x13))); var g = ((sx13) * (y12) + (sy13) * (y12) + (sx21) * (y13) + (sy21) * (y13)) / (2 * ((x31) * (y12) - (x21) * (y13))); var c = -(Math.pow(x1, 2)) - Math.pow(y1, 2) - 2 * g * x1 - 2 * f * y1; // eqn of circle be // x^2 + y^2 + 2*g*x + 2*f*y + c = 0 // where centre is (h = -g, k = -f) and radius r // as r^2 = h^2 + k^2 - c var h = -g; var k = -f; var sqr_of_r = h * h + k * k - c; // r is the radius var r = Math.sqrt(sqr_of_r); document.write(\"Centre = (\" + h + \", \"+ k +\")\" + \"<br>\"); document.write( \"Radius = \" + r.toFixed(5));} var x1 = 1, y1 = 1; var x2 = 2, y2 = 4; var x3 = 5, y3 = 3; findCircle(x1, y1, x2, y2, x3, y3); </script>",
"e": 35159,
"s": 33703,
"text": null
},
{
"code": null,
"e": 35192,
"s": 35159,
"text": "Centre = (3, 2)\nRadius = 2.23607"
},
{
"code": null,
"e": 35202,
"s": 35194,
"text": "ankthon"
},
{
"code": null,
"e": 35216,
"s": 35202,
"text": "Chandan_Kumar"
},
{
"code": null,
"e": 35232,
"s": 35216,
"text": "akshitsaxenaa09"
},
{
"code": null,
"e": 35244,
"s": 35232,
"text": "ysachin2314"
},
{
"code": null,
"e": 35258,
"s": 35244,
"text": "sanketgandhi1"
},
{
"code": null,
"e": 35265,
"s": 35258,
"text": "circle"
},
{
"code": null,
"e": 35275,
"s": 35265,
"text": "Geometric"
},
{
"code": null,
"e": 35288,
"s": 35275,
"text": "Mathematical"
},
{
"code": null,
"e": 35301,
"s": 35288,
"text": "Mathematical"
},
{
"code": null,
"e": 35311,
"s": 35301,
"text": "Geometric"
},
{
"code": null,
"e": 35409,
"s": 35311,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35458,
"s": 35409,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 35511,
"s": 35458,
"text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)"
},
{
"code": null,
"e": 35545,
"s": 35511,
"text": "Convex Hull | Set 2 (Graham Scan)"
},
{
"code": null,
"e": 35603,
"s": 35545,
"text": "Given n line segments, find if any two segments intersect"
},
{
"code": null,
"e": 35654,
"s": 35603,
"text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)"
},
{
"code": null,
"e": 35684,
"s": 35654,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 35744,
"s": 35684,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 35759,
"s": 35744,
"text": "C++ Data Types"
},
{
"code": null,
"e": 35802,
"s": 35759,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
XAML - Event Handling | The general concept of events in XAML is similar to events in other popular programming languages such as .NET and C++. In XAML, all of the controls expose some events so that they can be subscribed for specific purposes.
Whenever an event takes place, the application will be notified and the program can react to them, e.g., close buttons are used to close a dialog.
There are many types of events that can be subscribed for different behaviors of an application based on the requirement of that application, but the most commonly used events are those which are related to mouse and keyboard such as,
Click
MouseDown
MouseEnter
MouseLeave
MouseUp
KeyDown
KeyUp
In this chapter, we will use some of the basic and most commonly used events to understand how an event of a specific control can be linked to the code behind where the behavior will be implemented depending on what the user wants to do when a specific event occurs.
Let’s have a look at a simple example of a button click event. Given below is the XAML implementation for Button control which is created and initialized with some properties and a Click event (Click="OnClick").
<Window x:Class = "XAMLEventHandling.MainWindow"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
Title = "MainWindow" Height = "350" Width = "604">
<Grid>
<Button x:Name = "button1" Content = "Click" Click = "OnClick"
Width = "150" Height = "30" HorizontalAlignment = "Center" />
</Grid>
</Window>
Whenever this button is clicked, it will fire an OnClick event and you can add any type of behavior as a response to the Click. Let’s have a look at the OnClick event implementation which will show a message when this button is clicked.
using System;
using System.Windows;
using System.Windows.Controls;
namespace XAMLEventHandling {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
}
private void OnClick(object sender, RoutedEventArgs e) {
MessageBox.Show("Button is clicked!");
}
}
}
When you compile and execute the above code, it will produce the following output −
When you click on the button, the click (OnClick) event will be fired and the following message will be displayed.
Now let’s have a look at a little bit complex example where multiple events are handled.
The following example contains a textbox with ContextMenu which manipulates the text within the textbox.
The following XAML code creates a TextBox, a ContextMenu, and MenuItems with some properties and events such as Checked, Unchecked, and Click.
<Window x:Class = "XAMLContextMenu.MainWindow"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
Title = "MainWindow" Height = "350" Width = "604">
<Grid>
<TextBox Name = "textBox1" TextWrapping = "Wrap" Margin = "10" Grid.Row = "7">
Hi, this is XAML tutorial.
<TextBox.ContextMenu>
<ContextMenu>
<MenuItem Header = "_Bold" IsCheckable = "True"
Checked = "Bold_Checked" Unchecked = "Bold_Unchecked" />
<MenuItem Header = "_Italic" IsCheckable = "True"
Checked = "Italic_Checked" Unchecked = "Italic_Unchecked" />
<Separator />
<MenuItem Header = "Increase Font Size" Click = "IncreaseFont_Click" />
<MenuItem Header = "_Decrease Font Size" Click = "DecreaseFont_Click" />
</ContextMenu>
</TextBox.ContextMenu>
</TextBox>
</Grid>
</Window>
Here is the implementation in C# for the different events which will be fired whenever a menu item is checked, unchecked, or clicked.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace XAMLContextMenu {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
}
private void Bold_Checked(object sender, RoutedEventArgs e) {
textBox1.FontWeight = FontWeights.Bold;
}
private void Bold_Unchecked(object sender, RoutedEventArgs e) {
textBox1.FontWeight = FontWeights.Normal;
}
private void Italic_Checked(object sender, RoutedEventArgs e) {
textBox1.FontStyle = FontStyles.Italic;
}
private void Italic_Unchecked(object sender, RoutedEventArgs e) {
textBox1.FontStyle = FontStyles.Normal;
}
private void IncreaseFont_Click(object sender, RoutedEventArgs e) {
if (textBox1.FontSize < 18) {
textBox1.FontSize += 2;
}
}
private void DecreaseFont_Click(object sender, RoutedEventArgs e) {
if (textBox1.FontSize > 10) {
textBox1.FontSize -= 2;
}
}
}
}
When you compile and execute the above code, it will produce the following output −
We recommend you to execute the above example code and experiment with some other events.
Checked
Fires when a ToggleButton is checked. (Inherited from ToggleButton)
Click
Occurs when a button control is clicked. (Inherited from ButtonBase)
ContextMenuClosing
Occurs just before any context menu on the element is closed. (Inherited from FrameworkElement.)
ContextMenuOpening
Occurs when any context menu on the element is opened. (Inherited from FrameworkElement.)
DataContextChanged
Occurs when the value of the FrameworkElement.DataContext property changes. (Inherited from FrameworkElement)
DragEnter
Occurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement).
DragLeave
Occurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement)
DragOver
Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement)
DragStarting
Occurs when a drag operation is initiated. (Inherited from UIElement)
DropCompleted
Occurs when a drag-and-drop operation is ended. (Inherited from UIElement)
DropDownClosed
Occurs when the drop-down portion of the ComboBox closes.
DropDownOpened
Occurs when the drop-down portion of the ComboBox opens.
GotFocus
Occurs when a UIElement receives focus. (Inherited from UIElement)
Holding
Occurs when an otherwise unhandled Hold interaction occurs over the hit test area of this element. (Inherited from UIElement)
Intermediate
Fires when the state of a ToggleButton is switched to the indeterminate state. (Inherited from ToggleButton)
IsEnabledChanged
Occurs when the IsEnabled property changes. (Inherited from Control)
KeyDown
Occurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement)
KeyUp
Occurs when a keyboard key is released while the UIElement has focus. (Inherited from UIElement)
LostFocus
Occurs when a UIElement loses focus. (Inherited from UIElement)
ManipulationCompleted
Occurs when a manipulation on the UIElement is complete. (Inherited from UIElement)
ManipulationDelta
Occurs when the input device changes position during a manipulation. (Inherited from UIElement)
ManipulationInertiaStarting
Occurs when the input device loses contact with the UIElement object during a manipulation and inertia begins. (Inherited from UIElement)
ManipulationStarted
Occurs when an input device begins a manipulation on the UIElement. (Inherited from UIElement)
ManipulationStarting
Occurs when the manipulation processor is first created. (Inherited from UIElement)
SelectionChanged
Occurs when the text selection has changed.
SizeChanged
Occurs when either the ActualHeight or the ActualWidth property changes value on a FrameworkElement. (Inherited from FrameworkElement)
Unchecked
Occurs when a ToggleButton is unchecked. (Inherited from ToggleButton)
ValueChanged
Occurs when the range value changes. (Inherited from RangeBase)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2145,
"s": 1923,
"text": "The general concept of events in XAML is similar to events in other popular programming languages such as .NET and C++. In XAML, all of the controls expose some events so that they can be subscribed for specific purposes."
},
{
"code": null,
"e": 2292,
"s": 2145,
"text": "Whenever an event takes place, the application will be notified and the program can react to them, e.g., close buttons are used to close a dialog."
},
{
"code": null,
"e": 2527,
"s": 2292,
"text": "There are many types of events that can be subscribed for different behaviors of an application based on the requirement of that application, but the most commonly used events are those which are related to mouse and keyboard such as,"
},
{
"code": null,
"e": 2533,
"s": 2527,
"text": "Click"
},
{
"code": null,
"e": 2543,
"s": 2533,
"text": "MouseDown"
},
{
"code": null,
"e": 2554,
"s": 2543,
"text": "MouseEnter"
},
{
"code": null,
"e": 2565,
"s": 2554,
"text": "MouseLeave"
},
{
"code": null,
"e": 2573,
"s": 2565,
"text": "MouseUp"
},
{
"code": null,
"e": 2581,
"s": 2573,
"text": "KeyDown"
},
{
"code": null,
"e": 2587,
"s": 2581,
"text": "KeyUp"
},
{
"code": null,
"e": 2854,
"s": 2587,
"text": "In this chapter, we will use some of the basic and most commonly used events to understand how an event of a specific control can be linked to the code behind where the behavior will be implemented depending on what the user wants to do when a specific event occurs."
},
{
"code": null,
"e": 3066,
"s": 2854,
"text": "Let’s have a look at a simple example of a button click event. Given below is the XAML implementation for Button control which is created and initialized with some properties and a Click event (Click=\"OnClick\")."
},
{
"code": null,
"e": 3485,
"s": 3066,
"text": "<Window x:Class = \"XAMLEventHandling.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"MainWindow\" Height = \"350\" Width = \"604\"> \n\t\n <Grid> \n <Button x:Name = \"button1\" Content = \"Click\" Click = \"OnClick\" \n Width = \"150\" Height = \"30\" HorizontalAlignment = \"Center\" /> \n </Grid>\n \n</Window> "
},
{
"code": null,
"e": 3722,
"s": 3485,
"text": "Whenever this button is clicked, it will fire an OnClick event and you can add any type of behavior as a response to the Click. Let’s have a look at the OnClick event implementation which will show a message when this button is clicked."
},
{
"code": null,
"e": 4157,
"s": 3722,
"text": "using System; \nusing System.Windows; \nusing System.Windows.Controls; \n\nnamespace XAMLEventHandling {\n /// <summary> \n /// Interaction logic for MainWindow.xaml \n /// </summary> \n\t\n public partial class MainWindow : Window {\n public MainWindow() { \n InitializeComponent(); \n }\n private void OnClick(object sender, RoutedEventArgs e) { \n MessageBox.Show(\"Button is clicked!\"); \n } \n }\n}"
},
{
"code": null,
"e": 4241,
"s": 4157,
"text": "When you compile and execute the above code, it will produce the following output −"
},
{
"code": null,
"e": 4356,
"s": 4241,
"text": "When you click on the button, the click (OnClick) event will be fired and the following message will be displayed."
},
{
"code": null,
"e": 4445,
"s": 4356,
"text": "Now let’s have a look at a little bit complex example where multiple events are handled."
},
{
"code": null,
"e": 4550,
"s": 4445,
"text": "The following example contains a textbox with ContextMenu which manipulates the text within the textbox."
},
{
"code": null,
"e": 4693,
"s": 4550,
"text": "The following XAML code creates a TextBox, a ContextMenu, and MenuItems with some properties and events such as Checked, Unchecked, and Click."
},
{
"code": null,
"e": 5731,
"s": 4693,
"text": "<Window x:Class = \"XAMLContextMenu.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"MainWindow\" Height = \"350\" Width = \"604\"> \n\t\n <Grid> \n <TextBox Name = \"textBox1\" TextWrapping = \"Wrap\" Margin = \"10\" Grid.Row = \"7\"> \n Hi, this is XAML tutorial. \n <TextBox.ContextMenu>\n \n <ContextMenu>\n <MenuItem Header = \"_Bold\" IsCheckable = \"True\" \n Checked = \"Bold_Checked\" Unchecked = \"Bold_Unchecked\" /> \n <MenuItem Header = \"_Italic\" IsCheckable = \"True\" \n Checked = \"Italic_Checked\" Unchecked = \"Italic_Unchecked\" /> \n <Separator /> \n <MenuItem Header = \"Increase Font Size\" Click = \"IncreaseFont_Click\" />\n <MenuItem Header = \"_Decrease Font Size\" Click = \"DecreaseFont_Click\" /> \n </ContextMenu> \n\t\t\t\t\n </TextBox.ContextMenu>\n </TextBox>\n </Grid> \n\t\n</Window> "
},
{
"code": null,
"e": 5865,
"s": 5731,
"text": "Here is the implementation in C# for the different events which will be fired whenever a menu item is checked, unchecked, or clicked."
},
{
"code": null,
"e": 7172,
"s": 5865,
"text": "using System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Text; \nusing System.Threading.Tasks; \nusing System.Windows; \nusing System.Windows.Controls; \nusing System.Windows.Data; \n\nnamespace XAMLContextMenu { \n /// <summary> \n /// Interaction logic for MainWindow.xaml \n /// </summary>\n\t\n public partial class MainWindow : Window {\n public MainWindow() { \n InitializeComponent(); \n }\n private void Bold_Checked(object sender, RoutedEventArgs e) { \n textBox1.FontWeight = FontWeights.Bold; \n }\n private void Bold_Unchecked(object sender, RoutedEventArgs e) { \n textBox1.FontWeight = FontWeights.Normal; \n }\n private void Italic_Checked(object sender, RoutedEventArgs e) { \n textBox1.FontStyle = FontStyles.Italic; \n }\n private void Italic_Unchecked(object sender, RoutedEventArgs e) { \n textBox1.FontStyle = FontStyles.Normal; \n }\n private void IncreaseFont_Click(object sender, RoutedEventArgs e) { \n if (textBox1.FontSize < 18) { \n textBox1.FontSize += 2; \n } \n }\n private void DecreaseFont_Click(object sender, RoutedEventArgs e) { \n if (textBox1.FontSize > 10) { \n textBox1.FontSize -= 2; \n } \n }\n }\n}"
},
{
"code": null,
"e": 7256,
"s": 7172,
"text": "When you compile and execute the above code, it will produce the following output −"
},
{
"code": null,
"e": 7346,
"s": 7256,
"text": "We recommend you to execute the above example code and experiment with some other events."
},
{
"code": null,
"e": 7354,
"s": 7346,
"text": "Checked"
},
{
"code": null,
"e": 7422,
"s": 7354,
"text": "Fires when a ToggleButton is checked. (Inherited from ToggleButton)"
},
{
"code": null,
"e": 7428,
"s": 7422,
"text": "Click"
},
{
"code": null,
"e": 7497,
"s": 7428,
"text": "Occurs when a button control is clicked. (Inherited from ButtonBase)"
},
{
"code": null,
"e": 7516,
"s": 7497,
"text": "ContextMenuClosing"
},
{
"code": null,
"e": 7613,
"s": 7516,
"text": "Occurs just before any context menu on the element is closed. (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 7632,
"s": 7613,
"text": "ContextMenuOpening"
},
{
"code": null,
"e": 7722,
"s": 7632,
"text": "Occurs when any context menu on the element is opened. (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 7741,
"s": 7722,
"text": "DataContextChanged"
},
{
"code": null,
"e": 7851,
"s": 7741,
"text": "Occurs when the value of the FrameworkElement.DataContext property changes. (Inherited from FrameworkElement)"
},
{
"code": null,
"e": 7861,
"s": 7851,
"text": "DragEnter"
},
{
"code": null,
"e": 7984,
"s": 7861,
"text": "Occurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement)."
},
{
"code": null,
"e": 7994,
"s": 7984,
"text": "DragLeave"
},
{
"code": null,
"e": 8116,
"s": 7994,
"text": "Occurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement)"
},
{
"code": null,
"e": 8125,
"s": 8116,
"text": "DragOver"
},
{
"code": null,
"e": 8262,
"s": 8125,
"text": "Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement)"
},
{
"code": null,
"e": 8275,
"s": 8262,
"text": "DragStarting"
},
{
"code": null,
"e": 8345,
"s": 8275,
"text": "Occurs when a drag operation is initiated. (Inherited from UIElement)"
},
{
"code": null,
"e": 8359,
"s": 8345,
"text": "DropCompleted"
},
{
"code": null,
"e": 8434,
"s": 8359,
"text": "Occurs when a drag-and-drop operation is ended. (Inherited from UIElement)"
},
{
"code": null,
"e": 8449,
"s": 8434,
"text": "DropDownClosed"
},
{
"code": null,
"e": 8507,
"s": 8449,
"text": "Occurs when the drop-down portion of the ComboBox closes."
},
{
"code": null,
"e": 8522,
"s": 8507,
"text": "DropDownOpened"
},
{
"code": null,
"e": 8579,
"s": 8522,
"text": "Occurs when the drop-down portion of the ComboBox opens."
},
{
"code": null,
"e": 8588,
"s": 8579,
"text": "GotFocus"
},
{
"code": null,
"e": 8655,
"s": 8588,
"text": "Occurs when a UIElement receives focus. (Inherited from UIElement)"
},
{
"code": null,
"e": 8663,
"s": 8655,
"text": "Holding"
},
{
"code": null,
"e": 8789,
"s": 8663,
"text": "Occurs when an otherwise unhandled Hold interaction occurs over the hit test area of this element. (Inherited from UIElement)"
},
{
"code": null,
"e": 8802,
"s": 8789,
"text": "Intermediate"
},
{
"code": null,
"e": 8911,
"s": 8802,
"text": "Fires when the state of a ToggleButton is switched to the indeterminate state. (Inherited from ToggleButton)"
},
{
"code": null,
"e": 8928,
"s": 8911,
"text": "IsEnabledChanged"
},
{
"code": null,
"e": 8997,
"s": 8928,
"text": "Occurs when the IsEnabled property changes. (Inherited from Control)"
},
{
"code": null,
"e": 9005,
"s": 8997,
"text": "KeyDown"
},
{
"code": null,
"e": 9101,
"s": 9005,
"text": "Occurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement)"
},
{
"code": null,
"e": 9107,
"s": 9101,
"text": "KeyUp"
},
{
"code": null,
"e": 9204,
"s": 9107,
"text": "Occurs when a keyboard key is released while the UIElement has focus. (Inherited from UIElement)"
},
{
"code": null,
"e": 9214,
"s": 9204,
"text": "LostFocus"
},
{
"code": null,
"e": 9278,
"s": 9214,
"text": "Occurs when a UIElement loses focus. (Inherited from UIElement)"
},
{
"code": null,
"e": 9300,
"s": 9278,
"text": "ManipulationCompleted"
},
{
"code": null,
"e": 9384,
"s": 9300,
"text": "Occurs when a manipulation on the UIElement is complete. (Inherited from UIElement)"
},
{
"code": null,
"e": 9402,
"s": 9384,
"text": "ManipulationDelta"
},
{
"code": null,
"e": 9498,
"s": 9402,
"text": "Occurs when the input device changes position during a manipulation. (Inherited from UIElement)"
},
{
"code": null,
"e": 9526,
"s": 9498,
"text": "ManipulationInertiaStarting"
},
{
"code": null,
"e": 9664,
"s": 9526,
"text": "Occurs when the input device loses contact with the UIElement object during a manipulation and inertia begins. (Inherited from UIElement)"
},
{
"code": null,
"e": 9684,
"s": 9664,
"text": "ManipulationStarted"
},
{
"code": null,
"e": 9779,
"s": 9684,
"text": "Occurs when an input device begins a manipulation on the UIElement. (Inherited from UIElement)"
},
{
"code": null,
"e": 9800,
"s": 9779,
"text": "ManipulationStarting"
},
{
"code": null,
"e": 9884,
"s": 9800,
"text": "Occurs when the manipulation processor is first created. (Inherited from UIElement)"
},
{
"code": null,
"e": 9901,
"s": 9884,
"text": "SelectionChanged"
},
{
"code": null,
"e": 9945,
"s": 9901,
"text": "Occurs when the text selection has changed."
},
{
"code": null,
"e": 9957,
"s": 9945,
"text": "SizeChanged"
},
{
"code": null,
"e": 10092,
"s": 9957,
"text": "Occurs when either the ActualHeight or the ActualWidth property changes value on a FrameworkElement. (Inherited from FrameworkElement)"
},
{
"code": null,
"e": 10102,
"s": 10092,
"text": "Unchecked"
},
{
"code": null,
"e": 10173,
"s": 10102,
"text": "Occurs when a ToggleButton is unchecked. (Inherited from ToggleButton)"
},
{
"code": null,
"e": 10186,
"s": 10173,
"text": "ValueChanged"
},
{
"code": null,
"e": 10250,
"s": 10186,
"text": "Occurs when the range value changes. (Inherited from RangeBase)"
},
{
"code": null,
"e": 10257,
"s": 10250,
"text": " Print"
},
{
"code": null,
"e": 10268,
"s": 10257,
"text": " Add Notes"
}
] |
How to delete all files and folders from a path in C#? | For deleting all the folders and its respective directories we can make us System.IO namespace available in C#. The DirectoryInfo() class provides the details of all sub directories and file in a directory.
Let us consider a directory Demo having two sub directories and has some files like below.
using System.IO;
namespace DemoApplication {
class Program {
static void Main(string[] args) {
DirectoryInfo di = new DirectoryInfo(@"D:\Demo");
foreach (DirectoryInfo dir in di.GetDirectories()) {
foreach (FileInfo file in dir.GetFiles()) {
file.Delete();
}
dir.Delete(true);
}
}
}
}
output of the above code is
We could see that all the folders and its related files are deleted from the demo directory completely. Here GetDirectories() will fetch all the directories of the root directory (Demo) and GetFiles() will fetch all the files (Demo File 1, Demo File 2) present in that directory. | [
{
"code": null,
"e": 1269,
"s": 1062,
"text": "For deleting all the folders and its respective directories we can make us System.IO namespace available in C#. The DirectoryInfo() class provides the details of all sub directories and file in a directory."
},
{
"code": null,
"e": 1360,
"s": 1269,
"text": "Let us consider a directory Demo having two sub directories and has some files like below."
},
{
"code": null,
"e": 1741,
"s": 1360,
"text": "using System.IO;\nnamespace DemoApplication {\n class Program {\n static void Main(string[] args) {\n DirectoryInfo di = new DirectoryInfo(@\"D:\\Demo\");\n foreach (DirectoryInfo dir in di.GetDirectories()) {\n foreach (FileInfo file in dir.GetFiles()) {\n file.Delete();\n }\n dir.Delete(true);\n }\n }\n }\n}"
},
{
"code": null,
"e": 1769,
"s": 1741,
"text": "output of the above code is"
},
{
"code": null,
"e": 2049,
"s": 1769,
"text": "We could see that all the folders and its related files are deleted from the demo directory completely. Here GetDirectories() will fetch all the directories of the root directory (Demo) and GetFiles() will fetch all the files (Demo File 1, Demo File 2) present in that directory."
}
] |
Computer Networks | Set 6 - GeeksforGeeks | 27 Mar, 2017
Following questions have been asked in GATE CS 2005 exam.
1) An organization has a class B network and wishes to form subnets for 64 departments. The subnet mask would be:(a) 255.255.0.0(b) 255.255.64.0(c) 255.255.128.0(d) 255.255.252.0
Answer (d)The size of network ID is 16 bit in class B networks. So bits after 16th bit must be used to create 64 departments. Total 6 bits are needed to identify 64 different departments. Therefore, subnet mask will be 255.255.252.0.
2) In a packet switching network, packets are routed from source to destination along a single path having two intermediate nodes. If the message size is 24 bytes and each packet contains a header of 3 bytes, then the optimum packet size is:(a) 4(b) 6(c) 7(d) 9
Answer (d)Dividing a message into packets may decrease the transmission time due to parallelism as shown in the following figure.
But after a certain limit reducing the packet size may increase the transmission time also.
Following figure shows the situation given in question.
Let transmission time to transfer 1 byte for all nodes be t. The first packet will take time = (packet size)*3*t. After the first packet reaches the destination, remaining packets will take time equal to (packet size)*t due to parallelism.
If we use 4 bytes as packet size, there will be 24 packets
Total Transmission time = Time taken by first packet +
Time taken by remaining packets
= 3*4*t + 23*4*t = 104t
If we use 6 bytes as packet size, there will be 8 packets
Total Transmission time = 3*6*t + 7*6*t = 60t
If we use 7 bytes as packet size, there will be 6 packets
Total Transmission time = 3*7*t + 5*7*t = 56t
If we use 9 bytes as packet size, there will be 4 packets
Total Transmission time = 3*9*t + 3*9*t = 54t
3) Suppose the round trip propagation delay for a 10 Mbps Ethernet having 48-bit jamming signal is 46.4 ms. The minimum frame size is:(a) 94(b) 416(c) 464(d) 512
Answer (c)Transmission Speed = 10Mbps.Round trip propagation delay = 46.4 msThe minimum frame size = (Round Trip Propagation Delay) * (Transmission Speed) = 10*(10^6)*46.4*(10^-3) = 464 * 10^3 = 464 Kbit
The concept behind the above formula is collision detection. Consider a situation where a node A wants to send a frame to another node B. When Node A begins transmitting, the signal must propagate the network length. In the worst-case collision scenario, Node B begins to transmit just before the signal for Node A’s frame reaches it. The collision signal of Node A and Node B’s frame must travel back to Node A for Node A to detect that a collision has occurred.The time it takes for a signal to propagate from one end of the network to the other is known as the propagation delay. In this worst-case collision scenario, the time that it takes for Node A to detect that its frame has been collided with is twice the propagation delay. Node A’s frame must travel all the way to Node B, and then the collision signal must travel all the way from Node B back to Node A. This time is known as the slot time. An Ethernet node must be transmitting a frame for the slot time for a collision with that frame to be detected. This is the reason for the minimum Ethernet frame size.
Source: Microsoft® Windows® Server 2003 TCP/IP Protocols and Services Technical By Joseph Davies
Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc.
Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above
GATE-CS-2005
Computer Networks
GATE CS
MCQ
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Caesar Cipher in Cryptography
Socket Programming in Python
UDP Server-Client implementation in C
Differences between IPv4 and IPv6
Socket Programming in Java
ACID Properties in DBMS
Page Replacement Algorithms in Operating Systems
Types of Operating Systems
Normal Forms in DBMS
Semaphores in Process Synchronization | [
{
"code": null,
"e": 36592,
"s": 36564,
"text": "\n27 Mar, 2017"
},
{
"code": null,
"e": 36650,
"s": 36592,
"text": "Following questions have been asked in GATE CS 2005 exam."
},
{
"code": null,
"e": 36829,
"s": 36650,
"text": "1) An organization has a class B network and wishes to form subnets for 64 departments. The subnet mask would be:(a) 255.255.0.0(b) 255.255.64.0(c) 255.255.128.0(d) 255.255.252.0"
},
{
"code": null,
"e": 37063,
"s": 36829,
"text": "Answer (d)The size of network ID is 16 bit in class B networks. So bits after 16th bit must be used to create 64 departments. Total 6 bits are needed to identify 64 different departments. Therefore, subnet mask will be 255.255.252.0."
},
{
"code": null,
"e": 37325,
"s": 37063,
"text": "2) In a packet switching network, packets are routed from source to destination along a single path having two intermediate nodes. If the message size is 24 bytes and each packet contains a header of 3 bytes, then the optimum packet size is:(a) 4(b) 6(c) 7(d) 9"
},
{
"code": null,
"e": 37455,
"s": 37325,
"text": "Answer (d)Dividing a message into packets may decrease the transmission time due to parallelism as shown in the following figure."
},
{
"code": null,
"e": 37547,
"s": 37455,
"text": "But after a certain limit reducing the packet size may increase the transmission time also."
},
{
"code": null,
"e": 37603,
"s": 37547,
"text": "Following figure shows the situation given in question."
},
{
"code": null,
"e": 37843,
"s": 37603,
"text": "Let transmission time to transfer 1 byte for all nodes be t. The first packet will take time = (packet size)*3*t. After the first packet reaches the destination, remaining packets will take time equal to (packet size)*t due to parallelism."
},
{
"code": null,
"e": 38380,
"s": 37843,
"text": "If we use 4 bytes as packet size, there will be 24 packets\nTotal Transmission time = Time taken by first packet + \n Time taken by remaining packets \n = 3*4*t + 23*4*t = 104t\n\nIf we use 6 bytes as packet size, there will be 8 packets\nTotal Transmission time = 3*6*t + 7*6*t = 60t\n\nIf we use 7 bytes as packet size, there will be 6 packets\nTotal Transmission time = 3*7*t + 5*7*t = 56t\n\nIf we use 9 bytes as packet size, there will be 4 packets\nTotal Transmission time = 3*9*t + 3*9*t = 54t\n"
},
{
"code": null,
"e": 38542,
"s": 38380,
"text": "3) Suppose the round trip propagation delay for a 10 Mbps Ethernet having 48-bit jamming signal is 46.4 ms. The minimum frame size is:(a) 94(b) 416(c) 464(d) 512"
},
{
"code": null,
"e": 38746,
"s": 38542,
"text": "Answer (c)Transmission Speed = 10Mbps.Round trip propagation delay = 46.4 msThe minimum frame size = (Round Trip Propagation Delay) * (Transmission Speed) = 10*(10^6)*46.4*(10^-3) = 464 * 10^3 = 464 Kbit"
},
{
"code": null,
"e": 39819,
"s": 38746,
"text": "The concept behind the above formula is collision detection. Consider a situation where a node A wants to send a frame to another node B. When Node A begins transmitting, the signal must propagate the network length. In the worst-case collision scenario, Node B begins to transmit just before the signal for Node A’s frame reaches it. The collision signal of Node A and Node B’s frame must travel back to Node A for Node A to detect that a collision has occurred.The time it takes for a signal to propagate from one end of the network to the other is known as the propagation delay. In this worst-case collision scenario, the time that it takes for Node A to detect that its frame has been collided with is twice the propagation delay. Node A’s frame must travel all the way to Node B, and then the collision signal must travel all the way from Node B back to Node A. This time is known as the slot time. An Ethernet node must be transmitting a frame for the slot time for a collision with that frame to be detected. This is the reason for the minimum Ethernet frame size."
},
{
"code": null,
"e": 39916,
"s": 39819,
"text": "Source: Microsoft® Windows® Server 2003 TCP/IP Protocols and Services Technical By Joseph Davies"
},
{
"code": null,
"e": 40030,
"s": 39916,
"text": "Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc."
},
{
"code": null,
"e": 40178,
"s": 40030,
"text": "Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above"
},
{
"code": null,
"e": 40191,
"s": 40178,
"text": "GATE-CS-2005"
},
{
"code": null,
"e": 40209,
"s": 40191,
"text": "Computer Networks"
},
{
"code": null,
"e": 40217,
"s": 40209,
"text": "GATE CS"
},
{
"code": null,
"e": 40221,
"s": 40217,
"text": "MCQ"
},
{
"code": null,
"e": 40239,
"s": 40221,
"text": "Computer Networks"
},
{
"code": null,
"e": 40337,
"s": 40239,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40367,
"s": 40337,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 40396,
"s": 40367,
"text": "Socket Programming in Python"
},
{
"code": null,
"e": 40434,
"s": 40396,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 40468,
"s": 40434,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 40495,
"s": 40468,
"text": "Socket Programming in Java"
},
{
"code": null,
"e": 40519,
"s": 40495,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 40568,
"s": 40519,
"text": "Page Replacement Algorithms in Operating Systems"
},
{
"code": null,
"e": 40595,
"s": 40568,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 40616,
"s": 40595,
"text": "Normal Forms in DBMS"
}
] |
Connecting Python to Oracle, SQL Server, MySQL, and PostgreSQL | by Dario Radečić | Towards Data Science | I’ve also ignored them for a good part of my career, but then I needed to learn SQL and PL/SQL for my daily job. It’s a great skill to have — would even say a must for your CV — but clients wanting data science project delivered in PL/SQL is complete and utter idiotism.
But SQL does not equal to Databases. I love databases for their data storage capabilities, mainly for the reason that data is more secure than with CSVs — nobody can double click and open/alter your table in Excel.
For that reason, I’ve decided to write this article, because for some reason finding stuff online on this topic posted after 2010 isn’t as straightforward as you might think (and a LOT has changed since then).
To connect to the Oracle database you will, of course, need the database installed on your machine. My machine has 12c version, so there are no guarantees everything will work on older or newer versions. To test everything I’ve unlocked the famous HR schema and set the password to hr.
Once you do so too, clicking on Connections will show you every detail you need to connect Python to your Oracle database instance:
Before jumping into code, you will need to install cx_Oracle library through pip, like this:
pip install cx_oracle
The connection process is the lengthiest from the four I’ll cover today but is really simple if you read it line by line. I’ve chosen to fetch the first 10 rows from the famous employees table (note how Oracle uses ROWNUM, instead of TOP, or LIMIT):
import cx_Oracledsn = cx_Oracle.makedsn( 'localhost', '1521', service_name='orcl')conn = cx_Oracle.connect( user='hr', password='hr', dsn=dsn)c = conn.cursor()c.execute('SELECT * FROM employees WHERE ROWNUM <= 10')for row in c: print(row)conn.close()
Executing this code block will output the following to your Notebook:
That wasn’t so hard, was it? the following ones will be easier, or shorter to write at least, I promise!
Alongside with Oracle Database, SQL Server by Microsoft is also a pretty common database system to see in your typical work environment. To connect to it you will first need to grab the server name (the selected string):
Then, when you are connected to the database engine you will need to find the database name and table name, so you know what to put in the connection string:
Oh, almost forgot. You also need to install pyodbc library through pip:
pip install pyodbc
As promised, the code is a bit shorter than the one for connection to Oracle:
import pyodbcconn = pyodbc.connect( 'Driver={SQL Server};' 'Server=DESKTOP-TLF7IMQ\SQLEXPRESS;' 'Database=retail;' 'Trusted_Connection=yes;')cursor = conn.cursor()cursor.execute('SELECT TOP 5 * FROM dbo.table_transactions')for row in cursor: print(row)conn.close()
Executing this code cell will output the following:
Up next, MySQL.
Although maybe not used so many in work environments as the previous two, MySQL is still very popular, and you’ve probably used it before if you learned web development for example.
By default, MySQL instance comes with this sakila database, which looks really familiar to the dvdrental database. The connection I’ll make is to sakila database, and actor table.
My Python installed through Anaconda already came with necessary libraries built-in, so there’s no need for additional installations. To connect from Python, I’ll use mysql library:
import mysql.connectorconn = mysql.connector.connect( host='localhost', user='root', passwd='1234')cursor = conn.cursor()cursor.execute('SELECT * FROM sakila.actor LIMIT 5')for row in cursor: print(row)conn.close()
Once you execute this block of code you will get this as an output:
3 down, 1 to go!
Last but not least is the Postgres database. To connect to it you will need to install psycopg2 library:
pip install psycopg2
Strange name, I know. So easy to make a typo upon import.
Nevertheless, the connection process is fairly simple. My database instance contains the earlier mentioned dvdrental database, so I’ll connect to it, once again to the actor table:
import psycopg2conn = psycopg2.connect( user='postgres', password='1234', host='127.0.0.1', port='5432', database='dvdrental')cursor = conn.cursor()cursor.execute('SELECT * FROM actor LIMIT 10')for row in cursor: print(row)conn.close()
Executing that code block will output the following:
And that pretty much concludes this article. I’ve seen 15+ minutes article for connecting to only one database, covering all the nitty-gritty details. Personally, I don’t see a point in that, because come on, it’s only a database connection! There are a lot more important things to focus on.
If you are a data scientist you’ll be using databases mostly for fetching stuff, so this article is enough for you. For any more advanced stuff, ask your best friend, Google.
Thanks for reading...
Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you. | [
{
"code": null,
"e": 443,
"s": 172,
"text": "I’ve also ignored them for a good part of my career, but then I needed to learn SQL and PL/SQL for my daily job. It’s a great skill to have — would even say a must for your CV — but clients wanting data science project delivered in PL/SQL is complete and utter idiotism."
},
{
"code": null,
"e": 658,
"s": 443,
"text": "But SQL does not equal to Databases. I love databases for their data storage capabilities, mainly for the reason that data is more secure than with CSVs — nobody can double click and open/alter your table in Excel."
},
{
"code": null,
"e": 868,
"s": 658,
"text": "For that reason, I’ve decided to write this article, because for some reason finding stuff online on this topic posted after 2010 isn’t as straightforward as you might think (and a LOT has changed since then)."
},
{
"code": null,
"e": 1154,
"s": 868,
"text": "To connect to the Oracle database you will, of course, need the database installed on your machine. My machine has 12c version, so there are no guarantees everything will work on older or newer versions. To test everything I’ve unlocked the famous HR schema and set the password to hr."
},
{
"code": null,
"e": 1286,
"s": 1154,
"text": "Once you do so too, clicking on Connections will show you every detail you need to connect Python to your Oracle database instance:"
},
{
"code": null,
"e": 1379,
"s": 1286,
"text": "Before jumping into code, you will need to install cx_Oracle library through pip, like this:"
},
{
"code": null,
"e": 1401,
"s": 1379,
"text": "pip install cx_oracle"
},
{
"code": null,
"e": 1651,
"s": 1401,
"text": "The connection process is the lengthiest from the four I’ll cover today but is really simple if you read it line by line. I’ve chosen to fetch the first 10 rows from the famous employees table (note how Oracle uses ROWNUM, instead of TOP, or LIMIT):"
},
{
"code": null,
"e": 1924,
"s": 1651,
"text": "import cx_Oracledsn = cx_Oracle.makedsn( 'localhost', '1521', service_name='orcl')conn = cx_Oracle.connect( user='hr', password='hr', dsn=dsn)c = conn.cursor()c.execute('SELECT * FROM employees WHERE ROWNUM <= 10')for row in c: print(row)conn.close()"
},
{
"code": null,
"e": 1994,
"s": 1924,
"text": "Executing this code block will output the following to your Notebook:"
},
{
"code": null,
"e": 2099,
"s": 1994,
"text": "That wasn’t so hard, was it? the following ones will be easier, or shorter to write at least, I promise!"
},
{
"code": null,
"e": 2320,
"s": 2099,
"text": "Alongside with Oracle Database, SQL Server by Microsoft is also a pretty common database system to see in your typical work environment. To connect to it you will first need to grab the server name (the selected string):"
},
{
"code": null,
"e": 2478,
"s": 2320,
"text": "Then, when you are connected to the database engine you will need to find the database name and table name, so you know what to put in the connection string:"
},
{
"code": null,
"e": 2550,
"s": 2478,
"text": "Oh, almost forgot. You also need to install pyodbc library through pip:"
},
{
"code": null,
"e": 2569,
"s": 2550,
"text": "pip install pyodbc"
},
{
"code": null,
"e": 2647,
"s": 2569,
"text": "As promised, the code is a bit shorter than the one for connection to Oracle:"
},
{
"code": null,
"e": 2924,
"s": 2647,
"text": "import pyodbcconn = pyodbc.connect( 'Driver={SQL Server};' 'Server=DESKTOP-TLF7IMQ\\SQLEXPRESS;' 'Database=retail;' 'Trusted_Connection=yes;')cursor = conn.cursor()cursor.execute('SELECT TOP 5 * FROM dbo.table_transactions')for row in cursor: print(row)conn.close()"
},
{
"code": null,
"e": 2976,
"s": 2924,
"text": "Executing this code cell will output the following:"
},
{
"code": null,
"e": 2992,
"s": 2976,
"text": "Up next, MySQL."
},
{
"code": null,
"e": 3174,
"s": 2992,
"text": "Although maybe not used so many in work environments as the previous two, MySQL is still very popular, and you’ve probably used it before if you learned web development for example."
},
{
"code": null,
"e": 3354,
"s": 3174,
"text": "By default, MySQL instance comes with this sakila database, which looks really familiar to the dvdrental database. The connection I’ll make is to sakila database, and actor table."
},
{
"code": null,
"e": 3536,
"s": 3354,
"text": "My Python installed through Anaconda already came with necessary libraries built-in, so there’s no need for additional installations. To connect from Python, I’ll use mysql library:"
},
{
"code": null,
"e": 3760,
"s": 3536,
"text": "import mysql.connectorconn = mysql.connector.connect( host='localhost', user='root', passwd='1234')cursor = conn.cursor()cursor.execute('SELECT * FROM sakila.actor LIMIT 5')for row in cursor: print(row)conn.close()"
},
{
"code": null,
"e": 3828,
"s": 3760,
"text": "Once you execute this block of code you will get this as an output:"
},
{
"code": null,
"e": 3845,
"s": 3828,
"text": "3 down, 1 to go!"
},
{
"code": null,
"e": 3950,
"s": 3845,
"text": "Last but not least is the Postgres database. To connect to it you will need to install psycopg2 library:"
},
{
"code": null,
"e": 3971,
"s": 3950,
"text": "pip install psycopg2"
},
{
"code": null,
"e": 4029,
"s": 3971,
"text": "Strange name, I know. So easy to make a typo upon import."
},
{
"code": null,
"e": 4210,
"s": 4029,
"text": "Nevertheless, the connection process is fairly simple. My database instance contains the earlier mentioned dvdrental database, so I’ll connect to it, once again to the actor table:"
},
{
"code": null,
"e": 4461,
"s": 4210,
"text": "import psycopg2conn = psycopg2.connect( user='postgres', password='1234', host='127.0.0.1', port='5432', database='dvdrental')cursor = conn.cursor()cursor.execute('SELECT * FROM actor LIMIT 10')for row in cursor: print(row)conn.close()"
},
{
"code": null,
"e": 4514,
"s": 4461,
"text": "Executing that code block will output the following:"
},
{
"code": null,
"e": 4807,
"s": 4514,
"text": "And that pretty much concludes this article. I’ve seen 15+ minutes article for connecting to only one database, covering all the nitty-gritty details. Personally, I don’t see a point in that, because come on, it’s only a database connection! There are a lot more important things to focus on."
},
{
"code": null,
"e": 4982,
"s": 4807,
"text": "If you are a data scientist you’ll be using databases mostly for fetching stuff, so this article is enough for you. For any more advanced stuff, ask your best friend, Google."
},
{
"code": null,
"e": 5004,
"s": 4982,
"text": "Thanks for reading..."
}
] |
How to set a property having different datatype with a string value using reflection in C#? | Reflection is when managed code can read its own metadata to find assemblies.
Essentially, it allows code to inspect other code within the same system. With
reflection in C#, we can dynamically create an instance of a type and bind that type to
an existing object. Moreover, we can get the type from an existing object and access
its properties. When we use attributes in our code, reflection gives us access as it
provides objects of Type that describe modules, assemblies, and types.
Let us say we have a property of type double and in the runtime we actually have the value as string and assign it to the property after changing the type. We can use Convert.ChangeType() - It allows us to use runtime information on any IConvertible type to change representation formats.
Live Demo
using System;
using System.Reflection;
namespace DemoApplication{
class Program{
static void Main(){
Circle circle = new Circle();
string value = "6.5";
PropertyInfo propertyInfo = circle.GetType().GetProperty("Radius");
propertyInfo.SetValue(circle, Convert.ChangeType(value,
propertyInfo.PropertyType), null);
var radius = circle.GetType().GetProperty("Radius").GetValue(circle, null);
Console.WriteLine($"Radius: {radius}");
Console.ReadLine();
}
}
class Circle{
public double Radius { get; set; }
}
}
Radius: 6.5
In the above example we could see that string value "6.5" is converted to actual type
double using Convert.ChangeType and assigned to Radius property using reflection in
runtime. | [
{
"code": null,
"e": 1548,
"s": 1062,
"text": "Reflection is when managed code can read its own metadata to find assemblies.\nEssentially, it allows code to inspect other code within the same system. With\nreflection in C#, we can dynamically create an instance of a type and bind that type to\nan existing object. Moreover, we can get the type from an existing object and access\nits properties. When we use attributes in our code, reflection gives us access as it\nprovides objects of Type that describe modules, assemblies, and types."
},
{
"code": null,
"e": 1837,
"s": 1548,
"text": "Let us say we have a property of type double and in the runtime we actually have the value as string and assign it to the property after changing the type. We can use Convert.ChangeType() - It allows us to use runtime information on any IConvertible type to change representation formats."
},
{
"code": null,
"e": 1848,
"s": 1837,
"text": " Live Demo"
},
{
"code": null,
"e": 2455,
"s": 1848,
"text": "using System;\nusing System.Reflection;\nnamespace DemoApplication{\n class Program{\n static void Main(){\n Circle circle = new Circle();\n string value = \"6.5\";\n PropertyInfo propertyInfo = circle.GetType().GetProperty(\"Radius\");\n propertyInfo.SetValue(circle, Convert.ChangeType(value,\n propertyInfo.PropertyType), null);\n var radius = circle.GetType().GetProperty(\"Radius\").GetValue(circle, null);\n Console.WriteLine($\"Radius: {radius}\");\n Console.ReadLine();\n }\n }\n class Circle{\n public double Radius { get; set; }\n }\n}"
},
{
"code": null,
"e": 2467,
"s": 2455,
"text": "Radius: 6.5"
},
{
"code": null,
"e": 2646,
"s": 2467,
"text": "In the above example we could see that string value \"6.5\" is converted to actual type\ndouble using Convert.ChangeType and assigned to Radius property using reflection in\nruntime."
}
] |
Creating a prompt dialog box using Tkinter? | Dialog Boxes are handy for informing users to perform certain operations. We are already familiar with the dialog boxes and interacted with them many times. In a particular Tkinter application, we can create any type of dialog boxes, such as Message, User Interaction Dialogs, Single Value Entry Dialogs, File chooser, etc. To create dialog boxes, Tkinter has several built-in packages like a messagebox, simpledialog, filedialog, and colorchooser.
In this example, we will create a message box to inform the user to choose an option.
#Import the tkinter library
from tkinter import *
from tkinter import messagebox
#Create an instance of Tkinter frame
win= Tk()
#Define the geometry of the function
win.geometry("750x250")
answer = messagebox.askyesno("Question","Do you like Python Tkinter?")
#Create a Label
Label(win, text=answer, font= ('Georgia 20 bold')).pack()
win.mainloop()
Running the above code will display a prompt dialog box. Once we choose an option, it will display the Boolean value based on Yes (1) or No (0).
Once we click on Yes or No, it will update the Tkinter window with 1 or 0 values. | [
{
"code": null,
"e": 1511,
"s": 1062,
"text": "Dialog Boxes are handy for informing users to perform certain operations. We are already familiar with the dialog boxes and interacted with them many times. In a particular Tkinter application, we can create any type of dialog boxes, such as Message, User Interaction Dialogs, Single Value Entry Dialogs, File chooser, etc. To create dialog boxes, Tkinter has several built-in packages like a messagebox, simpledialog, filedialog, and colorchooser."
},
{
"code": null,
"e": 1597,
"s": 1511,
"text": "In this example, we will create a message box to inform the user to choose an option."
},
{
"code": null,
"e": 1946,
"s": 1597,
"text": "#Import the tkinter library\nfrom tkinter import *\nfrom tkinter import messagebox\n#Create an instance of Tkinter frame\nwin= Tk()\n#Define the geometry of the function\nwin.geometry(\"750x250\")\nanswer = messagebox.askyesno(\"Question\",\"Do you like Python Tkinter?\")\n#Create a Label\nLabel(win, text=answer, font= ('Georgia 20 bold')).pack()\nwin.mainloop()"
},
{
"code": null,
"e": 2091,
"s": 1946,
"text": "Running the above code will display a prompt dialog box. Once we choose an option, it will display the Boolean value based on Yes (1) or No (0)."
},
{
"code": null,
"e": 2173,
"s": 2091,
"text": "Once we click on Yes or No, it will update the Tkinter window with 1 or 0 values."
}
] |
Date.getMonth() function in JavaScript | The Date object is a data type built into the JavaScript language. Date objects are created with the new Date( ) as shown below.
Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object, using either local time or UTC (universal, or GMT) time.
The getMonth() function of the Date object returns the moth (0 represents January and so on...) of its current date.
Its syntax is as follows
dateObj.getMonth();
Live Demo
<html>
<head>
<title>JavaScript Example</title>
</head>
<body>
<script type="text/javascript">
var dateObj = new Date('september 26, 89 12:4:25:96');
document.write("Month of the year: "+dateObj.getMonth());
</script>
</body>
</html>
Month of the year: 8
Incase if you haven’t mentioned the month of the year while creating the date object, this function returns 0.
<html>
<head>
<title>JavaScript Example</title>
</head>
<body>
<script type="text/javascript">
var dateObj = new Date('89 12:4:25:96');
document.write("Month of the year: "+dateObj.getmonth());
</script>
</body>
</html>
Month of the year: 0
In the same way if you haven’t passed anything while creating the date object, this function returns the Current month of the current year.
<html>
<head>
<title>JavaScript Example</title>
</head>
<body>
<script type="text/javascript">
var dateObj = new Date();
document.write("Month of the year:+ "dateObj.getMonth());
</script>
</body>
</html>
Month of the year: 9 | [
{
"code": null,
"e": 1191,
"s": 1062,
"text": "The Date object is a data type built into the JavaScript language. Date objects are created with the new Date( ) as shown below."
},
{
"code": null,
"e": 1454,
"s": 1191,
"text": "Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object, using either local time or UTC (universal, or GMT) time."
},
{
"code": null,
"e": 1571,
"s": 1454,
"text": "The getMonth() function of the Date object returns the moth (0 represents January and so on...) of its current date."
},
{
"code": null,
"e": 1596,
"s": 1571,
"text": "Its syntax is as follows"
},
{
"code": null,
"e": 1616,
"s": 1596,
"text": "dateObj.getMonth();"
},
{
"code": null,
"e": 1627,
"s": 1616,
"text": " Live Demo"
},
{
"code": null,
"e": 1882,
"s": 1627,
"text": "<html>\n<head>\n <title>JavaScript Example</title>\n</head>\n<body>\n <script type=\"text/javascript\">\n var dateObj = new Date('september 26, 89 12:4:25:96');\n document.write(\"Month of the year: \"+dateObj.getMonth());\n </script>\n</body>\n</html>"
},
{
"code": null,
"e": 1903,
"s": 1882,
"text": "Month of the year: 8"
},
{
"code": null,
"e": 2014,
"s": 1903,
"text": "Incase if you haven’t mentioned the month of the year while creating the date object, this function returns 0."
},
{
"code": null,
"e": 2255,
"s": 2014,
"text": "<html>\n<head>\n <title>JavaScript Example</title>\n</head>\n<body>\n <script type=\"text/javascript\">\n var dateObj = new Date('89 12:4:25:96');\n document.write(\"Month of the year: \"+dateObj.getmonth());\n </script>\n</body>\n</html>"
},
{
"code": null,
"e": 2276,
"s": 2255,
"text": "Month of the year: 0"
},
{
"code": null,
"e": 2416,
"s": 2276,
"text": "In the same way if you haven’t passed anything while creating the date object, this function returns the Current month of the current year."
},
{
"code": null,
"e": 2642,
"s": 2416,
"text": "<html>\n<head>\n <title>JavaScript Example</title>\n</head>\n<body>\n <script type=\"text/javascript\">\n var dateObj = new Date();\n document.write(\"Month of the year:+ \"dateObj.getMonth());\n </script>\n</body>\n</html>"
},
{
"code": null,
"e": 2663,
"s": 2642,
"text": "Month of the year: 9"
}
] |
Get all the information of a Collection's indexes using PyMongo - GeeksforGeeks | 08 Jun, 2020
Prerequisites: MongoDB Python Basics
This article is about displaying the information of Collection’s indexes using the index_information() function of the PyMongo module.
index_information() returns a dictionary where the keys are index names (as returned by create_index()) and the values are dictionaries containing information about each index. The dictionary is guaranteed to contain at least a single key, “key” which is a list of (key, direction) pairs specifying the index (as passed to create_index()). It will also contain any other metadata about the indexes, except for the “ns” and “name” keys, which are cleaned.
Let’s begin:
Importing Required Modules: Import the required module using the command:from pymongo import MongoClient
If MongoDB is already not installed on your machine you can refer to the guide: Guide to Install MongoDB with PythonCreating a Connection: Now we had already imported the module, its time to establish a connection to the MongoDB server, presumably which is running on localhost (host name) at port 27017 (port number).client = MongoClient(‘localhost’, 27017)Accessing the Database: Since the connection to the MongoDB server is established. We can now create or use the existing database.mydatabase = client.name_of_the_databaseAccessing the Collection: We now select the collection from the database using the following syntax:collection_name = mydatabase.name_of_collectionGetting the information of the indexes: Using the function index_information to get the information of all the indexes of the collection.collection_name.index_information()
Importing Required Modules: Import the required module using the command:from pymongo import MongoClient
If MongoDB is already not installed on your machine you can refer to the guide: Guide to Install MongoDB with Python
from pymongo import MongoClient
If MongoDB is already not installed on your machine you can refer to the guide: Guide to Install MongoDB with Python
Creating a Connection: Now we had already imported the module, its time to establish a connection to the MongoDB server, presumably which is running on localhost (host name) at port 27017 (port number).client = MongoClient(‘localhost’, 27017)
client = MongoClient(‘localhost’, 27017)
Accessing the Database: Since the connection to the MongoDB server is established. We can now create or use the existing database.mydatabase = client.name_of_the_database
mydatabase = client.name_of_the_database
Accessing the Collection: We now select the collection from the database using the following syntax:collection_name = mydatabase.name_of_collection
collection_name = mydatabase.name_of_collection
Getting the information of the indexes: Using the function index_information to get the information of all the indexes of the collection.collection_name.index_information()
collection_name.index_information()
Example:
Sample Database:
# Python Program for demonstrating the # PyMongo Cursor to Pandas DataFrame # Importing required modulesfrom pymongo import MongoClientfrom pandas import DataFrame # Connecting to MongoDB server# client = MongoClient('host_name',# 'port_number')client = MongoClient('localhost', 27017) # Connecting to the database named# GFGmydatabase = client.GFG # Accessing the collection named# Studentmycollection = mydatabase.Student # Displaying the information of all the indexes# using the function index_information()ind_info = mycollection.index_information()print(ind_info)
Output:
{‘_id_’: {‘v’: 2, ‘key’: [(‘_id’, 1)], ‘ns’: ‘GFG.Student’}, ‘Roll No_1’: {‘v’: 2, ‘unique’: True, ‘key’: [(‘Roll No’, 1)], ‘ns’: ‘GFG.Student’}}
Python-mongoDB
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Defaultdict in Python
Selecting rows in pandas DataFrame based on conditions
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n08 Jun, 2020"
},
{
"code": null,
"e": 24329,
"s": 24292,
"text": "Prerequisites: MongoDB Python Basics"
},
{
"code": null,
"e": 24464,
"s": 24329,
"text": "This article is about displaying the information of Collection’s indexes using the index_information() function of the PyMongo module."
},
{
"code": null,
"e": 24919,
"s": 24464,
"text": "index_information() returns a dictionary where the keys are index names (as returned by create_index()) and the values are dictionaries containing information about each index. The dictionary is guaranteed to contain at least a single key, “key” which is a list of (key, direction) pairs specifying the index (as passed to create_index()). It will also contain any other metadata about the indexes, except for the “ns” and “name” keys, which are cleaned."
},
{
"code": null,
"e": 24932,
"s": 24919,
"text": "Let’s begin:"
},
{
"code": null,
"e": 25886,
"s": 24932,
"text": "Importing Required Modules: Import the required module using the command:from pymongo import MongoClient\nIf MongoDB is already not installed on your machine you can refer to the guide: Guide to Install MongoDB with PythonCreating a Connection: Now we had already imported the module, its time to establish a connection to the MongoDB server, presumably which is running on localhost (host name) at port 27017 (port number).client = MongoClient(‘localhost’, 27017)Accessing the Database: Since the connection to the MongoDB server is established. We can now create or use the existing database.mydatabase = client.name_of_the_databaseAccessing the Collection: We now select the collection from the database using the following syntax:collection_name = mydatabase.name_of_collectionGetting the information of the indexes: Using the function index_information to get the information of all the indexes of the collection.collection_name.index_information()\n"
},
{
"code": null,
"e": 26108,
"s": 25886,
"text": "Importing Required Modules: Import the required module using the command:from pymongo import MongoClient\nIf MongoDB is already not installed on your machine you can refer to the guide: Guide to Install MongoDB with Python"
},
{
"code": null,
"e": 26141,
"s": 26108,
"text": "from pymongo import MongoClient\n"
},
{
"code": null,
"e": 26258,
"s": 26141,
"text": "If MongoDB is already not installed on your machine you can refer to the guide: Guide to Install MongoDB with Python"
},
{
"code": null,
"e": 26501,
"s": 26258,
"text": "Creating a Connection: Now we had already imported the module, its time to establish a connection to the MongoDB server, presumably which is running on localhost (host name) at port 27017 (port number).client = MongoClient(‘localhost’, 27017)"
},
{
"code": null,
"e": 26542,
"s": 26501,
"text": "client = MongoClient(‘localhost’, 27017)"
},
{
"code": null,
"e": 26713,
"s": 26542,
"text": "Accessing the Database: Since the connection to the MongoDB server is established. We can now create or use the existing database.mydatabase = client.name_of_the_database"
},
{
"code": null,
"e": 26754,
"s": 26713,
"text": "mydatabase = client.name_of_the_database"
},
{
"code": null,
"e": 26902,
"s": 26754,
"text": "Accessing the Collection: We now select the collection from the database using the following syntax:collection_name = mydatabase.name_of_collection"
},
{
"code": null,
"e": 26950,
"s": 26902,
"text": "collection_name = mydatabase.name_of_collection"
},
{
"code": null,
"e": 27124,
"s": 26950,
"text": "Getting the information of the indexes: Using the function index_information to get the information of all the indexes of the collection.collection_name.index_information()\n"
},
{
"code": null,
"e": 27161,
"s": 27124,
"text": "collection_name.index_information()\n"
},
{
"code": null,
"e": 27170,
"s": 27161,
"text": "Example:"
},
{
"code": null,
"e": 27187,
"s": 27170,
"text": "Sample Database:"
},
{
"code": "# Python Program for demonstrating the # PyMongo Cursor to Pandas DataFrame # Importing required modulesfrom pymongo import MongoClientfrom pandas import DataFrame # Connecting to MongoDB server# client = MongoClient('host_name',# 'port_number')client = MongoClient('localhost', 27017) # Connecting to the database named# GFGmydatabase = client.GFG # Accessing the collection named# Studentmycollection = mydatabase.Student # Displaying the information of all the indexes# using the function index_information()ind_info = mycollection.index_information()print(ind_info)",
"e": 27767,
"s": 27187,
"text": null
},
{
"code": null,
"e": 27775,
"s": 27767,
"text": "Output:"
},
{
"code": null,
"e": 27921,
"s": 27775,
"text": "{‘_id_’: {‘v’: 2, ‘key’: [(‘_id’, 1)], ‘ns’: ‘GFG.Student’}, ‘Roll No_1’: {‘v’: 2, ‘unique’: True, ‘key’: [(‘Roll No’, 1)], ‘ns’: ‘GFG.Student’}}"
},
{
"code": null,
"e": 27936,
"s": 27921,
"text": "Python-mongoDB"
},
{
"code": null,
"e": 27943,
"s": 27936,
"text": "Python"
},
{
"code": null,
"e": 28041,
"s": 27943,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28073,
"s": 28041,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28115,
"s": 28073,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28171,
"s": 28115,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28213,
"s": 28171,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28235,
"s": 28213,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28290,
"s": 28235,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 28321,
"s": 28290,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28360,
"s": 28321,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28389,
"s": 28360,
"text": "Create a directory in Python"
}
] |
Exploratory Data Analysis with Pandas Profiling | by Albert Sanchez Lafuente | Towards Data Science | Pandas profiling is an open source Python module with which we can quickly do an exploratory data analysis with just a few lines of code. Besides, if this is not enough to convince us to use this tool, it also generates interactive reports in web format that can be presented to any person, even if they don’t know programming.
In short, what pandas profiling does is save us all the work of visualizing and understanding the distribution of each variable. It generates a report with all the information easily available.
To show you clearly how it works, this is an example of a report generated by pandas profiling:
You can also check an interactive report clicking this link.
One of the strong points of the generated report are the warnings that appear at the beginning. It tells us the variables that contain NaN values, variables with many zeros, categorical variables with high cardinality, etc.
First step is to install it with this command:
pip install pandas-profiling
Then we generate the report using these commands:
from pandas_profiling import ProfileReportprof = ProfileReport(df)prof.to_file(output_file='output.html')
Here we are, it’s been that simple. We can see the report generated in the output.html file.
The main disadvantage of pandas profiling is its use with large datasets. With the increase in the size of the data the time to generate the report also increases a lot.
One way to solve this problem is to generate the report from only a part of all the data we have. It is important to make sure that the data selected to generate the report is representative of all the data we have, for example it could be the case that the first X rows of data contain only data from one category. In this example we would like to randomize the order of the data and select a representative sample.
An example with code:
from pandas_profiling import ProfileReport#We only use the first 10000 data pointsprof = ProfileReport(df.sample(n=10000)) prof.to_file(output_file='output.html')
Another alternative is to use the minimum mode that was introduced in version 2.4 of pandas profiling. You can check which version you have installed with this command:
pandas_profiling.version.__version__
With the minimum mode a simplified report will be generated with less information than the full one but it can be generated relatively quickly for a large dataset. This is the code to be used:
profile = ProfileReport(df, minimal=True)profile.to_file(output_file="output_min.html") | [
{
"code": null,
"e": 499,
"s": 171,
"text": "Pandas profiling is an open source Python module with which we can quickly do an exploratory data analysis with just a few lines of code. Besides, if this is not enough to convince us to use this tool, it also generates interactive reports in web format that can be presented to any person, even if they don’t know programming."
},
{
"code": null,
"e": 693,
"s": 499,
"text": "In short, what pandas profiling does is save us all the work of visualizing and understanding the distribution of each variable. It generates a report with all the information easily available."
},
{
"code": null,
"e": 789,
"s": 693,
"text": "To show you clearly how it works, this is an example of a report generated by pandas profiling:"
},
{
"code": null,
"e": 850,
"s": 789,
"text": "You can also check an interactive report clicking this link."
},
{
"code": null,
"e": 1074,
"s": 850,
"text": "One of the strong points of the generated report are the warnings that appear at the beginning. It tells us the variables that contain NaN values, variables with many zeros, categorical variables with high cardinality, etc."
},
{
"code": null,
"e": 1121,
"s": 1074,
"text": "First step is to install it with this command:"
},
{
"code": null,
"e": 1150,
"s": 1121,
"text": "pip install pandas-profiling"
},
{
"code": null,
"e": 1200,
"s": 1150,
"text": "Then we generate the report using these commands:"
},
{
"code": null,
"e": 1306,
"s": 1200,
"text": "from pandas_profiling import ProfileReportprof = ProfileReport(df)prof.to_file(output_file='output.html')"
},
{
"code": null,
"e": 1399,
"s": 1306,
"text": "Here we are, it’s been that simple. We can see the report generated in the output.html file."
},
{
"code": null,
"e": 1569,
"s": 1399,
"text": "The main disadvantage of pandas profiling is its use with large datasets. With the increase in the size of the data the time to generate the report also increases a lot."
},
{
"code": null,
"e": 1986,
"s": 1569,
"text": "One way to solve this problem is to generate the report from only a part of all the data we have. It is important to make sure that the data selected to generate the report is representative of all the data we have, for example it could be the case that the first X rows of data contain only data from one category. In this example we would like to randomize the order of the data and select a representative sample."
},
{
"code": null,
"e": 2008,
"s": 1986,
"text": "An example with code:"
},
{
"code": null,
"e": 2171,
"s": 2008,
"text": "from pandas_profiling import ProfileReport#We only use the first 10000 data pointsprof = ProfileReport(df.sample(n=10000)) prof.to_file(output_file='output.html')"
},
{
"code": null,
"e": 2340,
"s": 2171,
"text": "Another alternative is to use the minimum mode that was introduced in version 2.4 of pandas profiling. You can check which version you have installed with this command:"
},
{
"code": null,
"e": 2377,
"s": 2340,
"text": "pandas_profiling.version.__version__"
},
{
"code": null,
"e": 2570,
"s": 2377,
"text": "With the minimum mode a simplified report will be generated with less information than the full one but it can be generated relatively quickly for a large dataset. This is the code to be used:"
}
] |
GATE | GATE-CS-2016 (Set 2) | Question 11 - GeeksforGeeks | 11 Oct, 2021
Consider the following expressions:(i) false(ii) Q(iii) true(iv) P ∨ Q(v) ¬Q ∨ PThe number of expressions given above that are logically implied by P ∧ (P ⇒ Q) is ______________
[This Question was originally a Fill-in-the-blanks Question](A) 2(B) 3(C) 4(D) 5Answer: (C)Explanation:
This solution is contributed by Anil Saikrishna Devarasetty.
Alternate Explanation :Answer is 4. Here is the solution
If say X is ‘Logically Implied’ by [ P ∧ (P ⇒ Q) ] then[ P ∧ (P ⇒ Q) ] ⇒ X is always true i.e it is a tautologyso if the above expression is a tautologythen we can say that X is logically implied by P ∧ (P ⇒ Q)
So we need to find X for which [ P ∧ (P ⇒ Q) ] ⇒ X will be always true for all values of P, Q and X.Look at the below table
P....Q...(P ⇒ Q)...[P ∧ (P ⇒ Q)].......X.......[ P ∧ (P ⇒ Q) ] ⇒ X
0....0.....1............0.............1/0............1......
0....1.....1............0.............1/0.... ......1......
1....0.....0..... ......0.............1/0............1......
1....1.....1............1..............1.............1.......
notice that value of X doesn’t matter if premise of expression i.ePremise of [ P ∧ (P ⇒ Q) ] ⇒ X i.e [ P ∧ (P ⇒ Q) ] is 0meaning the final expression would be a tautology for all values of X if [ P ∧ (P ⇒ Q) ] is 0
but if premise is 1 (as in last row) then X must be 1 so that the final implication i.e., [ P ∧ (P ⇒ Q) ] ⇒ X is true for all values.
if you replace X by all 5 options then you will find thatfor X = Q, True, P ∨ Q, ¬Q ∨ P the said expression would always be truefor X = False the expression would not be a tautologyHence # of expression is 4——————————————————————
Note:
An important inference rule called "modus ponenes"
says this [ P ∧ (P ⇒ Q) ] ⇒ Q is a tautology
we noted that if we replace X by Q then it is
indeed a tautology meaning Q is implied by
[ P ∧ (P ⇒ Q) ]
YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersPropositional Equivalence with Sakshi Singhal | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0054:04 / 1:00:27•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=cnLC3tgKzLM" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2016 (Set 2)
GATE-GATE-CS-2016 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2010 | Question 24
GATE | GATE CS 2011 | Question 7
GATE | GATE-IT-2004 | Question 71
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2012 | Question 54
GATE | GATE CS 2019 | Question 27
GATE | GATE-CS-2006 | Question 49 | [
{
"code": null,
"e": 24634,
"s": 24606,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 24812,
"s": 24634,
"text": "Consider the following expressions:(i) false(ii) Q(iii) true(iv) P ∨ Q(v) ¬Q ∨ PThe number of expressions given above that are logically implied by P ∧ (P ⇒ Q) is ______________"
},
{
"code": null,
"e": 24918,
"s": 24812,
"text": "[This Question was originally a Fill-in-the-blanks Question](A) 2(B) 3(C) 4(D) 5Answer: (C)Explanation: "
},
{
"code": null,
"e": 24981,
"s": 24920,
"text": "This solution is contributed by Anil Saikrishna Devarasetty."
},
{
"code": null,
"e": 25040,
"s": 24983,
"text": "Alternate Explanation :Answer is 4. Here is the solution"
},
{
"code": null,
"e": 25251,
"s": 25040,
"text": "If say X is ‘Logically Implied’ by [ P ∧ (P ⇒ Q) ] then[ P ∧ (P ⇒ Q) ] ⇒ X is always true i.e it is a tautologyso if the above expression is a tautologythen we can say that X is logically implied by P ∧ (P ⇒ Q)"
},
{
"code": null,
"e": 25375,
"s": 25251,
"text": "So we need to find X for which [ P ∧ (P ⇒ Q) ] ⇒ X will be always true for all values of P, Q and X.Look at the below table"
},
{
"code": null,
"e": 25688,
"s": 25375,
"text": "P....Q...(P ⇒ Q)...[P ∧ (P ⇒ Q)].......X.......[ P ∧ (P ⇒ Q) ] ⇒ X\n0....0.....1............0.............1/0............1......\n0....1.....1............0.............1/0.... ......1......\n1....0.....0..... ......0.............1/0............1......\n1....1.....1............1..............1.............1.......\n"
},
{
"code": null,
"e": 25903,
"s": 25688,
"text": "notice that value of X doesn’t matter if premise of expression i.ePremise of [ P ∧ (P ⇒ Q) ] ⇒ X i.e [ P ∧ (P ⇒ Q) ] is 0meaning the final expression would be a tautology for all values of X if [ P ∧ (P ⇒ Q) ] is 0"
},
{
"code": null,
"e": 26037,
"s": 25903,
"text": "but if premise is 1 (as in last row) then X must be 1 so that the final implication i.e., [ P ∧ (P ⇒ Q) ] ⇒ X is true for all values."
},
{
"code": null,
"e": 26267,
"s": 26037,
"text": "if you replace X by all 5 options then you will find thatfor X = Q, True, P ∨ Q, ¬Q ∨ P the said expression would always be truefor X = False the expression would not be a tautologyHence # of expression is 4——————————————————————"
},
{
"code": null,
"e": 26479,
"s": 26267,
"text": "Note: \nAn important inference rule called \"modus ponenes\" \nsays this [ P ∧ (P ⇒ Q) ] ⇒ Q is a tautology\nwe noted that if we replace X by Q then it is \nindeed a tautology meaning Q is implied by \n[ P ∧ (P ⇒ Q) ] "
},
{
"code": null,
"e": 27376,
"s": 26479,
"text": "YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersPropositional Equivalence with Sakshi Singhal | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0054:04 / 1:00:27•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=cnLC3tgKzLM\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question"
},
{
"code": null,
"e": 27397,
"s": 27376,
"text": "GATE-CS-2016 (Set 2)"
},
{
"code": null,
"e": 27423,
"s": 27397,
"text": "GATE-GATE-CS-2016 (Set 2)"
},
{
"code": null,
"e": 27428,
"s": 27423,
"text": "GATE"
},
{
"code": null,
"e": 27526,
"s": 27428,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27560,
"s": 27526,
"text": "GATE | GATE-IT-2004 | Question 66"
},
{
"code": null,
"e": 27602,
"s": 27560,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 48"
},
{
"code": null,
"e": 27644,
"s": 27602,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 27678,
"s": 27644,
"text": "GATE | GATE CS 2010 | Question 24"
},
{
"code": null,
"e": 27711,
"s": 27678,
"text": "GATE | GATE CS 2011 | Question 7"
},
{
"code": null,
"e": 27745,
"s": 27711,
"text": "GATE | GATE-IT-2004 | Question 71"
},
{
"code": null,
"e": 27778,
"s": 27745,
"text": "GATE | GATE-CS-2004 | Question 3"
},
{
"code": null,
"e": 27812,
"s": 27778,
"text": "GATE | GATE CS 2012 | Question 54"
},
{
"code": null,
"e": 27846,
"s": 27812,
"text": "GATE | GATE CS 2019 | Question 27"
}
] |
Maven - POM | POM stands for Project Object Model. It is fundamental unit of work in Maven. It is an XML file that resides in the base directory of the project as pom.xml.
The POM contains information about the project and various configuration detail used by Maven to build the project(s).
POM also contains the goals and plugins. While executing a task or goal, Maven looks for the POM in the current directory. It reads the POM, gets the needed configuration information, and then executes the goal. Some of the configuration that can be specified in the POM are following −
project dependencies
plugins
goals
build profiles
project version
developers
mailing list
Before creating a POM, we should first decide the project group (groupId), its name (artifactId) and its version as these attributes help in uniquely identifying the project in repository.
<project xmlns = "http://maven.apache.org/POM/4.0.0"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.companyname.project-group</groupId>
<artifactId>project</artifactId>
<version>1.0</version>
</project>
It should be noted that there should be a single POM file for each project.
All POM files require the project element and three mandatory fields: groupId, artifactId, version.
All POM files require the project element and three mandatory fields: groupId, artifactId, version.
Projects notation in repository is groupId:artifactId:version.
Projects notation in repository is groupId:artifactId:version.
Minimal requirements for a POM −
Minimal requirements for a POM −
Project root
This is project root tag. You need to specify the basic schema settings such as apache schema and w3.org specification.
Model version
Model version should be 4.0.0.
groupId
This is an Id of project's group. This is generally unique amongst an organization or a project. For example, a banking group com.company.bank has all bank related projects.
artifactId
This is an Id of the project. This is generally name of the project. For example, consumer-banking. Along with the groupId, the artifactId defines the artifact's location within the repository.
version
This is the version of the project. Along with the groupId, It is used within an artifact's repository to separate versions from each other. For example −
com.company.bank:consumer-banking:1.0
com.company.bank:consumer-banking:1.1.
The Super POM is Maven’s default POM. All POMs inherit from a parent or default (despite explicitly defined or not). This base POM is known as the Super POM, and contains values inherited by default.
Maven use the effective POM (configuration from super pom plus project configuration) to execute relevant goal. It helps developers to specify minimum configuration detail in his/her pom.xml. Although configurations can be overridden easily.
An easy way to look at the default configurations of the super POM is by running the following command: mvn help:effective-pom
Create a pom.xml in any directory on your computer.Use the content of above mentioned example pom.
In example below, We've created a pom.xml in C:\MVN\project folder.
Now open command console, go the folder containing pom.xml and execute the following mvn command.
C:\MVN\project>mvn help:effective-pom
Maven will start processing and display the effective-pom.
C:\MVN>mvn help:effective-pom
[INFO] Scanning for projects...
[INFO]
[INFO] ---------------< com.companyname.project-group:project >----------------
[INFO] Building project 1.0
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-help-plugin:3.2.0:effective-pom (default-cli) @ project ---
[INFO]
Effective POMs, after inheritance, interpolation, and profiles are applied:
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.261 s
[INFO] Finished at: 2021-12-10T19:54:53+05:30
[INFO] ------------------------------------------------------------------------
C:\MVN>
Effective POM displayed as result in console, after inheritance, interpolation, and profiles are applied.
<?xml version="1.0" encoding="Cp1252"?>
<!-- ====================================================================== -->
<!-- -->
<!-- Generated by Maven Help Plugin on 2021-12-10T19:54:52+05:30 -->
<!-- See: http://maven.apache.org/plugins/maven-help-plugin/ -->
<!-- -->
<!-- ====================================================================== -->
<!-- ====================================================================== -->
<!-- -->
<!-- Effective POM for project -->
<!-- 'com.companyname.project-group:project:jar:1.0' -->
<!-- -->
<!-- ====================================================================== -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.companyname.project-group</groupId>
<artifactId>project</artifactId>
<version>1.0</version>
<repositories>
<repository>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>central</id>
<name>Central Repository</name>
<url>https://repo.maven.apache.org/maven2</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<releases>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>central</id>
<name>Central Repository</name>
<url>https://repo.maven.apache.org/maven2</url>
</pluginRepository>
</pluginRepositories>
<build>
<sourceDirectory>C:\MVN\src\main\java</sourceDirectory>
<scriptSourceDirectory>C:\MVN\src\main\scripts</scriptSourceDirectory>
<testSourceDirectory>C:\MVN\src\test\java</testSourceDirectory>
<outputDirectory>C:\MVN\target\classes</outputDirectory>
<testOutputDirectory>C:\MVN\target\test-classes</testOutputDirectory>
<resources>
<resource>
<directory>C:\MVN\src\main\resources</directory>
</resource>
</resources>
<testResources>
<testResource>
<directory>C:\MVN\src\test\resources</directory>
</testResource>
</testResources>
<directory>C:\MVN\target</directory>
<finalName>project-1.0</finalName>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.3</version>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2-beta-5</version>
</plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.8</version>
</plugin>
<plugin>
<artifactId>maven-release-plugin</artifactId>
<version>2.5.3</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>2.5</version>
<executions>
<execution>
<id>default-clean</id>
<phase>clean</phase>
<goals>
<goal>clean</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<id>default-testResources</id>
<phase>process-test-resources</phase>
<goals>
<goal>testResources</goal>
</goals>
</execution>
<execution>
<id>default-resources</id>
<phase>process-resources</phase>
<goals>
<goal>resources</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<executions>
<execution>
<id>default-jar</id>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<executions>
<execution>
<id>default-compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>default-testCompile</id>
<phase>test-compile</phase>
<goals>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12.4</version>
<executions>
<execution>
<id>default-test</id>
<phase>test</phase>
<goals>
<goal>test</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.4</version>
<executions>
<execution>
<id>default-install</id>
<phase>install</phase>
<goals>
<goal>install</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.7</version>
<executions>
<execution>
<id>default-deploy</id>
<phase>deploy</phase>
<goals>
<goal>deploy</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.3</version>
<executions>
<execution>
<id>default-site</id>
<phase>site</phase>
<goals>
<goal>site</goal>
</goals>
<configuration>
<outputDirectory>C:\MVN\target\site</outputDirectory>
<reportPlugins>
<reportPlugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
</reportPlugin>
</reportPlugins>
</configuration>
</execution>
<execution>
<id>default-deploy</id>
<phase>site-deploy</phase>
<goals>
<goal>deploy</goal>
</goals>
<configuration>
<outputDirectory>C:\MVN\target\site</outputDirectory>
<reportPlugins>
<reportPlugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
</reportPlugin>
</reportPlugins>
</configuration>
</execution>
</executions>
<configuration>
<outputDirectory>C:\MVN\target\site</outputDirectory>
<reportPlugins>
<reportPlugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
</reportPlugin>
</reportPlugins>
</configuration>
</plugin>
</plugins>
</build>
<reporting>
<outputDirectory>C:\MVN\target\site</outputDirectory>
</reporting>
</project>
In above pom.xml, you can see the default project source folders structure, output directory, plug-ins required, repositories, reporting directory, which Maven will be using while executing the desired goals.
Maven pom.xml is also not required to be written manually. Maven provides numerous archetype plugins to create projects, which in order, create the project structure and pom.xml
34 Lectures
4 hours
Karthikeya T
14 Lectures
1.5 hours
Quaatso Learning
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2218,
"s": 2060,
"text": "POM stands for Project Object Model. It is fundamental unit of work in Maven. It is an XML file that resides in the base directory of the project as pom.xml."
},
{
"code": null,
"e": 2337,
"s": 2218,
"text": "The POM contains information about the project and various configuration detail used by Maven to build the project(s)."
},
{
"code": null,
"e": 2624,
"s": 2337,
"text": "POM also contains the goals and plugins. While executing a task or goal, Maven looks for the POM in the current directory. It reads the POM, gets the needed configuration information, and then executes the goal. Some of the configuration that can be specified in the POM are following −"
},
{
"code": null,
"e": 2645,
"s": 2624,
"text": "project dependencies"
},
{
"code": null,
"e": 2653,
"s": 2645,
"text": "plugins"
},
{
"code": null,
"e": 2659,
"s": 2653,
"text": "goals"
},
{
"code": null,
"e": 2674,
"s": 2659,
"text": "build profiles"
},
{
"code": null,
"e": 2690,
"s": 2674,
"text": "project version"
},
{
"code": null,
"e": 2701,
"s": 2690,
"text": "developers"
},
{
"code": null,
"e": 2714,
"s": 2701,
"text": "mailing list"
},
{
"code": null,
"e": 2903,
"s": 2714,
"text": "Before creating a POM, we should first decide the project group (groupId), its name (artifactId) and its version as these attributes help in uniquely identifying the project in repository."
},
{
"code": null,
"e": 3287,
"s": 2903,
"text": "<project xmlns = \"http://maven.apache.org/POM/4.0.0\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0\n http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n\n <groupId>com.companyname.project-group</groupId>\n <artifactId>project</artifactId>\n <version>1.0</version>\n</project>"
},
{
"code": null,
"e": 3363,
"s": 3287,
"text": "It should be noted that there should be a single POM file for each project."
},
{
"code": null,
"e": 3463,
"s": 3363,
"text": "All POM files require the project element and three mandatory fields: groupId, artifactId, version."
},
{
"code": null,
"e": 3563,
"s": 3463,
"text": "All POM files require the project element and three mandatory fields: groupId, artifactId, version."
},
{
"code": null,
"e": 3626,
"s": 3563,
"text": "Projects notation in repository is groupId:artifactId:version."
},
{
"code": null,
"e": 3689,
"s": 3626,
"text": "Projects notation in repository is groupId:artifactId:version."
},
{
"code": null,
"e": 3722,
"s": 3689,
"text": "Minimal requirements for a POM −"
},
{
"code": null,
"e": 3755,
"s": 3722,
"text": "Minimal requirements for a POM −"
},
{
"code": null,
"e": 3768,
"s": 3755,
"text": "Project root"
},
{
"code": null,
"e": 3888,
"s": 3768,
"text": "This is project root tag. You need to specify the basic schema settings such as apache schema and w3.org specification."
},
{
"code": null,
"e": 3902,
"s": 3888,
"text": "Model version"
},
{
"code": null,
"e": 3933,
"s": 3902,
"text": "Model version should be 4.0.0."
},
{
"code": null,
"e": 3941,
"s": 3933,
"text": "groupId"
},
{
"code": null,
"e": 4115,
"s": 3941,
"text": "This is an Id of project's group. This is generally unique amongst an organization or a project. For example, a banking group com.company.bank has all bank related projects."
},
{
"code": null,
"e": 4126,
"s": 4115,
"text": "artifactId"
},
{
"code": null,
"e": 4320,
"s": 4126,
"text": "This is an Id of the project. This is generally name of the project. For example, consumer-banking. Along with the groupId, the artifactId defines the artifact's location within the repository."
},
{
"code": null,
"e": 4328,
"s": 4320,
"text": "version"
},
{
"code": null,
"e": 4483,
"s": 4328,
"text": "This is the version of the project. Along with the groupId, It is used within an artifact's repository to separate versions from each other. For example −"
},
{
"code": null,
"e": 4521,
"s": 4483,
"text": "com.company.bank:consumer-banking:1.0"
},
{
"code": null,
"e": 4560,
"s": 4521,
"text": "com.company.bank:consumer-banking:1.1."
},
{
"code": null,
"e": 4760,
"s": 4560,
"text": "The Super POM is Maven’s default POM. All POMs inherit from a parent or default (despite explicitly defined or not). This base POM is known as the Super POM, and contains values inherited by default."
},
{
"code": null,
"e": 5002,
"s": 4760,
"text": "Maven use the effective POM (configuration from super pom plus project configuration) to execute relevant goal. It helps developers to specify minimum configuration detail in his/her pom.xml. Although configurations can be overridden easily."
},
{
"code": null,
"e": 5129,
"s": 5002,
"text": "An easy way to look at the default configurations of the super POM is by running the following command: mvn help:effective-pom"
},
{
"code": null,
"e": 5228,
"s": 5129,
"text": "Create a pom.xml in any directory on your computer.Use the content of above mentioned example pom."
},
{
"code": null,
"e": 5297,
"s": 5228,
"text": "In example below, We've created a pom.xml in C:\\MVN\\project folder. "
},
{
"code": null,
"e": 5395,
"s": 5297,
"text": "Now open command console, go the folder containing pom.xml and execute the following mvn command."
},
{
"code": null,
"e": 5434,
"s": 5395,
"text": "C:\\MVN\\project>mvn help:effective-pom\n"
},
{
"code": null,
"e": 5493,
"s": 5434,
"text": "Maven will start processing and display the effective-pom."
},
{
"code": null,
"e": 6263,
"s": 5493,
"text": "C:\\MVN>mvn help:effective-pom\n[INFO] Scanning for projects...\n[INFO]\n[INFO] ---------------< com.companyname.project-group:project >----------------\n[INFO] Building project 1.0\n[INFO] --------------------------------[ jar ]---------------------------------\n[INFO]\n[INFO] --- maven-help-plugin:3.2.0:effective-pom (default-cli) @ project ---\n[INFO]\nEffective POMs, after inheritance, interpolation, and profiles are applied:\n\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD SUCCESS\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 2.261 s\n[INFO] Finished at: 2021-12-10T19:54:53+05:30\n[INFO] ------------------------------------------------------------------------\n\nC:\\MVN>\n"
},
{
"code": null,
"e": 6369,
"s": 6263,
"text": "Effective POM displayed as result in console, after inheritance, interpolation, and profiles are applied."
},
{
"code": null,
"e": 15289,
"s": 6369,
"text": "<?xml version=\"1.0\" encoding=\"Cp1252\"?>\n<!-- ====================================================================== -->\n<!-- -->\n<!-- Generated by Maven Help Plugin on 2021-12-10T19:54:52+05:30 -->\n<!-- See: http://maven.apache.org/plugins/maven-help-plugin/ -->\n<!-- -->\n<!-- ====================================================================== -->\n<!-- ====================================================================== -->\n<!-- -->\n<!-- Effective POM for project -->\n<!-- 'com.companyname.project-group:project:jar:1.0' -->\n<!-- -->\n<!-- ====================================================================== -->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.companyname.project-group</groupId>\n <artifactId>project</artifactId>\n <version>1.0</version>\n <repositories>\n <repository>\n <snapshots>\n <enabled>false</enabled>\n </snapshots>\n <id>central</id>\n <name>Central Repository</name>\n <url>https://repo.maven.apache.org/maven2</url>\n </repository>\n </repositories>\n <pluginRepositories>\n <pluginRepository>\n <releases>\n <updatePolicy>never</updatePolicy>\n </releases>\n <snapshots>\n <enabled>false</enabled>\n </snapshots>\n <id>central</id>\n <name>Central Repository</name>\n <url>https://repo.maven.apache.org/maven2</url>\n </pluginRepository>\n </pluginRepositories>\n <build>\n <sourceDirectory>C:\\MVN\\src\\main\\java</sourceDirectory>\n <scriptSourceDirectory>C:\\MVN\\src\\main\\scripts</scriptSourceDirectory>\n <testSourceDirectory>C:\\MVN\\src\\test\\java</testSourceDirectory>\n <outputDirectory>C:\\MVN\\target\\classes</outputDirectory>\n <testOutputDirectory>C:\\MVN\\target\\test-classes</testOutputDirectory>\n <resources>\n <resource>\n <directory>C:\\MVN\\src\\main\\resources</directory>\n </resource>\n </resources>\n <testResources>\n <testResource>\n <directory>C:\\MVN\\src\\test\\resources</directory>\n </testResource>\n </testResources>\n <directory>C:\\MVN\\target</directory>\n <finalName>project-1.0</finalName>\n <pluginManagement>\n <plugins>\n <plugin>\n <artifactId>maven-antrun-plugin</artifactId>\n <version>1.3</version>\n </plugin>\n <plugin>\n <artifactId>maven-assembly-plugin</artifactId>\n <version>2.2-beta-5</version>\n </plugin>\n <plugin>\n <artifactId>maven-dependency-plugin</artifactId>\n <version>2.8</version>\n </plugin>\n <plugin>\n <artifactId>maven-release-plugin</artifactId>\n <version>2.5.3</version>\n </plugin>\n </plugins>\n </pluginManagement>\n <plugins>\n <plugin>\n <artifactId>maven-clean-plugin</artifactId>\n <version>2.5</version>\n <executions>\n <execution>\n <id>default-clean</id>\n <phase>clean</phase>\n <goals>\n <goal>clean</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n <plugin>\n <artifactId>maven-resources-plugin</artifactId>\n <version>2.6</version>\n <executions>\n <execution>\n <id>default-testResources</id>\n <phase>process-test-resources</phase>\n <goals>\n <goal>testResources</goal>\n </goals>\n </execution>\n <execution>\n <id>default-resources</id>\n <phase>process-resources</phase>\n <goals>\n <goal>resources</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n <plugin>\n <artifactId>maven-jar-plugin</artifactId>\n <version>2.4</version>\n <executions>\n <execution>\n <id>default-jar</id>\n <phase>package</phase>\n <goals>\n <goal>jar</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n <plugin>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>3.1</version>\n <executions>\n <execution>\n <id>default-compile</id>\n <phase>compile</phase>\n <goals>\n <goal>compile</goal>\n </goals>\n </execution>\n <execution>\n <id>default-testCompile</id>\n <phase>test-compile</phase>\n <goals>\n <goal>testCompile</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n <plugin>\n <artifactId>maven-surefire-plugin</artifactId>\n <version>2.12.4</version>\n <executions>\n <execution>\n <id>default-test</id>\n <phase>test</phase>\n <goals>\n <goal>test</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n <plugin>\n <artifactId>maven-install-plugin</artifactId>\n <version>2.4</version>\n <executions>\n <execution>\n <id>default-install</id>\n <phase>install</phase>\n <goals>\n <goal>install</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n <plugin>\n <artifactId>maven-deploy-plugin</artifactId>\n <version>2.7</version>\n <executions>\n <execution>\n <id>default-deploy</id>\n <phase>deploy</phase>\n <goals>\n <goal>deploy</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n <plugin>\n <artifactId>maven-site-plugin</artifactId>\n <version>3.3</version>\n <executions>\n <execution>\n <id>default-site</id>\n <phase>site</phase>\n <goals>\n <goal>site</goal>\n </goals>\n <configuration>\n <outputDirectory>C:\\MVN\\target\\site</outputDirectory>\n <reportPlugins>\n <reportPlugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-project-info-reports-plugin</artifactId>\n </reportPlugin>\n </reportPlugins>\n </configuration>\n </execution>\n <execution>\n <id>default-deploy</id>\n <phase>site-deploy</phase>\n <goals>\n <goal>deploy</goal>\n </goals>\n <configuration>\n <outputDirectory>C:\\MVN\\target\\site</outputDirectory>\n <reportPlugins>\n <reportPlugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-project-info-reports-plugin</artifactId>\n </reportPlugin>\n </reportPlugins>\n </configuration>\n </execution>\n </executions>\n <configuration>\n <outputDirectory>C:\\MVN\\target\\site</outputDirectory>\n <reportPlugins>\n <reportPlugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-project-info-reports-plugin</artifactId>\n </reportPlugin>\n </reportPlugins>\n </configuration>\n </plugin>\n </plugins>\n </build>\n <reporting>\n <outputDirectory>C:\\MVN\\target\\site</outputDirectory>\n </reporting>\n</project>"
},
{
"code": null,
"e": 15498,
"s": 15289,
"text": "In above pom.xml, you can see the default project source folders structure, output directory, plug-ins required, repositories, reporting directory, which Maven will be using while executing the desired goals."
},
{
"code": null,
"e": 15676,
"s": 15498,
"text": "Maven pom.xml is also not required to be written manually. Maven provides numerous archetype plugins to create projects, which in order, create the project structure and pom.xml"
},
{
"code": null,
"e": 15709,
"s": 15676,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 15723,
"s": 15709,
"text": " Karthikeya T"
},
{
"code": null,
"e": 15758,
"s": 15723,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 15776,
"s": 15758,
"text": " Quaatso Learning"
},
{
"code": null,
"e": 15783,
"s": 15776,
"text": " Print"
},
{
"code": null,
"e": 15794,
"s": 15783,
"text": " Add Notes"
}
] |
Python Program to merge two files into a third file | 29 Dec, 2020
Prerequisite: Reading and writing to a file.
Let the given two files be file1.txt and file2.txt. Our Task is to merge both files into third file say file3.txt. The following are steps to merge.
Open file1.txt and file2.txt in read mode.Open file3.txt in write mode.Read the data from file1 and add it in a string.Read the data from file2 and concatenate the data of this file to the previous string.Write the data from string to file3Close all the files
Open file1.txt and file2.txt in read mode.
Open file3.txt in write mode.
Read the data from file1 and add it in a string.
Read the data from file2 and concatenate the data of this file to the previous string.
Write the data from string to file3
Close all the files
Note: To successfully run the below program file1.txt and file2.txt must exist in the same folder.
Suppose the text files file1.txt and file2.txt contain the following data.
file1.txt
file2.txt
Below is the implementation.
# Python program to# demonstrate merging# of two files data = data2 = "" # Reading data from file1with open('file1.txt') as fp: data = fp.read() # Reading data from file2with open('file2.txt') as fp: data2 = fp.read() # Merging 2 files# To add the data of file2# from next linedata += "\n"data += data2 with open ('file3.txt', 'w') as fp: fp.write(data)
Output:
The above approach can be shortened using for loop. The following are steps to merge.
Create a list containing filenames.Open the file3 in write mode.Iterate through the list and open each file in read mode.Read the data from files and simultaneously write the data in file3.Close all the files
Create a list containing filenames.
Open the file3 in write mode.
Iterate through the list and open each file in read mode.
Read the data from files and simultaneously write the data in file3.
Close all the files
Below is the implementation.
# Python program to# demonstrate merging of# two files # Creating a list of filenamesfilenames = ['file1.txt', 'file2.txt'] # Open file3 in write modewith open('file3.txt', 'w') as outfile: # Iterate through list for names in filenames: # Open each file in read mode with open(names) as infile: # read the data from file1 and # file2 and write it in file3 outfile.write(infile.read()) # Add '\n' to enter data of file2 # from next line outfile.write("\n")
Output:
Python file-handling-programs
python-file-handling
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Dec, 2020"
},
{
"code": null,
"e": 73,
"s": 28,
"text": "Prerequisite: Reading and writing to a file."
},
{
"code": null,
"e": 222,
"s": 73,
"text": "Let the given two files be file1.txt and file2.txt. Our Task is to merge both files into third file say file3.txt. The following are steps to merge."
},
{
"code": null,
"e": 482,
"s": 222,
"text": "Open file1.txt and file2.txt in read mode.Open file3.txt in write mode.Read the data from file1 and add it in a string.Read the data from file2 and concatenate the data of this file to the previous string.Write the data from string to file3Close all the files"
},
{
"code": null,
"e": 525,
"s": 482,
"text": "Open file1.txt and file2.txt in read mode."
},
{
"code": null,
"e": 555,
"s": 525,
"text": "Open file3.txt in write mode."
},
{
"code": null,
"e": 604,
"s": 555,
"text": "Read the data from file1 and add it in a string."
},
{
"code": null,
"e": 691,
"s": 604,
"text": "Read the data from file2 and concatenate the data of this file to the previous string."
},
{
"code": null,
"e": 727,
"s": 691,
"text": "Write the data from string to file3"
},
{
"code": null,
"e": 747,
"s": 727,
"text": "Close all the files"
},
{
"code": null,
"e": 846,
"s": 747,
"text": "Note: To successfully run the below program file1.txt and file2.txt must exist in the same folder."
},
{
"code": null,
"e": 921,
"s": 846,
"text": "Suppose the text files file1.txt and file2.txt contain the following data."
},
{
"code": null,
"e": 931,
"s": 921,
"text": "file1.txt"
},
{
"code": null,
"e": 941,
"s": 931,
"text": "file2.txt"
},
{
"code": null,
"e": 970,
"s": 941,
"text": "Below is the implementation."
},
{
"code": "# Python program to# demonstrate merging# of two files data = data2 = \"\" # Reading data from file1with open('file1.txt') as fp: data = fp.read() # Reading data from file2with open('file2.txt') as fp: data2 = fp.read() # Merging 2 files# To add the data of file2# from next linedata += \"\\n\"data += data2 with open ('file3.txt', 'w') as fp: fp.write(data)",
"e": 1338,
"s": 970,
"text": null
},
{
"code": null,
"e": 1346,
"s": 1338,
"text": "Output:"
},
{
"code": null,
"e": 1432,
"s": 1346,
"text": "The above approach can be shortened using for loop. The following are steps to merge."
},
{
"code": null,
"e": 1641,
"s": 1432,
"text": "Create a list containing filenames.Open the file3 in write mode.Iterate through the list and open each file in read mode.Read the data from files and simultaneously write the data in file3.Close all the files"
},
{
"code": null,
"e": 1677,
"s": 1641,
"text": "Create a list containing filenames."
},
{
"code": null,
"e": 1707,
"s": 1677,
"text": "Open the file3 in write mode."
},
{
"code": null,
"e": 1765,
"s": 1707,
"text": "Iterate through the list and open each file in read mode."
},
{
"code": null,
"e": 1834,
"s": 1765,
"text": "Read the data from files and simultaneously write the data in file3."
},
{
"code": null,
"e": 1854,
"s": 1834,
"text": "Close all the files"
},
{
"code": null,
"e": 1883,
"s": 1854,
"text": "Below is the implementation."
},
{
"code": "# Python program to# demonstrate merging of# two files # Creating a list of filenamesfilenames = ['file1.txt', 'file2.txt'] # Open file3 in write modewith open('file3.txt', 'w') as outfile: # Iterate through list for names in filenames: # Open each file in read mode with open(names) as infile: # read the data from file1 and # file2 and write it in file3 outfile.write(infile.read()) # Add '\\n' to enter data of file2 # from next line outfile.write(\"\\n\")",
"e": 2423,
"s": 1883,
"text": null
},
{
"code": null,
"e": 2431,
"s": 2423,
"text": "Output:"
},
{
"code": null,
"e": 2461,
"s": 2431,
"text": "Python file-handling-programs"
},
{
"code": null,
"e": 2482,
"s": 2461,
"text": "python-file-handling"
},
{
"code": null,
"e": 2489,
"s": 2482,
"text": "Python"
}
] |
Python | time.monotonic_ns() method | 11 Oct, 2021
Time module in Python provides various time-related functions. This module comes under Python’s standard utility modules.
time.monotonic_ns() method of time module in Python is used to get the value of a monotonic clock in nanoseconds. This method is similar to time.monotonic() method which returns the monotonic clock value in fractional seconds. A monotonic clock is a clock that can not go backwards.
Syntax: time.monotonic_ns()
Parameter: No parameter is required.
Return type: This method returns an integer value which represents the value of a monotonic clock in nanoseconds.
Code #1: Use of time.monotonic_ns() method to get value of a monotonic clock in nanoseconds
# Python program to explain time.monotonic_ns() method # importing time moduleimport time # Get the value of# the monotonic clock in # fractional seconds using# time.monotonic() methodvalue1 = time.monotonic() # Get the value of# the monotonic clock in # nanoseconds using# time.monotonic_ns() methodvalue2 = time.monotonic_ns() # print the value of # the monotonic clock (in fractional seconds)print("Value of the monotonic clock (in fractional seconds):", value1) # print the value of # the monotonic clock (in nanoseconds)print("Value of the monotonic clock (in nanoseconds):", value2)
Value of the monotonic clock (in fractional seconds): 13486.679399824
Value of the monotonic clock (in nanoseconds): 13486679402777
Code #2: Use of time.monotonic_ns() method to measure elapsed time in long running process.
# Python program to explain time.monotonic_ns() method # importing time moduleimport time # Function to calculate factorial # of the given numberdef factorial(n): f = 1 for i in range(n, 1, -1): f = f * i return f # Get the value of the# monotonic clock in nanoseconds at the # beginning of the process# using time.monotonic_ns() methodstart = time.monotonic_ns() # print the value of # the monotonic clock in nanosecondsprint("At the beginning of the process")print("Value of the monotonic clock (in nanoseconds):", start, "\n") # Calculate factorial of all# numbers form 0 to 9i = 0fact = [0] * 10; while i < 10: fact[i] = factorial(i) i = i + 1 # Print the calculated factorialfor i in range(0, len(fact)): print("Factorial of % d:" % i, fact[i]) # Get the value of# monotonic clock in nanoseconds# using time.monotonic_ns() methodend = time.monotonic_ns() # print the value of # the monotonic clockprint("\nAt the end of the process")print("Value of the monotonic clock (in nanoseconds):", end)print("Time elapsed during the process:", end - start)
At the beginning of the process
Value of the monotonic clock (in nanoseconds): 14671301967243
Factorial of 0: 1
Factorial of 1: 1
Factorial of 2: 2
Factorial of 3: 6
Factorial of 4: 24
Factorial of 5: 120
Factorial of 6: 720
Factorial of 7: 5040
Factorial of 8: 40320
Factorial of 9: 362880
At the end of the process
Value of the monotonic clock (in nanoseconds): 14671302231487
Time elapsed during the process: 264244
Reference: https://docs.python.org/3/library/time.html#time.monotonic_ns
surinderdawra388
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 150,
"s": 28,
"text": "Time module in Python provides various time-related functions. This module comes under Python’s standard utility modules."
},
{
"code": null,
"e": 433,
"s": 150,
"text": "time.monotonic_ns() method of time module in Python is used to get the value of a monotonic clock in nanoseconds. This method is similar to time.monotonic() method which returns the monotonic clock value in fractional seconds. A monotonic clock is a clock that can not go backwards."
},
{
"code": null,
"e": 461,
"s": 433,
"text": "Syntax: time.monotonic_ns()"
},
{
"code": null,
"e": 498,
"s": 461,
"text": "Parameter: No parameter is required."
},
{
"code": null,
"e": 612,
"s": 498,
"text": "Return type: This method returns an integer value which represents the value of a monotonic clock in nanoseconds."
},
{
"code": null,
"e": 704,
"s": 612,
"text": "Code #1: Use of time.monotonic_ns() method to get value of a monotonic clock in nanoseconds"
},
{
"code": "# Python program to explain time.monotonic_ns() method # importing time moduleimport time # Get the value of# the monotonic clock in # fractional seconds using# time.monotonic() methodvalue1 = time.monotonic() # Get the value of# the monotonic clock in # nanoseconds using# time.monotonic_ns() methodvalue2 = time.monotonic_ns() # print the value of # the monotonic clock (in fractional seconds)print(\"Value of the monotonic clock (in fractional seconds):\", value1) # print the value of # the monotonic clock (in nanoseconds)print(\"Value of the monotonic clock (in nanoseconds):\", value2)",
"e": 1298,
"s": 704,
"text": null
},
{
"code": null,
"e": 1431,
"s": 1298,
"text": "Value of the monotonic clock (in fractional seconds): 13486.679399824\nValue of the monotonic clock (in nanoseconds): 13486679402777\n"
},
{
"code": null,
"e": 1523,
"s": 1431,
"text": "Code #2: Use of time.monotonic_ns() method to measure elapsed time in long running process."
},
{
"code": "# Python program to explain time.monotonic_ns() method # importing time moduleimport time # Function to calculate factorial # of the given numberdef factorial(n): f = 1 for i in range(n, 1, -1): f = f * i return f # Get the value of the# monotonic clock in nanoseconds at the # beginning of the process# using time.monotonic_ns() methodstart = time.monotonic_ns() # print the value of # the monotonic clock in nanosecondsprint(\"At the beginning of the process\")print(\"Value of the monotonic clock (in nanoseconds):\", start, \"\\n\") # Calculate factorial of all# numbers form 0 to 9i = 0fact = [0] * 10; while i < 10: fact[i] = factorial(i) i = i + 1 # Print the calculated factorialfor i in range(0, len(fact)): print(\"Factorial of % d:\" % i, fact[i]) # Get the value of# monotonic clock in nanoseconds# using time.monotonic_ns() methodend = time.monotonic_ns() # print the value of # the monotonic clockprint(\"\\nAt the end of the process\")print(\"Value of the monotonic clock (in nanoseconds):\", end)print(\"Time elapsed during the process:\", end - start) ",
"e": 2625,
"s": 1523,
"text": null
},
{
"code": null,
"e": 3048,
"s": 2625,
"text": "At the beginning of the process\nValue of the monotonic clock (in nanoseconds): 14671301967243 \n\nFactorial of 0: 1\nFactorial of 1: 1\nFactorial of 2: 2\nFactorial of 3: 6\nFactorial of 4: 24\nFactorial of 5: 120\nFactorial of 6: 720\nFactorial of 7: 5040\nFactorial of 8: 40320\nFactorial of 9: 362880\n\nAt the end of the process\nValue of the monotonic clock (in nanoseconds): 14671302231487\nTime elapsed during the process: 264244\n"
},
{
"code": null,
"e": 3121,
"s": 3048,
"text": "Reference: https://docs.python.org/3/library/time.html#time.monotonic_ns"
},
{
"code": null,
"e": 3138,
"s": 3121,
"text": "surinderdawra388"
},
{
"code": null,
"e": 3153,
"s": 3138,
"text": "python-utility"
},
{
"code": null,
"e": 3160,
"s": 3153,
"text": "Python"
}
] |
Coin Change | Practice | GeeksforGeeks | Given a value N, find the number of ways to make change for N cents, if we have infinite supply of each of S = { S1, S2, .. , SM } valued coins.
Example 1:
Input:
n = 4 , m = 3
S[] = {1,2,3}
Output: 4
Explanation: Four Possible ways are:
{1,1,1,1},{1,1,2},{2,2},{1,3}.
Example 2:
Input:
n = 10 , m = 4
S[] ={2,5,3,6}
Output: 5
Explanation: Five Possible ways are:
{2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5}
and {5,5}.
Your Task:
You don't need to read input or print anything. Your task is to complete the function count() which accepts an array S[] its size m and n as input parameter and returns the number of ways to make change for N cents.
Expected Time Complexity: O(m*n).
Expected Auxiliary Space: O(n).
Constraints:
1 <= n,m <= 103
0
savr123in 11 hours
C++ SOLUTION USING DP[MEMO+REC]
long long int f(int i,int num[], int x,vector<vector<long long>> &dp){ if(i==0) { if(x%num[0]==0) return 1; else return 0; } if(dp[i][x]!=-1) return dp[i][x]; long long int pick=0; if(x>=num[i]) pick=f(i,num,x-num[i],dp); long long int notpick=f(i-1,num,x,dp);
return dp[i][x]=(pick+notpick);}long long int count(int S[], int m, int n)
{
vector<vector<long long>> dp(m,vector<long long>(n+1,-1)); return f(m-1,S,n,dp); }
0
mishraaman4351 hour ago
JAVA
class Solution {
public long count(int S[], int m, int n) {
Arrays.sort(S);
long []v = new long [n+1];
v[0]=1;
for(int i=0; i<m; i++){
int j=S[i];
while(j<=n){
v[j]=v[j]+v[j-S[i]];
j++;
}
}
return v[n];
}
}
0
kvatsadeo5 hours ago
public:
long long int f(int ind,int tar,int arr[],vector<vector<long long int>> &dp){
if(ind==0) return ((tar%arr[ind])==0);
if(dp[ind][tar]!=-1) return dp[ind][tar];
if(arr[ind]<=tar){
return dp[ind][tar]=f(ind,tar-arr[ind],arr,dp)+f(ind-1,tar,arr,dp);
}
return dp[ind][tar]=f(ind-1,tar,arr,dp);
}
long long int count(int arr[], int m, int n) {
return f(m-1,n,arr,dp);
}
tabulation:
vector<vector<long long int>> dp(m,vector<long long int>(n+1,0));
for(int tar=0;tar<=n;tar++){
dp[0][tar]=((tar%arr[0])==0);
}
for(int ind=1;ind<m;ind++){
for(int tar=0;tar<=n;tar++){
if(arr[ind]<=tar){
dp[ind][tar]=dp[ind][tar-arr[ind]]+dp[ind-1][tar];
}else dp[ind][tar]=dp[ind-1][tar];
}
}
return dp[m-1][n];
+1
shobit15024 days ago
Easy solution c++
long long int dp[1001][1001];
long long int solve(int s[],int &m,int n,int p){
if(n==0)return 1;
if(n<0 or p==m)return 0;
if(dp[n][p]!=-1)return dp[n][p];
long long int ans=0;
ans+=solve(s,m,n-s[p],p);
ans+=solve(s,m,n,p+1);
return dp[n][p]=ans;
}
long long int count(int S[], int m, int n) {
memset(dp,-1,sizeof dp);
return solve(S,m,n,0);
}
0
dev864405 days ago
//Recursion
long long int sol(int nums[],int m,int tar,int i){
if(tar==0)return 1;
if(i==0||tar<0)return 0;
if(nums[i-1]<=tar)return sol(nums,m,tar-nums[i-1],i)+sol(nums,m,tar,i-1);
else return sol(nums,m,tar,i-1);
}
//Tabulation
long long int count(int nums[], int m, int n) {
vector<long long int>dp(n+1,0);
dp[0]=1;
for(int i=1;i<m+1;i++){
vector<long long int>temp(n+1,0);
temp[0]=1;
for(int j=1;j<n+1;j++){
if(nums[i-1]<=j) temp[j]=temp[j-nums[i-1]]+dp[j];
else temp[j]=dp[j];
}
dp=temp;
}
return dp[n];
}
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": 384,
"s": 238,
"text": "Given a value N, find the number of ways to make change for N cents, if we have infinite supply of each of S = { S1, S2, .. , SM } valued coins. "
},
{
"code": null,
"e": 396,
"s": 384,
"text": "\nExample 1:"
},
{
"code": null,
"e": 510,
"s": 396,
"text": "Input:\nn = 4 , m = 3\nS[] = {1,2,3}\nOutput: 4\nExplanation: Four Possible ways are:\n{1,1,1,1},{1,1,2},{2,2},{1,3}.\n"
},
{
"code": null,
"e": 521,
"s": 510,
"text": "Example 2:"
},
{
"code": null,
"e": 659,
"s": 521,
"text": "Input:\nn = 10 , m = 4\nS[] ={2,5,3,6}\nOutput: 5\nExplanation: Five Possible ways are:\n{2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5} \nand {5,5}.\n"
},
{
"code": null,
"e": 887,
"s": 659,
"text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function count() which accepts an array S[] its size m and n as input parameter and returns the number of ways to make change for N cents."
},
{
"code": null,
"e": 955,
"s": 887,
"text": "\nExpected Time Complexity: O(m*n).\nExpected Auxiliary Space: O(n). "
},
{
"code": null,
"e": 985,
"s": 955,
"text": "\nConstraints:\n1 <= n,m <= 103"
},
{
"code": null,
"e": 987,
"s": 985,
"text": "0"
},
{
"code": null,
"e": 1006,
"s": 987,
"text": "savr123in 11 hours"
},
{
"code": null,
"e": 1039,
"s": 1006,
"text": "C++ SOLUTION USING DP[MEMO+REC]"
},
{
"code": null,
"e": 1342,
"s": 1039,
"text": "long long int f(int i,int num[], int x,vector<vector<long long>> &dp){ if(i==0) { if(x%num[0]==0) return 1; else return 0; } if(dp[i][x]!=-1) return dp[i][x]; long long int pick=0; if(x>=num[i]) pick=f(i,num,x-num[i],dp); long long int notpick=f(i-1,num,x,dp);"
},
{
"code": null,
"e": 1420,
"s": 1342,
"text": " return dp[i][x]=(pick+notpick);}long long int count(int S[], int m, int n)"
},
{
"code": null,
"e": 1423,
"s": 1420,
"text": " {"
},
{
"code": null,
"e": 1519,
"s": 1423,
"text": " vector<vector<long long>> dp(m,vector<long long>(n+1,-1)); return f(m-1,S,n,dp); }"
},
{
"code": null,
"e": 1521,
"s": 1519,
"text": "0"
},
{
"code": null,
"e": 1545,
"s": 1521,
"text": "mishraaman4351 hour ago"
},
{
"code": null,
"e": 1550,
"s": 1545,
"text": "JAVA"
},
{
"code": null,
"e": 1881,
"s": 1550,
"text": "class Solution {\n public long count(int S[], int m, int n) {\n Arrays.sort(S);\n long []v = new long [n+1];\n v[0]=1;\n for(int i=0; i<m; i++){\n int j=S[i];\n while(j<=n){\n v[j]=v[j]+v[j-S[i]];\n j++;\n }\n }\n return v[n];\n }\n}"
},
{
"code": null,
"e": 1883,
"s": 1881,
"text": "0"
},
{
"code": null,
"e": 1904,
"s": 1883,
"text": "kvatsadeo5 hours ago"
},
{
"code": null,
"e": 2834,
"s": 1904,
"text": " public:\n long long int f(int ind,int tar,int arr[],vector<vector<long long int>> &dp){\n if(ind==0) return ((tar%arr[ind])==0);\n if(dp[ind][tar]!=-1) return dp[ind][tar];\n if(arr[ind]<=tar){\n return dp[ind][tar]=f(ind,tar-arr[ind],arr,dp)+f(ind-1,tar,arr,dp);\n }\n return dp[ind][tar]=f(ind-1,tar,arr,dp);\n }\n long long int count(int arr[], int m, int n) {\n return f(m-1,n,arr,dp);\n }\n \n \n tabulation:\n vector<vector<long long int>> dp(m,vector<long long int>(n+1,0));\n \n for(int tar=0;tar<=n;tar++){\n dp[0][tar]=((tar%arr[0])==0);\n }\n for(int ind=1;ind<m;ind++){\n for(int tar=0;tar<=n;tar++){\n if(arr[ind]<=tar){\n dp[ind][tar]=dp[ind][tar-arr[ind]]+dp[ind-1][tar];\n }else dp[ind][tar]=dp[ind-1][tar];\n }\n }\n return dp[m-1][n];"
},
{
"code": null,
"e": 2843,
"s": 2840,
"text": "+1"
},
{
"code": null,
"e": 2864,
"s": 2843,
"text": "shobit15024 days ago"
},
{
"code": null,
"e": 2882,
"s": 2864,
"text": "Easy solution c++"
},
{
"code": null,
"e": 3353,
"s": 2882,
"text": "\tlong long int dp[1001][1001];\n long long int solve(int s[],int &m,int n,int p){\n \n if(n==0)return 1;\n if(n<0 or p==m)return 0;\n if(dp[n][p]!=-1)return dp[n][p];\n long long int ans=0;\n \n ans+=solve(s,m,n-s[p],p);\n ans+=solve(s,m,n,p+1);\n \n return dp[n][p]=ans;\n }\n long long int count(int S[], int m, int n) \t\t\t\t\t\t\t\t\t\t {\n memset(dp,-1,sizeof dp);\n return solve(S,m,n,0);\n }"
},
{
"code": null,
"e": 3355,
"s": 3353,
"text": "0"
},
{
"code": null,
"e": 3374,
"s": 3355,
"text": "dev864405 days ago"
},
{
"code": null,
"e": 4050,
"s": 3374,
"text": "//Recursion\n\nlong long int sol(int nums[],int m,int tar,int i){\n if(tar==0)return 1;\n if(i==0||tar<0)return 0;\n \n if(nums[i-1]<=tar)return sol(nums,m,tar-nums[i-1],i)+sol(nums,m,tar,i-1);\n else return sol(nums,m,tar,i-1);\n }\n \n //Tabulation\n long long int count(int nums[], int m, int n) {\n vector<long long int>dp(n+1,0);\n dp[0]=1;\n \n for(int i=1;i<m+1;i++){\n vector<long long int>temp(n+1,0);\n temp[0]=1;\n for(int j=1;j<n+1;j++){\n if(nums[i-1]<=j) temp[j]=temp[j-nums[i-1]]+dp[j];\n else temp[j]=dp[j];\n }\n dp=temp;\n }\n return dp[n];\n }"
},
{
"code": null,
"e": 4196,
"s": 4050,
"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": 4232,
"s": 4196,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4242,
"s": 4232,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4252,
"s": 4242,
"text": "\nContest\n"
},
{
"code": null,
"e": 4315,
"s": 4252,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4500,
"s": 4315,
"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": 4784,
"s": 4500,
"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": 4930,
"s": 4784,
"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": 5007,
"s": 4930,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 5048,
"s": 5007,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 5076,
"s": 5048,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 5147,
"s": 5076,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 5334,
"s": 5147,
"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."
}
] |
Svelte | Introduction and Installation | 11 Feb, 2022
Svelte is the new methodology for creating web apps. It can be used in a small part of a code or in an entire single page application. It is a compiler not a framework, which is faster than other JavaScript libraries like ReactJS, AngularJS, VueJS. It is used to create reactive web apps. If any change occurs in the data that change will reflect on the page instantly. It is also used in rapid application development (RAD) means quickly produce minimally coded software application. It is used in Web Optimization. But it does not use virtual DOM which makes it different from others. It is free and open source written by Rich Harris. Svelte Compiles your Code for production at execution time into vanilla JavaScript bundle. If you deploy your application over the internet then you don’t need to deploy Svelte like we did other library. That’s why it results in a fast execution.
Prerequisite: Before installing or start working on Svelte, we have to make sure few things are available in our system.
Any Text Editor(e.g vs code, Atom etc.)
NodeJS installed in your system: Installation of Node.js on WindowsInstallation of Node.js on Linux
Installation of Node.js on WindowsInstallation of Node.js on Linux
Installation of Node.js on Windows
Installation of Node.js on Linux
Installation of Svelte: Now we are ready to install the Svelte.
Step 1: Open the command prompt or terminal and install a package named degit, which allows us to easily clone the latest commit from a github repository.
npm install -g degit
Step 2: Now create a directory on the desktop and run the below command. The degit go to the repository(sveltejs) find the template and download it locally for us in the project named myproject.
degit sveltejs/template myproject
Step 3: The project is created, now open this in text editor. In the src folder we have main.js file which is used to execute our svelte app The App.svelte is the root component of our application and the package.json file contains all the dependencies which needs to be installed.
Step 4: Now install all the dependencies make sure you are inside of the “myproject” directory.
npm install
Step 5: Now create a local development server to run our application.
npm run dev
Step 6: Now follow the above link and application will open in the browser.
sagar0719kumar
kk9826225
siddharthdedhia11
how-to-install
JavaScript-Misc
Installation Guide
JavaScript
Web Technologies
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Feb, 2022"
},
{
"code": null,
"e": 914,
"s": 28,
"text": "Svelte is the new methodology for creating web apps. It can be used in a small part of a code or in an entire single page application. It is a compiler not a framework, which is faster than other JavaScript libraries like ReactJS, AngularJS, VueJS. It is used to create reactive web apps. If any change occurs in the data that change will reflect on the page instantly. It is also used in rapid application development (RAD) means quickly produce minimally coded software application. It is used in Web Optimization. But it does not use virtual DOM which makes it different from others. It is free and open source written by Rich Harris. Svelte Compiles your Code for production at execution time into vanilla JavaScript bundle. If you deploy your application over the internet then you don’t need to deploy Svelte like we did other library. That’s why it results in a fast execution. "
},
{
"code": null,
"e": 1036,
"s": 914,
"text": "Prerequisite: Before installing or start working on Svelte, we have to make sure few things are available in our system. "
},
{
"code": null,
"e": 1076,
"s": 1036,
"text": "Any Text Editor(e.g vs code, Atom etc.)"
},
{
"code": null,
"e": 1176,
"s": 1076,
"text": "NodeJS installed in your system: Installation of Node.js on WindowsInstallation of Node.js on Linux"
},
{
"code": null,
"e": 1243,
"s": 1176,
"text": "Installation of Node.js on WindowsInstallation of Node.js on Linux"
},
{
"code": null,
"e": 1278,
"s": 1243,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 1311,
"s": 1278,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1377,
"s": 1311,
"text": "Installation of Svelte: Now we are ready to install the Svelte. "
},
{
"code": null,
"e": 1533,
"s": 1377,
"text": "Step 1: Open the command prompt or terminal and install a package named degit, which allows us to easily clone the latest commit from a github repository. "
},
{
"code": null,
"e": 1554,
"s": 1533,
"text": "npm install -g degit"
},
{
"code": null,
"e": 1752,
"s": 1556,
"text": "Step 2: Now create a directory on the desktop and run the below command. The degit go to the repository(sveltejs) find the template and download it locally for us in the project named myproject. "
},
{
"code": null,
"e": 1786,
"s": 1752,
"text": "degit sveltejs/template myproject"
},
{
"code": null,
"e": 2071,
"s": 1788,
"text": "Step 3: The project is created, now open this in text editor. In the src folder we have main.js file which is used to execute our svelte app The App.svelte is the root component of our application and the package.json file contains all the dependencies which needs to be installed. "
},
{
"code": null,
"e": 2168,
"s": 2071,
"text": "Step 4: Now install all the dependencies make sure you are inside of the “myproject” directory. "
},
{
"code": null,
"e": 2180,
"s": 2168,
"text": "npm install"
},
{
"code": null,
"e": 2251,
"s": 2180,
"text": "Step 5: Now create a local development server to run our application. "
},
{
"code": null,
"e": 2263,
"s": 2251,
"text": "npm run dev"
},
{
"code": null,
"e": 2339,
"s": 2263,
"text": "Step 6: Now follow the above link and application will open in the browser."
},
{
"code": null,
"e": 2354,
"s": 2339,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 2364,
"s": 2354,
"text": "kk9826225"
},
{
"code": null,
"e": 2382,
"s": 2364,
"text": "siddharthdedhia11"
},
{
"code": null,
"e": 2397,
"s": 2382,
"text": "how-to-install"
},
{
"code": null,
"e": 2413,
"s": 2397,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 2432,
"s": 2413,
"text": "Installation Guide"
},
{
"code": null,
"e": 2443,
"s": 2432,
"text": "JavaScript"
},
{
"code": null,
"e": 2460,
"s": 2443,
"text": "Web Technologies"
},
{
"code": null,
"e": 2476,
"s": 2460,
"text": "Write From Home"
}
] |
GATE | GATE CS 1996 | Question 8 | 21 May, 2020
Which two of the following four regular expressions are equivalent? (ε is the empty string).(i). (00)*(ε+0)(ii). (00)*(iii). 0*(iv). 0(00)*(A) (i) and (ii)(B) (ii) and (iii)(C) (i) and (iii)(D) (iii) and (iv)Answer: (C)Explanation: Here,
(00)*(ε+0)
= (00)*.ε+ (00)*.0
= (00)* + (00)*0
= 0*
It is equal to (iii) [ using regular expression properties ].
Here,we see that (00)* generates strings of even length and (00)*0 generated the strings of odd length.
Option (C) is correct.Quiz of this Question
vivekkumarmth0077
GATE CS 1996
GATE-GATE CS 1996
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 May, 2020"
},
{
"code": null,
"e": 266,
"s": 28,
"text": "Which two of the following four regular expressions are equivalent? (ε is the empty string).(i). (00)*(ε+0)(ii). (00)*(iii). 0*(iv). 0(00)*(A) (i) and (ii)(B) (ii) and (iii)(C) (i) and (iii)(D) (iii) and (iv)Answer: (C)Explanation: Here,"
},
{
"code": null,
"e": 321,
"s": 266,
"text": "(00)*(ε+0)\n= (00)*.ε+ (00)*.0 \n= (00)* + (00)*0 \n= 0* "
},
{
"code": null,
"e": 383,
"s": 321,
"text": "It is equal to (iii) [ using regular expression properties ]."
},
{
"code": null,
"e": 487,
"s": 383,
"text": "Here,we see that (00)* generates strings of even length and (00)*0 generated the strings of odd length."
},
{
"code": null,
"e": 531,
"s": 487,
"text": "Option (C) is correct.Quiz of this Question"
},
{
"code": null,
"e": 549,
"s": 531,
"text": "vivekkumarmth0077"
},
{
"code": null,
"e": 562,
"s": 549,
"text": "GATE CS 1996"
},
{
"code": null,
"e": 580,
"s": 562,
"text": "GATE-GATE CS 1996"
},
{
"code": null,
"e": 585,
"s": 580,
"text": "GATE"
}
] |
How to Check whether Element Exists in Java ArrayList? | 04 Dec, 2020
Java ArrayList is a resizable array, which can be found in java.util package. We can add or delete elements from an ArrayList whenever we want, unlike a built-in array.
We can check whether an element exists in ArrayList in java in two ways:
Using contains() methodUsing indexOf() method
Using contains() method
Using indexOf() method
Method 1: Using contains() method
The contains() method of the java.util.ArrayList class can be used to check whether an element exists in Java ArrayList.
Syntax:
public boolean contains(Object)
Parameter:
object – element whose presence in this list is to be tested
Returns: It returns true if the specified element is found in the list else it returns false.
Java
// Java program to check// whether element exists// in Java ArrayList import java.io.*;import java.util.ArrayList; class GFG { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(); // use add() method to add elements in the list list.add(1); list.add(2); list.add(3); list.add(4); // passing 5 as as as // parameter to contains() // function if (list.contains(5)) System.out.println("5 exists in the ArrayList"); else System.out.println("5 does not exist in the ArrayList"); if (list.contains(2)) System.out.println("2 exists in the ArrayList"); else System.out.println("2 does not exist in the ArrayList"); }}
5 does not exist in the ArrayList
2 exists in the ArrayList
Method 2: Using indexOf() method
Contains() method uses indexOf() method to determine if a specified element is present in the list or not.
So we can also directly use the indexOf() method to check the existence of any supplied element value.
Java
// Java program to check // whether element exists // in Java ArrayList import java.io.*;import java.util.ArrayList; class GFG { public static void main (String[] args) { ArrayList<Integer> list = new ArrayList<>(); // use add() method to add elements in the list list.add(2); list.add(5); list.add(1); list.add(6); // passing 5 as as as // parameter to contains() // function if(list.indexOf(5)>=0) System.out.println("5 exists in the ArrayList"); else System.out.println("5 does not exist in the ArrayList"); if(list.indexOf(8)>=0) System.out.println("8 exists in the ArrayList"); else System.out.println("8 does not exist in the ArrayList"); }}
5 exists in the ArrayList
8 does not exist in the ArrayList
Java-ArrayList
Java-Collections
Picked
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Dec, 2020"
},
{
"code": null,
"e": 197,
"s": 28,
"text": "Java ArrayList is a resizable array, which can be found in java.util package. We can add or delete elements from an ArrayList whenever we want, unlike a built-in array."
},
{
"code": null,
"e": 270,
"s": 197,
"text": "We can check whether an element exists in ArrayList in java in two ways:"
},
{
"code": null,
"e": 316,
"s": 270,
"text": "Using contains() methodUsing indexOf() method"
},
{
"code": null,
"e": 340,
"s": 316,
"text": "Using contains() method"
},
{
"code": null,
"e": 363,
"s": 340,
"text": "Using indexOf() method"
},
{
"code": null,
"e": 397,
"s": 363,
"text": "Method 1: Using contains() method"
},
{
"code": null,
"e": 518,
"s": 397,
"text": "The contains() method of the java.util.ArrayList class can be used to check whether an element exists in Java ArrayList."
},
{
"code": null,
"e": 526,
"s": 518,
"text": "Syntax:"
},
{
"code": null,
"e": 558,
"s": 526,
"text": "public boolean contains(Object)"
},
{
"code": null,
"e": 569,
"s": 558,
"text": "Parameter:"
},
{
"code": null,
"e": 630,
"s": 569,
"text": "object – element whose presence in this list is to be tested"
},
{
"code": null,
"e": 724,
"s": 630,
"text": "Returns: It returns true if the specified element is found in the list else it returns false."
},
{
"code": null,
"e": 729,
"s": 724,
"text": "Java"
},
{
"code": "// Java program to check// whether element exists// in Java ArrayList import java.io.*;import java.util.ArrayList; class GFG { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(); // use add() method to add elements in the list list.add(1); list.add(2); list.add(3); list.add(4); // passing 5 as as as // parameter to contains() // function if (list.contains(5)) System.out.println(\"5 exists in the ArrayList\"); else System.out.println(\"5 does not exist in the ArrayList\"); if (list.contains(2)) System.out.println(\"2 exists in the ArrayList\"); else System.out.println(\"2 does not exist in the ArrayList\"); }}",
"e": 1536,
"s": 729,
"text": null
},
{
"code": null,
"e": 1596,
"s": 1536,
"text": "5 does not exist in the ArrayList\n2 exists in the ArrayList"
},
{
"code": null,
"e": 1629,
"s": 1596,
"text": "Method 2: Using indexOf() method"
},
{
"code": null,
"e": 1737,
"s": 1629,
"text": "Contains() method uses indexOf() method to determine if a specified element is present in the list or not. "
},
{
"code": null,
"e": 1840,
"s": 1737,
"text": "So we can also directly use the indexOf() method to check the existence of any supplied element value."
},
{
"code": null,
"e": 1845,
"s": 1840,
"text": "Java"
},
{
"code": "// Java program to check // whether element exists // in Java ArrayList import java.io.*;import java.util.ArrayList; class GFG { public static void main (String[] args) { ArrayList<Integer> list = new ArrayList<>(); // use add() method to add elements in the list list.add(2); list.add(5); list.add(1); list.add(6); // passing 5 as as as // parameter to contains() // function if(list.indexOf(5)>=0) System.out.println(\"5 exists in the ArrayList\"); else System.out.println(\"5 does not exist in the ArrayList\"); if(list.indexOf(8)>=0) System.out.println(\"8 exists in the ArrayList\"); else System.out.println(\"8 does not exist in the ArrayList\"); }}",
"e": 2639,
"s": 1845,
"text": null
},
{
"code": null,
"e": 2699,
"s": 2639,
"text": "5 exists in the ArrayList\n8 does not exist in the ArrayList"
},
{
"code": null,
"e": 2714,
"s": 2699,
"text": "Java-ArrayList"
},
{
"code": null,
"e": 2731,
"s": 2714,
"text": "Java-Collections"
},
{
"code": null,
"e": 2738,
"s": 2731,
"text": "Picked"
},
{
"code": null,
"e": 2743,
"s": 2738,
"text": "Java"
},
{
"code": null,
"e": 2748,
"s": 2743,
"text": "Java"
},
{
"code": null,
"e": 2765,
"s": 2748,
"text": "Java-Collections"
}
] |
Weighted Job Scheduling | 23 Mar, 2022
Given N jobs where every job is represented by following three elements of it.
Start TimeFinish TimeProfit or Value Associated (>= 0)
Start Time
Finish Time
Profit or Value Associated (>= 0)
Find the maximum profit subset of jobs such that no two jobs in the subset overlap.
Example:
Input: Number of Jobs n = 4
Job Details {Start Time, Finish Time, Profit}
Job 1: {1, 2, 50}
Job 2: {3, 5, 20}
Job 3: {6, 19, 100}
Job 4: {2, 100, 200}
Output: The maximum profit is 250.
We can get the maximum profit by scheduling jobs 1 and 4.
Note that there is longer schedules possible Jobs 1, 2 and 3
but the profit with this schedule is 20+50+100 which is less than 250.
A simple version of this problem is discussed here where every job has the same profit or value. The Greedy Strategy for activity selection doesn’t work here as a schedule with more jobs may have smaller profit or value.
The above problem can be solved using the following recursive solution.
1) First sort jobs according to finish time.
2) Now apply following recursive process.
// Here arr[] is array of n jobs
findMaximumProfit(arr[], n)
{
a) if (n == 1) return arr[0];
b) Return the maximum of following two profits.
(i) Maximum profit by excluding current job, i.e.,
findMaximumProfit(arr, n-1)
(ii) Maximum profit by including the current job
}
How to find the profit including current job?
The idea is to find the latest job before the current job (in
sorted array) that doesn't conflict with current job 'arr[n-1]'.
Once we find such a job, we recur for all jobs till that job and
add profit of current job to result.
In the above example, "job 1" is the latest non-conflicting
for "job 4" and "job 2" is the latest non-conflicting for "job 3".
The following is the implementation of the above naive recursive method.
C++
Java
Python3
Javascript
// C++ program for weighted job scheduling using Naive Recursive Method#include <iostream>#include <algorithm>using namespace std; // A job has start time, finish time and profit.struct Job{ int start, finish, profit;}; // A utility function that is used for sorting events// according to finish timebool jobComparator(Job s1, Job s2){ return (s1.finish < s2.finish);} // Find the latest job (in sorted array) that doesn't// conflict with the job[i]. If there is no compatible job,// then it returns -1.int latestNonConflict(Job arr[], int i){ for (int j=i-1; j>=0; j--) { if (arr[j].finish <= arr[i-1].start) return j; } return -1;} // A recursive function that returns the maximum possible// profit from given array of jobs. The array of jobs must// be sorted according to finish time.int findMaxProfitRec(Job arr[], int n){ // Base case if (n == 1) return arr[n-1].profit; // Find profit when current job is included int inclProf = arr[n-1].profit; int i = latestNonConflict(arr, n); if (i != -1) inclProf += findMaxProfitRec(arr, i+1); // Find profit when current job is excluded int exclProf = findMaxProfitRec(arr, n-1); return max(inclProf, exclProf);} // The main function that returns the maximum possible// profit from given array of jobsint findMaxProfit(Job arr[], int n){ // Sort jobs according to finish time sort(arr, arr+n, jobComparator); return findMaxProfitRec(arr, n);} // Driver programint main(){ Job arr[] = {{3, 10, 20}, {1, 2, 50}, {6, 19, 100}, {2, 100, 200}}; int n = sizeof(arr)/sizeof(arr[0]); cout << "The optimal profit is " << findMaxProfit(arr, n); return 0;}
// JAVA program for weighted job scheduling using Naive Recursive Methodimport java.util.*;class GFG{ // A job has start time, finish time and profit.static class Job{ int start, finish, profit; Job(int start, int finish, int profit) { this.start = start; this.finish = finish; this.profit = profit; }} // Find the latest job (in sorted array) that doesn't// conflict with the job[i]. If there is no compatible job,// then it returns -1.static int latestNonConflict(Job arr[], int i){ for (int j = i - 1; j >= 0; j--) { if (arr[j].finish <= arr[i - 1].start) return j; } return -1;} // A recursive function that returns the maximum possible// profit from given array of jobs. The array of jobs must// be sorted according to finish time.static int findMaxProfitRec(Job arr[], int n){ // Base case if (n == 1) return arr[n-1].profit; // Find profit when current job is included int inclProf = arr[n-1].profit; int i = latestNonConflict(arr, n); if (i != -1) inclProf += findMaxProfitRec(arr, i+1); // Find profit when current job is excluded int exclProf = findMaxProfitRec(arr, n-1); return Math.max(inclProf, exclProf);} // The main function that returns the maximum possible// profit from given array of jobsstatic int findMaxProfit(Job arr[], int n){ // Sort jobs according to finish time Arrays.sort(arr,new Comparator<Job>(){ public int compare(Job j1,Job j2) { return j1.finish-j2.finish; } }); return findMaxProfitRec(arr, n);} // Driver programpublic static void main(String args[]){ int m = 4; Job arr[] = new Job[m]; arr[0] = new Job(3, 10, 20); arr[1] = new Job(1, 2, 50); arr[2] = new Job(6, 19, 100); arr[3] = new Job(2, 100, 200); int n =arr.length; System.out.println("The optimal profit is " + findMaxProfit(arr, n));}} // This code is contributed by Debojyoti Mandal
# Python3 program for weighted job scheduling using# Naive Recursive Method # Importing the following module to sort array# based on our custom comparison functionfrom functools import cmp_to_key # A job has start time, finish time and profitclass Job: def __init__(self, start, finish, profit): self.start = start self.finish = finish self.profit = profit # A utility function that is used for# sorting events according to finish timedef jobComparator(s1, s2): return s1.finish < s2.finish # Find the latest job (in sorted array) that# doesn't conflict with the job[i]. If there# is no compatible job, then it returns -1def latestNonConflict(arr, i): for j in range(i - 1, -1, -1): if arr[j].finish <= arr[i - 1].start: return j return -1 # A recursive function that returns the# maximum possible profit from given# array of jobs. The array of jobs must# be sorted according to finish timedef findMaxProfitRec(arr, n): # Base case if n == 1: return arr[n - 1].profit # Find profit when current job is included inclProf = arr[n - 1].profit i = latestNonConflict(arr, n) if i != -1: inclProf += findMaxProfitRec(arr, i + 1) # Find profit when current job is excluded exclProf = findMaxProfitRec(arr, n - 1) return max(inclProf, exclProf) # The main function that returns the maximum# possible profit from given array of jobsdef findMaxProfit(arr, n): # Sort jobs according to finish time arr = sorted(arr, key = cmp_to_key(jobComparator)) return findMaxProfitRec(arr, n) # Driver codevalues = [ (3, 10, 20), (1, 2, 50), (6, 19, 100), (2, 100, 200) ]arr = []for i in values: arr.append(Job(i[0], i[1], i[2])) n = len(arr) print("The optimal profit is", findMaxProfit(arr, n)) # This code is code contributed by Kevin Joshi
<script> // JavaScript program for weighted job scheduling using// Naive Recursive Method // A job has start time, finish time and profitclass Job{ constructor(start, finish, profit) { this.start = start this.finish = finish this.profit = profit }} // A utility function that is used for// sorting events according to finish timefunction jobComparator(s1, s2){ return s2.finish - s1.finish;} // Find the latest job (in sorted array) that// doesn't conflict with the job[i]. If there// is no compatible job, then it returns -1function latestNonConflict(arr, i){ for(let j = i - 1; j >= 0; j--) { if(arr[j].finish <= arr[i - 1].start) return j } return -1} // A recursive function that returns the// maximum possible profit from given// array of jobs. The array of jobs must// be sorted according to finish timefunction findMaxProfitRec(arr, n){ // Base case if(n == 1) return arr[n - 1].profit // Find profit when current job is included let inclProf = arr[n - 1].profit let i = latestNonConflict(arr, n) if(i != -1) inclProf += findMaxProfitRec(arr, i + 1) // Find profit when current job is excluded let exclProf = findMaxProfitRec(arr, n - 1) return Math.max(inclProf, exclProf)} // The main function that returns the maximum// possible profit from given array of jobsfunction findMaxProfit(arr, n){ // Sort jobs according to finish time arr.sort(jobComparator) return findMaxProfitRec(arr, n) } // Driver codelet values = [ [3, 10, 20], [1, 2, 50], [6, 19, 100], [2, 100, 200] ]let arr = []for(let i of values) arr.push(new Job(i[0], i[1], i[2])) let n = arr.lengthdocument.write("The optimal profit is ", findMaxProfit(arr, n),"</br>") // This code is code contributed by shinjanpatra </script>
Output:
The optimal profit is 250
The above solution may contain many overlapping subproblems. For example, if lastNonConflicting() always returns the previous job, then findMaxProfitRec(arr, n-1) is called twice and the time complexity becomes O(n*2n). As another example when lastNonConflicting() returns previous to the previous job, there are two recursive calls, for n-2 and n-1. In this example case, recursion becomes the same as Fibonacci Numbers.
So this problem has both properties of Dynamic Programming, Optimal Substructure, and Overlapping Subproblems. Like other Dynamic Programming Problems, we can solve this problem by making a table that stores solutions of subproblems.
Below is an implementation based on Dynamic Programming.
C++
Java
Python3
Javascript
// C++ program for weighted job scheduling using Dynamic// Programming.#include <algorithm>#include <iostream>using namespace std; // A job has start time, finish time and profit.struct Job { int start, finish, profit;}; // A utility function that is used for sorting events// according to finish timebool jobComparator(Job s1, Job s2){ return (s1.finish < s2.finish);} // Find the latest job (in sorted array) that doesn't// conflict with the job[i]int latestNonConflict(Job arr[], int i){ for (int j = i - 1; j >= 0; j--) { if (arr[j].finish <= arr[i].start) return j; } return -1;} // The main function that returns the maximum possible// profit from given array of jobsint findMaxProfit(Job arr[], int n){ // Sort jobs according to finish time sort(arr, arr + n, jobComparator); // Create an array to store solutions of subproblems. // table[i] stores the profit for jobs till arr[i] // (including arr[i]) int* table = new int[n]; table[0] = arr[0].profit; // Fill entries in M[] using recursive property for (int i = 1; i < n; i++) { // Find profit including the current job int inclProf = arr[i].profit; int l = latestNonConflict(arr, i); if (l != -1) inclProf += table[l]; // Store maximum of including and excluding table[i] = max(inclProf, table[i - 1]); } // Store result and free dynamic memory allocated for // table[] int result = table[n - 1]; delete[] table; return result;} // Driver programint main(){ Job arr[] = { { 3, 10, 20 }, { 1, 2, 50 }, { 6, 19, 100 }, { 2, 100, 200 } }; int n = sizeof(arr) / sizeof(arr[0]); cout << "The optimal profit is " << findMaxProfit(arr, n); return 0;}
// JAVA program for weighted job scheduling using Naive// Recursive Methodimport java.util.*;class GFG { // A job has start time, finish time and profit. static class Job { int start, finish, profit; Job(int start, int finish, int profit) { this.start = start; this.finish = finish; this.profit = profit; } } // Find the latest job (in sorted array) that doesn't // conflict with the job[i]. If there is no compatible // job, then it returns -1. static int latestNonConflict(Job arr[], int i) { for (int j = i - 1; j >= 0; j--) { // finish before next is started if (arr[j].finish <= arr[i - 1].start) return j; } return -1; } static int findMaxProfitDP(Job arr[], int n) { // Create an array to store solutions of // subproblems. table[i] stores the profit for jobs // till arr[i] (including arr[i]) int[] table = new int[n]; table[0] = arr[0].profit; // Fill entries in M[] using recursive property for (int i = 1; i < n; i++) { // Find profit including the current job int inclProf = arr[i].profit; int l = latestNonConflict(arr, i); if (l != -1) inclProf += table[l]; // Store maximum of including and excluding table[i] = Math.max(inclProf, table[i - 1]); } // Store result and free dynamic memory allocated // for table[] int result = table[n - 1]; return result; } // The main function that returns the maximum possible // profit from given array of jobs static int findMaxProfit(Job arr[], int n) { // Sort jobs according to finish time Arrays.sort(arr, new Comparator<Job>() { public int compare(Job j1, Job j2) { return j1.finish - j2.finish; } }); return findMaxProfitDP(arr, n); } // Driver program public static void main(String args[]) { int m = 4; Job arr[] = new Job[m]; arr[0] = new Job(3, 10, 20); arr[1] = new Job(1, 2, 50); arr[2] = new Job(6, 19, 100); arr[3] = new Job(2, 100, 200); int n = arr.length; System.out.println("The optimal profit is " + findMaxProfit(arr, n)); }}
# Python3 program for weighted job scheduling# using Dynamic Programming # Importing the following module to sort array# based on our custom comparison functionfrom functools import cmp_to_key # A job has start time, finish time and profit class Job: def __init__(self, start, finish, profit): self.start = start self.finish = finish self.profit = profit # A utility function that is used for sorting# events according to finish time def jobComparator(s1, s2): return s1.finish < s2.finish # Find the latest job (in sorted array) that# doesn't conflict with the job[i]. If there# is no compatible job, then it returns -1 def latestNonConflict(arr, i): for j in range(i - 1, -1, -1): if arr[j].finish <= arr[i - 1].start: return j return -1 # The main function that returns the maximum possible# profit from given array of jobs def findMaxProfit(arr, n): # Sort jobs according to finish time arr = sorted(arr, key=cmp_to_key(jobComparator)) # Create an array to store solutions of subproblems. # table[i] stores the profit for jobs till arr[i] # (including arr[i]) table = [None] * n table[0] = arr[0].profit # Fill entries in M[] using recursive property for i in range(1, n): # Find profit including the current job inclProf = arr[i].profit l = latestNonConflict(arr, i) if l != -1: inclProf += table[l] # Store maximum of including and excluding table[i] = max(inclProf, table[i - 1]) # Store result and free dynamic memory # allocated for table[] result = table[n - 1] return result # Driver codevalues = [(3, 10, 20), (1, 2, 50), (6, 19, 100), (2, 100, 200)]arr = []for i in values: arr.append(Job(i[0], i[1], i[2])) n = len(arr) print("The optimal profit is", findMaxProfit(arr, n)) # This code is contributed by Kevin Joshi
<script> // JavaScript program for weighted job scheduling using// Naive Recursive Method // A job has start time, finish time and profitclass Job{ constructor(start, finish, profit){ this.start = start this.finish = finish this.profit = profit } } // A utility function that is used for// sorting events according to finish timefunction jobComparator(s1, s2){ return s1.finish - s2.finish} // Find the latest job (in sorted array) that// doesn't conflict with the job[i]. If there// is no compatible job, then it returns -1function latestNonConflict(arr, i){ for(let j=i-1;j>=0;j--){ if (arr[j].finish <= arr[i - 1].start) return j } return -1} // The main function that returns the maximum// possible profit from given array of jobsfunction findMaxProfit(arr, n){ // Sort jobs according to finish time arr.sort(jobComparator) // Create an array to store solutions of subproblems. // table[i] stores the profit for jobs till arr[i] // (including arr[i]) let table = new Array(n).fill(null) table[0] = arr[0].profit // Fill entries in M[] using recursive property for(let i=1;i<n;i++){ // Find profit including the current job let inclProf = arr[i].profit let l = latestNonConflict(arr, i) if (l != -1) inclProf += table[l] // Store maximum of including and excluding table[i] = Math.max(inclProf, table[i - 1]) } // Store result and free dynamic memory // allocated for table[] let result = table[n - 1] return result} // Driver codelet values = [ [3, 10, 20], [1, 2, 50], [6, 19, 100], [2, 100, 200] ]let arr = []for(let i of values) arr.push(new Job(i[0], i[1], i[2])) let n = arr.length document.write("The optimal profit is ", findMaxProfit(arr, n),"</br>") // This code is code contributed by shinjanpatra </script>
Output:
The optimal profit is 250
Time Complexity of the above Dynamic Programming Solution is O(n2). Note that the above solution can be optimized to O(nLogn) using Binary Search in latestNonConflict() instead of linear search. Thanks to Garvit for suggesting this optimization. Please refer below post for details.
Weighted Job Scheduling in O(n Log n) time
References: http://courses.cs.washington.edu/courses/cse521/13wi/slides/06dp-sched.pdf
This article is contributed by Shivam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
adrien
rayhuangcj
kevinjoshi46b
jyoti369
arorakashish0911
mrswapnilgupta
shinjanpatra
Dynamic Programming
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Largest Sum Contiguous Subarray
Program for Fibonacci numbers
Find if there is a path between two vertices in an undirected graph
Longest Increasing Subsequence | DP-3
Longest Palindromic Substring | Set 1
Bellman–Ford Algorithm | DP-23
Sieve of Eratosthenes
Find minimum number of coins that make a given value
Minimum number of jumps to reach end
Count number of binary strings without consecutive 1's | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Mar, 2022"
},
{
"code": null,
"e": 133,
"s": 54,
"text": "Given N jobs where every job is represented by following three elements of it."
},
{
"code": null,
"e": 188,
"s": 133,
"text": "Start TimeFinish TimeProfit or Value Associated (>= 0)"
},
{
"code": null,
"e": 199,
"s": 188,
"text": "Start Time"
},
{
"code": null,
"e": 211,
"s": 199,
"text": "Finish Time"
},
{
"code": null,
"e": 245,
"s": 211,
"text": "Profit or Value Associated (>= 0)"
},
{
"code": null,
"e": 330,
"s": 245,
"text": "Find the maximum profit subset of jobs such that no two jobs in the subset overlap. "
},
{
"code": null,
"e": 340,
"s": 330,
"text": "Example: "
},
{
"code": null,
"e": 757,
"s": 340,
"text": "Input: Number of Jobs n = 4\n Job Details {Start Time, Finish Time, Profit}\n Job 1: {1, 2, 50} \n Job 2: {3, 5, 20}\n Job 3: {6, 19, 100}\n Job 4: {2, 100, 200}\nOutput: The maximum profit is 250.\nWe can get the maximum profit by scheduling jobs 1 and 4.\nNote that there is longer schedules possible Jobs 1, 2 and 3 \nbut the profit with this schedule is 20+50+100 which is less than 250."
},
{
"code": null,
"e": 978,
"s": 757,
"text": "A simple version of this problem is discussed here where every job has the same profit or value. The Greedy Strategy for activity selection doesn’t work here as a schedule with more jobs may have smaller profit or value."
},
{
"code": null,
"e": 1052,
"s": 978,
"text": "The above problem can be solved using the following recursive solution. "
},
{
"code": null,
"e": 1882,
"s": 1052,
"text": "1) First sort jobs according to finish time.\n2) Now apply following recursive process. \n // Here arr[] is array of n jobs\n findMaximumProfit(arr[], n)\n {\n a) if (n == 1) return arr[0];\n b) Return the maximum of following two profits.\n (i) Maximum profit by excluding current job, i.e., \n findMaximumProfit(arr, n-1)\n (ii) Maximum profit by including the current job \n }\n\nHow to find the profit including current job?\nThe idea is to find the latest job before the current job (in \nsorted array) that doesn't conflict with current job 'arr[n-1]'. \nOnce we find such a job, we recur for all jobs till that job and\nadd profit of current job to result.\nIn the above example, \"job 1\" is the latest non-conflicting\nfor \"job 4\" and \"job 2\" is the latest non-conflicting for \"job 3\"."
},
{
"code": null,
"e": 1956,
"s": 1882,
"text": "The following is the implementation of the above naive recursive method. "
},
{
"code": null,
"e": 1960,
"s": 1956,
"text": "C++"
},
{
"code": null,
"e": 1965,
"s": 1960,
"text": "Java"
},
{
"code": null,
"e": 1973,
"s": 1965,
"text": "Python3"
},
{
"code": null,
"e": 1984,
"s": 1973,
"text": "Javascript"
},
{
"code": "// C++ program for weighted job scheduling using Naive Recursive Method#include <iostream>#include <algorithm>using namespace std; // A job has start time, finish time and profit.struct Job{ int start, finish, profit;}; // A utility function that is used for sorting events// according to finish timebool jobComparator(Job s1, Job s2){ return (s1.finish < s2.finish);} // Find the latest job (in sorted array) that doesn't// conflict with the job[i]. If there is no compatible job,// then it returns -1.int latestNonConflict(Job arr[], int i){ for (int j=i-1; j>=0; j--) { if (arr[j].finish <= arr[i-1].start) return j; } return -1;} // A recursive function that returns the maximum possible// profit from given array of jobs. The array of jobs must// be sorted according to finish time.int findMaxProfitRec(Job arr[], int n){ // Base case if (n == 1) return arr[n-1].profit; // Find profit when current job is included int inclProf = arr[n-1].profit; int i = latestNonConflict(arr, n); if (i != -1) inclProf += findMaxProfitRec(arr, i+1); // Find profit when current job is excluded int exclProf = findMaxProfitRec(arr, n-1); return max(inclProf, exclProf);} // The main function that returns the maximum possible// profit from given array of jobsint findMaxProfit(Job arr[], int n){ // Sort jobs according to finish time sort(arr, arr+n, jobComparator); return findMaxProfitRec(arr, n);} // Driver programint main(){ Job arr[] = {{3, 10, 20}, {1, 2, 50}, {6, 19, 100}, {2, 100, 200}}; int n = sizeof(arr)/sizeof(arr[0]); cout << \"The optimal profit is \" << findMaxProfit(arr, n); return 0;}",
"e": 3672,
"s": 1984,
"text": null
},
{
"code": "// JAVA program for weighted job scheduling using Naive Recursive Methodimport java.util.*;class GFG{ // A job has start time, finish time and profit.static class Job{ int start, finish, profit; Job(int start, int finish, int profit) { this.start = start; this.finish = finish; this.profit = profit; }} // Find the latest job (in sorted array) that doesn't// conflict with the job[i]. If there is no compatible job,// then it returns -1.static int latestNonConflict(Job arr[], int i){ for (int j = i - 1; j >= 0; j--) { if (arr[j].finish <= arr[i - 1].start) return j; } return -1;} // A recursive function that returns the maximum possible// profit from given array of jobs. The array of jobs must// be sorted according to finish time.static int findMaxProfitRec(Job arr[], int n){ // Base case if (n == 1) return arr[n-1].profit; // Find profit when current job is included int inclProf = arr[n-1].profit; int i = latestNonConflict(arr, n); if (i != -1) inclProf += findMaxProfitRec(arr, i+1); // Find profit when current job is excluded int exclProf = findMaxProfitRec(arr, n-1); return Math.max(inclProf, exclProf);} // The main function that returns the maximum possible// profit from given array of jobsstatic int findMaxProfit(Job arr[], int n){ // Sort jobs according to finish time Arrays.sort(arr,new Comparator<Job>(){ public int compare(Job j1,Job j2) { return j1.finish-j2.finish; } }); return findMaxProfitRec(arr, n);} // Driver programpublic static void main(String args[]){ int m = 4; Job arr[] = new Job[m]; arr[0] = new Job(3, 10, 20); arr[1] = new Job(1, 2, 50); arr[2] = new Job(6, 19, 100); arr[3] = new Job(2, 100, 200); int n =arr.length; System.out.println(\"The optimal profit is \" + findMaxProfit(arr, n));}} // This code is contributed by Debojyoti Mandal",
"e": 5623,
"s": 3672,
"text": null
},
{
"code": "# Python3 program for weighted job scheduling using# Naive Recursive Method # Importing the following module to sort array# based on our custom comparison functionfrom functools import cmp_to_key # A job has start time, finish time and profitclass Job: def __init__(self, start, finish, profit): self.start = start self.finish = finish self.profit = profit # A utility function that is used for# sorting events according to finish timedef jobComparator(s1, s2): return s1.finish < s2.finish # Find the latest job (in sorted array) that# doesn't conflict with the job[i]. If there# is no compatible job, then it returns -1def latestNonConflict(arr, i): for j in range(i - 1, -1, -1): if arr[j].finish <= arr[i - 1].start: return j return -1 # A recursive function that returns the# maximum possible profit from given# array of jobs. The array of jobs must# be sorted according to finish timedef findMaxProfitRec(arr, n): # Base case if n == 1: return arr[n - 1].profit # Find profit when current job is included inclProf = arr[n - 1].profit i = latestNonConflict(arr, n) if i != -1: inclProf += findMaxProfitRec(arr, i + 1) # Find profit when current job is excluded exclProf = findMaxProfitRec(arr, n - 1) return max(inclProf, exclProf) # The main function that returns the maximum# possible profit from given array of jobsdef findMaxProfit(arr, n): # Sort jobs according to finish time arr = sorted(arr, key = cmp_to_key(jobComparator)) return findMaxProfitRec(arr, n) # Driver codevalues = [ (3, 10, 20), (1, 2, 50), (6, 19, 100), (2, 100, 200) ]arr = []for i in values: arr.append(Job(i[0], i[1], i[2])) n = len(arr) print(\"The optimal profit is\", findMaxProfit(arr, n)) # This code is code contributed by Kevin Joshi",
"e": 7516,
"s": 5623,
"text": null
},
{
"code": "<script> // JavaScript program for weighted job scheduling using// Naive Recursive Method // A job has start time, finish time and profitclass Job{ constructor(start, finish, profit) { this.start = start this.finish = finish this.profit = profit }} // A utility function that is used for// sorting events according to finish timefunction jobComparator(s1, s2){ return s2.finish - s1.finish;} // Find the latest job (in sorted array) that// doesn't conflict with the job[i]. If there// is no compatible job, then it returns -1function latestNonConflict(arr, i){ for(let j = i - 1; j >= 0; j--) { if(arr[j].finish <= arr[i - 1].start) return j } return -1} // A recursive function that returns the// maximum possible profit from given// array of jobs. The array of jobs must// be sorted according to finish timefunction findMaxProfitRec(arr, n){ // Base case if(n == 1) return arr[n - 1].profit // Find profit when current job is included let inclProf = arr[n - 1].profit let i = latestNonConflict(arr, n) if(i != -1) inclProf += findMaxProfitRec(arr, i + 1) // Find profit when current job is excluded let exclProf = findMaxProfitRec(arr, n - 1) return Math.max(inclProf, exclProf)} // The main function that returns the maximum// possible profit from given array of jobsfunction findMaxProfit(arr, n){ // Sort jobs according to finish time arr.sort(jobComparator) return findMaxProfitRec(arr, n) } // Driver codelet values = [ [3, 10, 20], [1, 2, 50], [6, 19, 100], [2, 100, 200] ]let arr = []for(let i of values) arr.push(new Job(i[0], i[1], i[2])) let n = arr.lengthdocument.write(\"The optimal profit is \", findMaxProfit(arr, n),\"</br>\") // This code is code contributed by shinjanpatra </script>",
"e": 9379,
"s": 7516,
"text": null
},
{
"code": null,
"e": 9388,
"s": 9379,
"text": "Output: "
},
{
"code": null,
"e": 9414,
"s": 9388,
"text": "The optimal profit is 250"
},
{
"code": null,
"e": 9837,
"s": 9414,
"text": "The above solution may contain many overlapping subproblems. For example, if lastNonConflicting() always returns the previous job, then findMaxProfitRec(arr, n-1) is called twice and the time complexity becomes O(n*2n). As another example when lastNonConflicting() returns previous to the previous job, there are two recursive calls, for n-2 and n-1. In this example case, recursion becomes the same as Fibonacci Numbers. "
},
{
"code": null,
"e": 10071,
"s": 9837,
"text": "So this problem has both properties of Dynamic Programming, Optimal Substructure, and Overlapping Subproblems. Like other Dynamic Programming Problems, we can solve this problem by making a table that stores solutions of subproblems."
},
{
"code": null,
"e": 10129,
"s": 10071,
"text": "Below is an implementation based on Dynamic Programming. "
},
{
"code": null,
"e": 10133,
"s": 10129,
"text": "C++"
},
{
"code": null,
"e": 10138,
"s": 10133,
"text": "Java"
},
{
"code": null,
"e": 10146,
"s": 10138,
"text": "Python3"
},
{
"code": null,
"e": 10157,
"s": 10146,
"text": "Javascript"
},
{
"code": "// C++ program for weighted job scheduling using Dynamic// Programming.#include <algorithm>#include <iostream>using namespace std; // A job has start time, finish time and profit.struct Job { int start, finish, profit;}; // A utility function that is used for sorting events// according to finish timebool jobComparator(Job s1, Job s2){ return (s1.finish < s2.finish);} // Find the latest job (in sorted array) that doesn't// conflict with the job[i]int latestNonConflict(Job arr[], int i){ for (int j = i - 1; j >= 0; j--) { if (arr[j].finish <= arr[i].start) return j; } return -1;} // The main function that returns the maximum possible// profit from given array of jobsint findMaxProfit(Job arr[], int n){ // Sort jobs according to finish time sort(arr, arr + n, jobComparator); // Create an array to store solutions of subproblems. // table[i] stores the profit for jobs till arr[i] // (including arr[i]) int* table = new int[n]; table[0] = arr[0].profit; // Fill entries in M[] using recursive property for (int i = 1; i < n; i++) { // Find profit including the current job int inclProf = arr[i].profit; int l = latestNonConflict(arr, i); if (l != -1) inclProf += table[l]; // Store maximum of including and excluding table[i] = max(inclProf, table[i - 1]); } // Store result and free dynamic memory allocated for // table[] int result = table[n - 1]; delete[] table; return result;} // Driver programint main(){ Job arr[] = { { 3, 10, 20 }, { 1, 2, 50 }, { 6, 19, 100 }, { 2, 100, 200 } }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"The optimal profit is \" << findMaxProfit(arr, n); return 0;}",
"e": 11969,
"s": 10157,
"text": null
},
{
"code": "// JAVA program for weighted job scheduling using Naive// Recursive Methodimport java.util.*;class GFG { // A job has start time, finish time and profit. static class Job { int start, finish, profit; Job(int start, int finish, int profit) { this.start = start; this.finish = finish; this.profit = profit; } } // Find the latest job (in sorted array) that doesn't // conflict with the job[i]. If there is no compatible // job, then it returns -1. static int latestNonConflict(Job arr[], int i) { for (int j = i - 1; j >= 0; j--) { // finish before next is started if (arr[j].finish <= arr[i - 1].start) return j; } return -1; } static int findMaxProfitDP(Job arr[], int n) { // Create an array to store solutions of // subproblems. table[i] stores the profit for jobs // till arr[i] (including arr[i]) int[] table = new int[n]; table[0] = arr[0].profit; // Fill entries in M[] using recursive property for (int i = 1; i < n; i++) { // Find profit including the current job int inclProf = arr[i].profit; int l = latestNonConflict(arr, i); if (l != -1) inclProf += table[l]; // Store maximum of including and excluding table[i] = Math.max(inclProf, table[i - 1]); } // Store result and free dynamic memory allocated // for table[] int result = table[n - 1]; return result; } // The main function that returns the maximum possible // profit from given array of jobs static int findMaxProfit(Job arr[], int n) { // Sort jobs according to finish time Arrays.sort(arr, new Comparator<Job>() { public int compare(Job j1, Job j2) { return j1.finish - j2.finish; } }); return findMaxProfitDP(arr, n); } // Driver program public static void main(String args[]) { int m = 4; Job arr[] = new Job[m]; arr[0] = new Job(3, 10, 20); arr[1] = new Job(1, 2, 50); arr[2] = new Job(6, 19, 100); arr[3] = new Job(2, 100, 200); int n = arr.length; System.out.println(\"The optimal profit is \" + findMaxProfit(arr, n)); }}",
"e": 14384,
"s": 11969,
"text": null
},
{
"code": "# Python3 program for weighted job scheduling# using Dynamic Programming # Importing the following module to sort array# based on our custom comparison functionfrom functools import cmp_to_key # A job has start time, finish time and profit class Job: def __init__(self, start, finish, profit): self.start = start self.finish = finish self.profit = profit # A utility function that is used for sorting# events according to finish time def jobComparator(s1, s2): return s1.finish < s2.finish # Find the latest job (in sorted array) that# doesn't conflict with the job[i]. If there# is no compatible job, then it returns -1 def latestNonConflict(arr, i): for j in range(i - 1, -1, -1): if arr[j].finish <= arr[i - 1].start: return j return -1 # The main function that returns the maximum possible# profit from given array of jobs def findMaxProfit(arr, n): # Sort jobs according to finish time arr = sorted(arr, key=cmp_to_key(jobComparator)) # Create an array to store solutions of subproblems. # table[i] stores the profit for jobs till arr[i] # (including arr[i]) table = [None] * n table[0] = arr[0].profit # Fill entries in M[] using recursive property for i in range(1, n): # Find profit including the current job inclProf = arr[i].profit l = latestNonConflict(arr, i) if l != -1: inclProf += table[l] # Store maximum of including and excluding table[i] = max(inclProf, table[i - 1]) # Store result and free dynamic memory # allocated for table[] result = table[n - 1] return result # Driver codevalues = [(3, 10, 20), (1, 2, 50), (6, 19, 100), (2, 100, 200)]arr = []for i in values: arr.append(Job(i[0], i[1], i[2])) n = len(arr) print(\"The optimal profit is\", findMaxProfit(arr, n)) # This code is contributed by Kevin Joshi",
"e": 16287,
"s": 14384,
"text": null
},
{
"code": "<script> // JavaScript program for weighted job scheduling using// Naive Recursive Method // A job has start time, finish time and profitclass Job{ constructor(start, finish, profit){ this.start = start this.finish = finish this.profit = profit } } // A utility function that is used for// sorting events according to finish timefunction jobComparator(s1, s2){ return s1.finish - s2.finish} // Find the latest job (in sorted array) that// doesn't conflict with the job[i]. If there// is no compatible job, then it returns -1function latestNonConflict(arr, i){ for(let j=i-1;j>=0;j--){ if (arr[j].finish <= arr[i - 1].start) return j } return -1} // The main function that returns the maximum// possible profit from given array of jobsfunction findMaxProfit(arr, n){ // Sort jobs according to finish time arr.sort(jobComparator) // Create an array to store solutions of subproblems. // table[i] stores the profit for jobs till arr[i] // (including arr[i]) let table = new Array(n).fill(null) table[0] = arr[0].profit // Fill entries in M[] using recursive property for(let i=1;i<n;i++){ // Find profit including the current job let inclProf = arr[i].profit let l = latestNonConflict(arr, i) if (l != -1) inclProf += table[l] // Store maximum of including and excluding table[i] = Math.max(inclProf, table[i - 1]) } // Store result and free dynamic memory // allocated for table[] let result = table[n - 1] return result} // Driver codelet values = [ [3, 10, 20], [1, 2, 50], [6, 19, 100], [2, 100, 200] ]let arr = []for(let i of values) arr.push(new Job(i[0], i[1], i[2])) let n = arr.length document.write(\"The optimal profit is \", findMaxProfit(arr, n),\"</br>\") // This code is code contributed by shinjanpatra </script>",
"e": 18223,
"s": 16287,
"text": null
},
{
"code": null,
"e": 18232,
"s": 18223,
"text": "Output: "
},
{
"code": null,
"e": 18258,
"s": 18232,
"text": "The optimal profit is 250"
},
{
"code": null,
"e": 18541,
"s": 18258,
"text": "Time Complexity of the above Dynamic Programming Solution is O(n2). Note that the above solution can be optimized to O(nLogn) using Binary Search in latestNonConflict() instead of linear search. Thanks to Garvit for suggesting this optimization. Please refer below post for details."
},
{
"code": null,
"e": 18584,
"s": 18541,
"text": "Weighted Job Scheduling in O(n Log n) time"
},
{
"code": null,
"e": 18671,
"s": 18584,
"text": "References: http://courses.cs.washington.edu/courses/cse521/13wi/slides/06dp-sched.pdf"
},
{
"code": null,
"e": 18835,
"s": 18671,
"text": "This article is contributed by Shivam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 18842,
"s": 18835,
"text": "adrien"
},
{
"code": null,
"e": 18853,
"s": 18842,
"text": "rayhuangcj"
},
{
"code": null,
"e": 18867,
"s": 18853,
"text": "kevinjoshi46b"
},
{
"code": null,
"e": 18876,
"s": 18867,
"text": "jyoti369"
},
{
"code": null,
"e": 18893,
"s": 18876,
"text": "arorakashish0911"
},
{
"code": null,
"e": 18908,
"s": 18893,
"text": "mrswapnilgupta"
},
{
"code": null,
"e": 18921,
"s": 18908,
"text": "shinjanpatra"
},
{
"code": null,
"e": 18941,
"s": 18921,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 18961,
"s": 18941,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 19059,
"s": 18961,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 19091,
"s": 19059,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 19121,
"s": 19091,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 19189,
"s": 19121,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 19227,
"s": 19189,
"text": "Longest Increasing Subsequence | DP-3"
},
{
"code": null,
"e": 19265,
"s": 19227,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 19296,
"s": 19265,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 19318,
"s": 19296,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 19371,
"s": 19318,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 19408,
"s": 19371,
"text": "Minimum number of jumps to reach end"
}
] |
Java Program to Find Sum of Array Elements | 13 Jun, 2022
Given an array of integers. Write a Java Program to find the sum of the elements of the array.
Examples:
Input : arr[] = {1, 2, 3}
Output : 6
1 + 2 + 3 = 6
Input : arr[] = {15, 12, 13, 10}
Output : 50
15 + 12 + 13 + 10 = 50
An array is a data structure that contains a group of elements. Typically these elements are all of the same data type, such as an integer or string. Arrays are commonly used in computer programs to organize data so that a related set of values can be quickly sorted or searched. All the items of the array are stored at contiguous memory locations.
Array Elements: Each item of an array is an Element. All the elements in an array must be of the same type.
Initialize an array arr and a variable sum.Set the value of sum=0. Start a for loop from index 0 to the length of the array – 1.In every iteration, perform sum = sum + arr[i].After the termination of the loop, print the value of the sum.
Initialize an array arr and a variable sum.
Set the value of sum=0.
Start a for loop from index 0 to the length of the array – 1.
In every iteration, perform sum = sum + arr[i].
After the termination of the loop, print the value of the sum.
Java
// Java Program to find sum of elements in a given arrayclass Test { static int arr[] = { 12, 3, 4, 15 }; // method for sum of elements in an array static int sum() { int sum = 0; // initialize sum int i; // Iterate through all elements and add them to sum for (i = 0; i < arr.length; i++) sum += arr[i]; return sum; } // Driver method public static void main(String[] args) { System.out.println("Sum of given array is " + sum()); }}
Sum of given array is 34
Time Complexity: O(n)
Auxiliary Space: O(1)
nishkarshgandhi
chandramauliguptach
Java-Array-Programs
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 147,
"s": 52,
"text": "Given an array of integers. Write a Java Program to find the sum of the elements of the array."
},
{
"code": null,
"e": 157,
"s": 147,
"text": "Examples:"
},
{
"code": null,
"e": 277,
"s": 157,
"text": "Input : arr[] = {1, 2, 3}\nOutput : 6\n1 + 2 + 3 = 6\n\nInput : arr[] = {15, 12, 13, 10}\nOutput : 50\n15 + 12 + 13 + 10 = 50"
},
{
"code": null,
"e": 628,
"s": 277,
"text": "An array is a data structure that contains a group of elements. Typically these elements are all of the same data type, such as an integer or string. Arrays are commonly used in computer programs to organize data so that a related set of values can be quickly sorted or searched. All the items of the array are stored at contiguous memory locations. "
},
{
"code": null,
"e": 736,
"s": 628,
"text": "Array Elements: Each item of an array is an Element. All the elements in an array must be of the same type."
},
{
"code": null,
"e": 974,
"s": 736,
"text": "Initialize an array arr and a variable sum.Set the value of sum=0. Start a for loop from index 0 to the length of the array – 1.In every iteration, perform sum = sum + arr[i].After the termination of the loop, print the value of the sum."
},
{
"code": null,
"e": 1018,
"s": 974,
"text": "Initialize an array arr and a variable sum."
},
{
"code": null,
"e": 1042,
"s": 1018,
"text": "Set the value of sum=0."
},
{
"code": null,
"e": 1105,
"s": 1042,
"text": " Start a for loop from index 0 to the length of the array – 1."
},
{
"code": null,
"e": 1153,
"s": 1105,
"text": "In every iteration, perform sum = sum + arr[i]."
},
{
"code": null,
"e": 1216,
"s": 1153,
"text": "After the termination of the loop, print the value of the sum."
},
{
"code": null,
"e": 1221,
"s": 1216,
"text": "Java"
},
{
"code": "// Java Program to find sum of elements in a given arrayclass Test { static int arr[] = { 12, 3, 4, 15 }; // method for sum of elements in an array static int sum() { int sum = 0; // initialize sum int i; // Iterate through all elements and add them to sum for (i = 0; i < arr.length; i++) sum += arr[i]; return sum; } // Driver method public static void main(String[] args) { System.out.println(\"Sum of given array is \" + sum()); }}",
"e": 1765,
"s": 1221,
"text": null
},
{
"code": null,
"e": 1790,
"s": 1765,
"text": "Sum of given array is 34"
},
{
"code": null,
"e": 1812,
"s": 1790,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 1834,
"s": 1812,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1850,
"s": 1834,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 1870,
"s": 1850,
"text": "chandramauliguptach"
},
{
"code": null,
"e": 1890,
"s": 1870,
"text": "Java-Array-Programs"
},
{
"code": null,
"e": 1895,
"s": 1890,
"text": "Java"
},
{
"code": null,
"e": 1909,
"s": 1895,
"text": "Java Programs"
},
{
"code": null,
"e": 1914,
"s": 1909,
"text": "Java"
}
] |
GATE | GATE CS 2008 | Question 66 | 05 Apr, 2019
A process executes the following code
for (i = 0; i < n; i++) fork();
The total number of child processes created is(A) n(B) 2n - 1(C) 2n(D) 2(n+1) - 1Answer: (B)Explanation:
F0 // There will be 1 child process created by first fork
/ \
F1 F1 // There will be 2 child processes created by second fork
/ \ / \
F2 F2 F2 F2 // There will be 4 child processes created by third fork
/ \ / \ / \ / \
............... // and so on
If we sum all levels of above tree for i = 0 to n-1, we get 2n - 1. So there will be 2n – 1 child processes. On the other hand, the total number of process created are (number of child processes)+1.
Note:The maximum number of process is 2n and may vary due to fork failures.Also see this post for more details.
Quiz of this Question
kalpaj_12
GATE-CS-2008
GATE-GATE CS 2008
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n05 Apr, 2019"
},
{
"code": null,
"e": 91,
"s": 53,
"text": "A process executes the following code"
},
{
"code": null,
"e": 123,
"s": 91,
"text": "for (i = 0; i < n; i++) fork();"
},
{
"code": null,
"e": 228,
"s": 123,
"text": "The total number of child processes created is(A) n(B) 2n - 1(C) 2n(D) 2(n+1) - 1Answer: (B)Explanation:"
},
{
"code": null,
"e": 534,
"s": 228,
"text": " F0 // There will be 1 child process created by first fork\n / \\\n F1 F1 // There will be 2 child processes created by second fork\n / \\ / \\\n F2 F2 F2 F2 // There will be 4 child processes created by third fork\n/ \\ / \\ / \\ / \\\n ............... // and so on"
},
{
"code": null,
"e": 733,
"s": 534,
"text": "If we sum all levels of above tree for i = 0 to n-1, we get 2n - 1. So there will be 2n – 1 child processes. On the other hand, the total number of process created are (number of child processes)+1."
},
{
"code": null,
"e": 845,
"s": 733,
"text": "Note:The maximum number of process is 2n and may vary due to fork failures.Also see this post for more details."
},
{
"code": null,
"e": 867,
"s": 845,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 877,
"s": 867,
"text": "kalpaj_12"
},
{
"code": null,
"e": 890,
"s": 877,
"text": "GATE-CS-2008"
},
{
"code": null,
"e": 908,
"s": 890,
"text": "GATE-GATE CS 2008"
},
{
"code": null,
"e": 913,
"s": 908,
"text": "GATE"
}
] |
IntStream rangeClosed() in Java | 06 Dec, 2018
IntStream rangeClosed(int startInclusive, int endInclusive) returns an IntStream from startInclusive (inclusive) to endInclusive (inclusive) by an incremental step of 1.
Syntax :
static IntStream rangeClosed(int startInclusive, int endInclusive)
Parameters :
IntStream : A sequence of primitive int-valued elements.startInclusive : The inclusive initial value.endInclusive : The inclusive upper bound.
IntStream : A sequence of primitive int-valued elements.
startInclusive : The inclusive initial value.
endInclusive : The inclusive upper bound.
Return Value : A sequential IntStream for the range of int elements.
Example :
// Implementation of IntStream rangeClosed// (int startInclusive, int endInclusive)import java.util.*;import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream IntStream stream = IntStream.rangeClosed(-4, 3); // Displaying the elements in range // including the lower and upper bound stream.forEach(System.out::println); }}
-4
-3
-2
-1
0
1
2
3
Note : IntStream rangeClosed(int startInclusive, int endInclusive) basically works like a for loop. An equivalent sequence of increasing values can be produced sequentially as :
for (int i = startInclusive; i <= endInclusive ; i++)
{
...
...
...
}
Java - util package
Java-Functions
java-intstream
java-stream
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Dec, 2018"
},
{
"code": null,
"e": 198,
"s": 28,
"text": "IntStream rangeClosed(int startInclusive, int endInclusive) returns an IntStream from startInclusive (inclusive) to endInclusive (inclusive) by an incremental step of 1."
},
{
"code": null,
"e": 207,
"s": 198,
"text": "Syntax :"
},
{
"code": null,
"e": 277,
"s": 207,
"text": "static IntStream rangeClosed(int startInclusive, int endInclusive)\n"
},
{
"code": null,
"e": 290,
"s": 277,
"text": "Parameters :"
},
{
"code": null,
"e": 433,
"s": 290,
"text": "IntStream : A sequence of primitive int-valued elements.startInclusive : The inclusive initial value.endInclusive : The inclusive upper bound."
},
{
"code": null,
"e": 490,
"s": 433,
"text": "IntStream : A sequence of primitive int-valued elements."
},
{
"code": null,
"e": 536,
"s": 490,
"text": "startInclusive : The inclusive initial value."
},
{
"code": null,
"e": 578,
"s": 536,
"text": "endInclusive : The inclusive upper bound."
},
{
"code": null,
"e": 647,
"s": 578,
"text": "Return Value : A sequential IntStream for the range of int elements."
},
{
"code": null,
"e": 657,
"s": 647,
"text": "Example :"
},
{
"code": "// Implementation of IntStream rangeClosed// (int startInclusive, int endInclusive)import java.util.*;import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream IntStream stream = IntStream.rangeClosed(-4, 3); // Displaying the elements in range // including the lower and upper bound stream.forEach(System.out::println); }}",
"e": 1103,
"s": 657,
"text": null
},
{
"code": null,
"e": 1124,
"s": 1103,
"text": "-4\n-3\n-2\n-1\n0\n1\n2\n3\n"
},
{
"code": null,
"e": 1302,
"s": 1124,
"text": "Note : IntStream rangeClosed(int startInclusive, int endInclusive) basically works like a for loop. An equivalent sequence of increasing values can be produced sequentially as :"
},
{
"code": null,
"e": 1377,
"s": 1302,
"text": "for (int i = startInclusive; i <= endInclusive ; i++) \n{\n ...\n ...\n ...\n}\n"
},
{
"code": null,
"e": 1397,
"s": 1377,
"text": "Java - util package"
},
{
"code": null,
"e": 1412,
"s": 1397,
"text": "Java-Functions"
},
{
"code": null,
"e": 1427,
"s": 1412,
"text": "java-intstream"
},
{
"code": null,
"e": 1439,
"s": 1427,
"text": "java-stream"
},
{
"code": null,
"e": 1444,
"s": 1439,
"text": "Java"
},
{
"code": null,
"e": 1449,
"s": 1444,
"text": "Java"
}
] |
Subsets and Splits