title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Dice Roll Simulation in C++
Suppose a die simulator generates a random number from 1 to 6 for each roll. We want to introduced a constraint to the generator such that it cannot roll the number i more than rollMax[i] (1-indexed) consecutive times. Consider we have an array of integers rollMax and an integer n, we have to return the number of distinct sequences that can be obtained with exact n rolls. The two sequences are considered different if at least one element differs from each other. So if n is 2, then rollMax = [1,1,2,2,2,3], then the output will be 34. So there will be 2 rolls on die, if there is no constraints, on the die there are 6*6 = 36 possible combinations, in this case the numbers 1 and 2 appears at most once consecutively, so sequences (1,1) and (2,2) cannot occur. so the final answer will be 36 – 2 = 34. To solve this, we will follow these steps βˆ’ create one method called dfs(), this will take dieLeft, last, currLen, array r and matrix dp if dieLeft = 0, then return 1 if dp[dieLeft][last][currLen] is not -1, then return dp[dieLeft, last, currLen] counter := 0 for i in range 0 to 6if i = last and r[i] = currLen, then skip the next part and go for next iterationcounter := dfs(dieLeft – 1, i, currLen + 1 when i = last, otherwise 1, r, dp) if i = last and r[i] = currLen, then skip the next part and go for next iteration counter := dfs(dieLeft – 1, i, currLen + 1 when i = last, otherwise 1, r, dp) dp[dieLeft, last, currLen] := counter return dp[dieLeft, last, currLeft] the main method will be like βˆ’ create one 3D array called dp of order (n + 1) x 6 x 16, and fill this with -1 return dfs(n, 0, 0, rollMax, dp) Let us see the following implementation to get better understanding βˆ’ Live Demo #include <bits/stdc++.h> using namespace std; const int mod = 1e9+7; class Solution { public: int dfs(int dieLeft, int last, int currLen, vector <int> &r,vector < vector < vector <int> > > &dp){ if(dieLeft == 0){ return 1; } if(dp[dieLeft][last][currLen]!=-1)return dp[dieLeft][last][currLen]; int counter = 0; for(int i =0;i<6;i++){ if(i==last && r[i] == currLen)continue; counter = (counter%mod + (dfs(dieLeft-1,i,i==last?currLen+1:1,r,dp))%mod)%mod; } dp[dieLeft][last][currLen] = counter%mod; return dp[dieLeft][last][currLen]%mod; } int dieSimulator(int n, vector<int>& rollMax) { vector < vector < vector <int> > > dp(n+1, vector < vector <int> > (6, vector <int>(16, -1))); return dfs(n,0,0,rollMax, dp)%mod; } }; main(){ vector<int> v = {1,1,2,2,2,3}; Solution ob; cout << (ob.dieSimulator(2,v)); } 2 [1,1,2,2,2,3] 34
[ { "code": null, "e": 1868, "s": 1062, "text": "Suppose a die simulator generates a random number from 1 to 6 for each roll. We want to introduced a constraint to the generator such that it cannot roll the number i more than rollMax[i] (1-indexed) consecutive times. Consider we have an array of integers rollMax and an integer n, we have to return the number of distinct sequences that can be obtained with exact n rolls. The two sequences are considered different if at least one element differs from each other. So if n is 2, then rollMax = [1,1,2,2,2,3], then the output will be 34. So there will be 2 rolls on die, if there is no constraints, on the die there are 6*6 = 36 possible combinations, in this case the numbers 1 and 2 appears at most once consecutively, so sequences (1,1) and (2,2) cannot occur. so the final answer will be 36 – 2 = 34." }, { "code": null, "e": 1912, "s": 1868, "text": "To solve this, we will follow these steps βˆ’" }, { "code": null, "e": 2005, "s": 1912, "text": "create one method called dfs(), this will take dieLeft, last, currLen, array r and matrix dp" }, { "code": null, "e": 2035, "s": 2005, "text": "if dieLeft = 0, then return 1" }, { "code": null, "e": 2115, "s": 2035, "text": "if dp[dieLeft][last][currLen] is not -1, then return dp[dieLeft, last, currLen]" }, { "code": null, "e": 2128, "s": 2115, "text": "counter := 0" }, { "code": null, "e": 2308, "s": 2128, "text": "for i in range 0 to 6if i = last and r[i] = currLen, then skip the next part and go for next iterationcounter := dfs(dieLeft – 1, i, currLen + 1 when i = last, otherwise 1, r, dp)" }, { "code": null, "e": 2390, "s": 2308, "text": "if i = last and r[i] = currLen, then skip the next part and go for next iteration" }, { "code": null, "e": 2468, "s": 2390, "text": "counter := dfs(dieLeft – 1, i, currLen + 1 when i = last, otherwise 1, r, dp)" }, { "code": null, "e": 2506, "s": 2468, "text": "dp[dieLeft, last, currLen] := counter" }, { "code": null, "e": 2541, "s": 2506, "text": "return dp[dieLeft, last, currLeft]" }, { "code": null, "e": 2572, "s": 2541, "text": "the main method will be like βˆ’" }, { "code": null, "e": 2651, "s": 2572, "text": "create one 3D array called dp of order (n + 1) x 6 x 16, and fill this with -1" }, { "code": null, "e": 2684, "s": 2651, "text": "return dfs(n, 0, 0, rollMax, dp)" }, { "code": null, "e": 2754, "s": 2684, "text": "Let us see the following implementation to get better understanding βˆ’" }, { "code": null, "e": 2765, "s": 2754, "text": " Live Demo" }, { "code": null, "e": 3683, "s": 2765, "text": "#include <bits/stdc++.h>\nusing namespace std;\nconst int mod = 1e9+7;\nclass Solution {\n public:\n int dfs(int dieLeft, int last, int currLen, vector <int> &r,vector < vector < vector <int> > > &dp){\n if(dieLeft == 0){\n return 1;\n }\n if(dp[dieLeft][last][currLen]!=-1)return dp[dieLeft][last][currLen];\n int counter = 0;\n for(int i =0;i<6;i++){\n if(i==last && r[i] == currLen)continue;\n counter = (counter%mod + (dfs(dieLeft-1,i,i==last?currLen+1:1,r,dp))%mod)%mod;\n }\n dp[dieLeft][last][currLen] = counter%mod;\n return dp[dieLeft][last][currLen]%mod;\n }\n int dieSimulator(int n, vector<int>& rollMax) {\n vector < vector < vector <int> > > dp(n+1, vector < vector <int> > (6, vector <int>(16, -1)));\n return dfs(n,0,0,rollMax, dp)%mod;\n }\n};\nmain(){\n vector<int> v = {1,1,2,2,2,3};\n Solution ob;\n cout << (ob.dieSimulator(2,v));\n}" }, { "code": null, "e": 3699, "s": 3683, "text": "2\n[1,1,2,2,2,3]" }, { "code": null, "e": 3702, "s": 3699, "text": "34" } ]
Exception handling and object destruction | Set 1 - GeeksforGeeks
24 Jan, 2022 Predict the output of following C++ program. CPP #include <iostream>using namespace std; class Test {public: Test() { cout << "Constructing an object of Test " << endl; } ~Test() { cout << "Destructing an object of Test " << endl; }}; int main() { try { Test t1; throw 10; } catch(int i) { cout << "Caught " << i << endl; }} Output: Constructing an object of Test Destructing an object of Test Caught 10 When an exception is thrown, destructors of the objects (whose scope ends with the try block) is automatically called before the catch block gets executed. That is why the above program prints β€œDestructing an object of Test” before β€œCaught 10”.What happens when an exception is thrown from a constructor? Consider the following program. CPP #include <iostream>using namespace std; class Test1 {public: Test1() { cout << "Constructing an Object of Test1" << endl; } ~Test1() { cout << "Destructing an Object of Test1" << endl; }}; class Test2 {public: // Following constructor throws an integer exception Test2() { cout << "Constructing an Object of Test2" << endl; throw 20; } ~Test2() { cout << "Destructing an Object of Test2" << endl; }}; int main() { try { Test1 t1; // Constructed and destructed Test2 t2; // Partially constructed Test1 t3; // t3 is not constructed as this statement never gets executed } catch(int i) { cout << "Caught " << i << endl; }} Output: Constructing an Object of Test1 Constructing an Object of Test2 Destructing an Object of Test1 Caught 20 Destructors are only called for the completely constructed objects. When constructor of an object throws an exception, destructor for that object is not called. As an exercise, predict the output of following program. CPP #include <iostream>using namespace std; class Test { static int count; int id;public: Test() { count++; id = count; cout << "Constructing object number " << id << endl; if(id == 4) throw 4; } ~Test() { cout << "Destructing object number " << id << endl; }}; int Test::count = 0; int main() { try { Test array[5]; } catch(int i) { cout << "Caught " << i << endl; }} We will be covering more of this topic in a separate post. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. simmytarika5 sumitgumber28 C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments std::sort() in C++ STL rand() and srand() in C/C++ Enumeration (or enum) in C fgets() and gets() in C language How to dynamically allocate a 2D array in C? Vector in C++ STL Initialize a vector in C++ (6 different ways) Virtual Function in C++ Iterators in C++ STL getline (string) in C++
[ { "code": null, "e": 26569, "s": 26541, "text": "\n24 Jan, 2022" }, { "code": null, "e": 26615, "s": 26569, "text": "Predict the output of following C++ program. " }, { "code": null, "e": 26619, "s": 26615, "text": "CPP" }, { "code": "#include <iostream>using namespace std; class Test {public: Test() { cout << \"Constructing an object of Test \" << endl; } ~Test() { cout << \"Destructing an object of Test \" << endl; }}; int main() { try { Test t1; throw 10; } catch(int i) { cout << \"Caught \" << i << endl; }}", "e": 26910, "s": 26619, "text": null }, { "code": null, "e": 26920, "s": 26910, "text": "Output: " }, { "code": null, "e": 26997, "s": 26920, "text": " Constructing an object of Test\n Destructing an object of Test\n Caught 10" }, { "code": null, "e": 27336, "s": 26997, "text": "When an exception is thrown, destructors of the objects (whose scope ends with the try block) is automatically called before the catch block gets executed. That is why the above program prints β€œDestructing an object of Test” before β€œCaught 10”.What happens when an exception is thrown from a constructor? Consider the following program. " }, { "code": null, "e": 27340, "s": 27336, "text": "CPP" }, { "code": "#include <iostream>using namespace std; class Test1 {public: Test1() { cout << \"Constructing an Object of Test1\" << endl; } ~Test1() { cout << \"Destructing an Object of Test1\" << endl; }}; class Test2 {public: // Following constructor throws an integer exception Test2() { cout << \"Constructing an Object of Test2\" << endl; throw 20; } ~Test2() { cout << \"Destructing an Object of Test2\" << endl; }}; int main() { try { Test1 t1; // Constructed and destructed Test2 t2; // Partially constructed Test1 t3; // t3 is not constructed as this statement never gets executed } catch(int i) { cout << \"Caught \" << i << endl; }}", "e": 27994, "s": 27340, "text": null }, { "code": null, "e": 28004, "s": 27994, "text": "Output: " }, { "code": null, "e": 28117, "s": 28004, "text": " Constructing an Object of Test1\n Constructing an Object of Test2\n Destructing an Object of Test1\n Caught 20" }, { "code": null, "e": 28336, "s": 28117, "text": "Destructors are only called for the completely constructed objects. When constructor of an object throws an exception, destructor for that object is not called. As an exercise, predict the output of following program. " }, { "code": null, "e": 28340, "s": 28336, "text": "CPP" }, { "code": "#include <iostream>using namespace std; class Test { static int count; int id;public: Test() { count++; id = count; cout << \"Constructing object number \" << id << endl; if(id == 4) throw 4; } ~Test() { cout << \"Destructing object number \" << id << endl; }}; int Test::count = 0; int main() { try { Test array[5]; } catch(int i) { cout << \"Caught \" << i << endl; }}", "e": 28737, "s": 28340, "text": null }, { "code": null, "e": 28922, "s": 28737, "text": "We will be covering more of this topic in a separate post. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 28935, "s": 28922, "text": "simmytarika5" }, { "code": null, "e": 28949, "s": 28935, "text": "sumitgumber28" }, { "code": null, "e": 28960, "s": 28949, "text": "C Language" }, { "code": null, "e": 28964, "s": 28960, "text": "C++" }, { "code": null, "e": 28968, "s": 28964, "text": "CPP" }, { "code": null, "e": 29066, "s": 28968, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29075, "s": 29066, "text": "Comments" }, { "code": null, "e": 29088, "s": 29075, "text": "Old Comments" }, { "code": null, "e": 29111, "s": 29088, "text": "std::sort() in C++ STL" }, { "code": null, "e": 29139, "s": 29111, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 29166, "s": 29139, "text": "Enumeration (or enum) in C" }, { "code": null, "e": 29199, "s": 29166, "text": "fgets() and gets() in C language" }, { "code": null, "e": 29244, "s": 29199, "text": "How to dynamically allocate a 2D array in C?" }, { "code": null, "e": 29262, "s": 29244, "text": "Vector in C++ STL" }, { "code": null, "e": 29308, "s": 29262, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 29332, "s": 29308, "text": "Virtual Function in C++" }, { "code": null, "e": 29353, "s": 29332, "text": "Iterators in C++ STL" } ]
How to Upload Your Python Package to PyPI and pip | Towards Data Science
You wrote a new Python package that solves a specific problem and it’s now time to share it with the wider Python community. To do so, you need to upload the package to a central repository that can be accessed by developers across the globe. In today’s article we are going to discuss how PyPI lets developers share packages with other people who may wish to use that particular functionality in their own application. Additionally, we are going to introduce a step-by-step guide to help you upload your Python package on PyPi so that it is available to every Python user. I’ll use a real end-to-end example so that all the steps are crystal clear. The Python Package Index, abbreviated as PyPI, is the official repository of software for the Python programming language. By default, pip β€” which is the most popular Python package manager β€” uses PyPI as the source for retrieving package dependencies. PyPI lets you find, install and even publish your Python packages so that they are widely available to the public. More than 300,000 different packages are currently published in the index with more than 2,500,000 releases being distributed to users. In the following section we’ll explore the steps you need to follow in order to publish your Python package on PyPI and make it available on pip. If you are using Python 2 β‰₯ 2.7.9 or Python 3 β‰₯ 3.4 pip should be already installed. But if for any reason you may need to install it simply run the commands below (instructions are suitable for Unix): curl https://bootstrap.pypa.io/get-pip.py -o get-pip.pypython get-pip.py And that’s it! You can ensure that pip is now installed as below. $ python -m pip --versionpip X.Y.Z from .../site-packages/pip (python X.Y) I created a sample project on GitHub so that it’s easier to demonstrate how to publish your own packages on PyPI. The project can be found on this link β€” normally you’ll need to create at least the files below: README.rst: It is highly recommended to include a README file where you should outline the basic functionality offered by your package. Additionally, you may also include installation instructions or usage guide. LICENSE.txt: It’s always best to include a license in the package you intend to make it widely available. For more options and details refer to the Licensing a repository section of GitHub docs. setup.py: This file should be placed into the top-level directory of your project structure. In this file you can specify configurations for your Python project. For more details you can refer to the official documentation. The setup.py file for our example project can be found on GitHub and is identical to the one shown below. setup.cfg: This file contains default options for setup.py commands. The overall structure of our example project is shown below .β”œβ”€β”€ LICENSE.txtβ”œβ”€β”€ README.rstβ”œβ”€β”€ setup.cfgβ”œβ”€β”€ setup.pyβ”œβ”€β”€ srcβ”‚ β”œβ”€β”€ example_publish_pypi_mediumβ”‚ β”‚ β”œβ”€β”€ __init__.pyβ”‚ β”‚ └── exampleβ”‚ β”‚ β”œβ”€β”€ __init__.pyβ”‚ β”‚ └── custom_sklearn.pyβ”œβ”€β”€ testsβ”‚ β”œβ”€β”€ __init__.pyβ”‚ └── exampleβ”‚ β”œβ”€β”€ __init__.pyβ”‚ └── test_custom_sklearn.py Now we just need to publish our package on PyPI so that other users can install it on their local machines. Note that our example package depends on scikit-learn and this dependency is explicitly specified in setup.py file. Therefore, when users install your package using say pip, the specified dependencies will also be installed. Now that our source code is structured and contains all the required files for packaging we can go ahead and create the source distribution. A source distribution β€” commonly referred to as sdist β€” is a distribution that contains the setup.py file along with the source code and data files (as specified in the setup.py and/or setup.cfg) You can create the source distribution of the package by running the command given below: python setup.py sdist If everything goes to plan should create a .tar.gz file under the newly created directory dist. In my case setuptools also added a MANIFEST file too. Note: If by any chance you’ve got a warning similar to Unknown distribution option: 'install_requires' you can ignore it for now. twine is a utility package that is used for publishing Python packages on PyPI. pip install twine In order to publish a package on PyPI you have to create an account. You can do so by visiting this link. It’s completely free and to sign up you just need to provide your e-mail address, a username and password. Finally, we’ll now use twine in order to upload the created source distribution on PyPI. twine upload dist/* You will be prompted to type your username and password and your package will be finally made available on PyPI: twine upload dist/*Uploading distributions to https://upload.pypi.org/legacy/Enter your username: YOUR_USER_NAMEEnter your password: YOUR_PASSWORDUploading example_publish_pypi_medium-0.6.tar.gz100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 3.49k/3.49k [00:01<00:00, 2.17kB/s]View at:https://pypi.org/project/example-publish-pypi-medium/0.6/ Voila! Our example package is now available on PyPI. Now let’s verify that our package works as expected. As we already mentioned, the default source index of pip is PyPI. Therefore, our package can be installed directly from pip. To do so, run pip install example-publish-pypi-medium==0.6 The package should be successfully installed on your local machine. If you inspect the output you’ll also see that scikit-learn is also installed since it is a dependency that we also specified while we were packaging our source code. Finally, we can verify that the package works as expected: $ python3>>> from example_publish_pypi_medium.example import custom_sklearn>>> custom_sklearn.get_sklearn_version()'0.24.1' It’s important to know how you can distribute your Python packages and make them widely available. In today’s article we discussed how PyPI is used as a central repository containing Python packages. Additionally, we’ve seen how to package and publish your own Python package to PyPI so that it is widely available. Note however that it is highly recommended to use TestPyPI, which is a separate test instance of the original index that allows users to try out distribution tools and processes without affecting the real index. Once you verify that everything behaves as expected you can then publish it to the real PyPI using the commands we explored earlier.
[ { "code": null, "e": 414, "s": 171, "text": "You wrote a new Python package that solves a specific problem and it’s now time to share it with the wider Python community. To do so, you need to upload the package to a central repository that can be accessed by developers across the globe." }, { "code": null, "e": 821, "s": 414, "text": "In today’s article we are going to discuss how PyPI lets developers share packages with other people who may wish to use that particular functionality in their own application. Additionally, we are going to introduce a step-by-step guide to help you upload your Python package on PyPi so that it is available to every Python user. I’ll use a real end-to-end example so that all the steps are crystal clear." }, { "code": null, "e": 1074, "s": 821, "text": "The Python Package Index, abbreviated as PyPI, is the official repository of software for the Python programming language. By default, pip β€” which is the most popular Python package manager β€” uses PyPI as the source for retrieving package dependencies." }, { "code": null, "e": 1325, "s": 1074, "text": "PyPI lets you find, install and even publish your Python packages so that they are widely available to the public. More than 300,000 different packages are currently published in the index with more than 2,500,000 releases being distributed to users." }, { "code": null, "e": 1471, "s": 1325, "text": "In the following section we’ll explore the steps you need to follow in order to publish your Python package on PyPI and make it available on pip." }, { "code": null, "e": 1673, "s": 1471, "text": "If you are using Python 2 β‰₯ 2.7.9 or Python 3 β‰₯ 3.4 pip should be already installed. But if for any reason you may need to install it simply run the commands below (instructions are suitable for Unix):" }, { "code": null, "e": 1746, "s": 1673, "text": "curl https://bootstrap.pypa.io/get-pip.py -o get-pip.pypython get-pip.py" }, { "code": null, "e": 1812, "s": 1746, "text": "And that’s it! You can ensure that pip is now installed as below." }, { "code": null, "e": 1887, "s": 1812, "text": "$ python -m pip --versionpip X.Y.Z from .../site-packages/pip (python X.Y)" }, { "code": null, "e": 2098, "s": 1887, "text": "I created a sample project on GitHub so that it’s easier to demonstrate how to publish your own packages on PyPI. The project can be found on this link β€” normally you’ll need to create at least the files below:" }, { "code": null, "e": 2311, "s": 2098, "text": "README.rst: It is highly recommended to include a README file where you should outline the basic functionality offered by your package. Additionally, you may also include installation instructions or usage guide." }, { "code": null, "e": 2506, "s": 2311, "text": "LICENSE.txt: It’s always best to include a license in the package you intend to make it widely available. For more options and details refer to the Licensing a repository section of GitHub docs." }, { "code": null, "e": 2836, "s": 2506, "text": "setup.py: This file should be placed into the top-level directory of your project structure. In this file you can specify configurations for your Python project. For more details you can refer to the official documentation. The setup.py file for our example project can be found on GitHub and is identical to the one shown below." }, { "code": null, "e": 2905, "s": 2836, "text": "setup.cfg: This file contains default options for setup.py commands." }, { "code": null, "e": 2965, "s": 2905, "text": "The overall structure of our example project is shown below" }, { "code": null, "e": 3265, "s": 2965, "text": ".β”œβ”€β”€ LICENSE.txtβ”œβ”€β”€ README.rstβ”œβ”€β”€ setup.cfgβ”œβ”€β”€ setup.pyβ”œβ”€β”€ srcβ”‚ β”œβ”€β”€ example_publish_pypi_mediumβ”‚ β”‚ β”œβ”€β”€ __init__.pyβ”‚ β”‚ └── exampleβ”‚ β”‚ β”œβ”€β”€ __init__.pyβ”‚ β”‚ └── custom_sklearn.pyβ”œβ”€β”€ testsβ”‚ β”œβ”€β”€ __init__.pyβ”‚ └── exampleβ”‚ β”œβ”€β”€ __init__.pyβ”‚ └── test_custom_sklearn.py" }, { "code": null, "e": 3598, "s": 3265, "text": "Now we just need to publish our package on PyPI so that other users can install it on their local machines. Note that our example package depends on scikit-learn and this dependency is explicitly specified in setup.py file. Therefore, when users install your package using say pip, the specified dependencies will also be installed." }, { "code": null, "e": 3739, "s": 3598, "text": "Now that our source code is structured and contains all the required files for packaging we can go ahead and create the source distribution." }, { "code": null, "e": 3935, "s": 3739, "text": "A source distribution β€” commonly referred to as sdist β€” is a distribution that contains the setup.py file along with the source code and data files (as specified in the setup.py and/or setup.cfg)" }, { "code": null, "e": 4025, "s": 3935, "text": "You can create the source distribution of the package by running the command given below:" }, { "code": null, "e": 4047, "s": 4025, "text": "python setup.py sdist" }, { "code": null, "e": 4197, "s": 4047, "text": "If everything goes to plan should create a .tar.gz file under the newly created directory dist. In my case setuptools also added a MANIFEST file too." }, { "code": null, "e": 4252, "s": 4197, "text": "Note: If by any chance you’ve got a warning similar to" }, { "code": null, "e": 4300, "s": 4252, "text": "Unknown distribution option: 'install_requires'" }, { "code": null, "e": 4327, "s": 4300, "text": "you can ignore it for now." }, { "code": null, "e": 4407, "s": 4327, "text": "twine is a utility package that is used for publishing Python packages on PyPI." }, { "code": null, "e": 4425, "s": 4407, "text": "pip install twine" }, { "code": null, "e": 4638, "s": 4425, "text": "In order to publish a package on PyPI you have to create an account. You can do so by visiting this link. It’s completely free and to sign up you just need to provide your e-mail address, a username and password." }, { "code": null, "e": 4727, "s": 4638, "text": "Finally, we’ll now use twine in order to upload the created source distribution on PyPI." }, { "code": null, "e": 4747, "s": 4727, "text": "twine upload dist/*" }, { "code": null, "e": 4860, "s": 4747, "text": "You will be prompted to type your username and password and your package will be finally made available on PyPI:" }, { "code": null, "e": 5224, "s": 4860, "text": "twine upload dist/*Uploading distributions to https://upload.pypi.org/legacy/Enter your username: YOUR_USER_NAMEEnter your password: YOUR_PASSWORDUploading example_publish_pypi_medium-0.6.tar.gz100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 3.49k/3.49k [00:01<00:00, 2.17kB/s]View at:https://pypi.org/project/example-publish-pypi-medium/0.6/" }, { "code": null, "e": 5277, "s": 5224, "text": "Voila! Our example package is now available on PyPI." }, { "code": null, "e": 5330, "s": 5277, "text": "Now let’s verify that our package works as expected." }, { "code": null, "e": 5469, "s": 5330, "text": "As we already mentioned, the default source index of pip is PyPI. Therefore, our package can be installed directly from pip. To do so, run" }, { "code": null, "e": 5514, "s": 5469, "text": "pip install example-publish-pypi-medium==0.6" }, { "code": null, "e": 5749, "s": 5514, "text": "The package should be successfully installed on your local machine. If you inspect the output you’ll also see that scikit-learn is also installed since it is a dependency that we also specified while we were packaging our source code." }, { "code": null, "e": 5808, "s": 5749, "text": "Finally, we can verify that the package works as expected:" }, { "code": null, "e": 5932, "s": 5808, "text": "$ python3>>> from example_publish_pypi_medium.example import custom_sklearn>>> custom_sklearn.get_sklearn_version()'0.24.1'" }, { "code": null, "e": 6248, "s": 5932, "text": "It’s important to know how you can distribute your Python packages and make them widely available. In today’s article we discussed how PyPI is used as a central repository containing Python packages. Additionally, we’ve seen how to package and publish your own Python package to PyPI so that it is widely available." } ]
A Guide to Building Your First Regression Model in Just 8 Lines of Code | by Braden Riggs | Towards Data Science
Mathematical modeling and machine learning can often feel like difficult topics to explore and learn, especially to those unfamiliar with the fields of computer science and mathematics. It surprises me to hear from my non-STEM friends that they feel overwhelmed trying to use basic modeling techniques in their own projects and that they can get caught up in the semantics of the field. This is a shame because linear modeling can be very helpful in a number of instances, and with all the open-source code on the internet, implementing your own model has never been easier. Hence, here is my no-frills guide to understanding and implementing a basic linear regression model in Python. Contents: What is Linear Regression? How to Prepare Your Data for Linear Regression. Performing Linear Regression. Interpreting the Results: Final Thoughts and Further Reading Linear regression is a form of mathematical modeling commonly used to evaluate the relationship between a dependent variable, such as weight, and an independent variable, such as height. Our brains do this naturally, just in a less precise manner. If I asked you to decide who the heavier person is between someone who is 6'2" and someone who is 5'2", you would likely pick the 6'2" person. Sure, the 5'2" person could weigh more, but I’ll bet that in your experiences interacting with people, you have established some sort of a relationship between the height of the person and the weight of the person. Linear regression is just a precise and mathematical way of creating this relationship and drawing meaning from it. So how does it work? Linear regression works by creating a line of best fit. The line of best fit is the line that best captures the relationship between the x and y-axis. For example, that relationship could be, as β€œX” increases, β€œY” also increases: Alternatively, this relationship could be as β€œX” increases, β€œY” decreases. Establishing the general direction of the trend is easy enough in the examples above, however, depending on the data, it can become much more complex. Furthermore, the precise details of the line can be hard to calculate by hand. In many cases, having the exact equation of the line can be very helpful, allowing us to understand the relationship between two variables and surmising the value of one variable based on the value of another variable. For linear regression to work effectively, you’ll need at least two things: a variable you think might be dependent, such as the weight in kilograms of an NBA player, and a variable you think might influence the dependent variable, such as the height in centimeters of an NBA player. Linear regression works best if both of these variables are continuous. By continuous I mean that there is a continuation between the values. Someone can weigh 151 lbs or 152 lbs or 151.5 lbs or 151.72 lbs, etc. This is unlike discrete or categorical variables such as movie ratings in stars or grades given in a classroom. There are other techniques for handling these types of data however we will be focusing on linear regression for now. Height and weight are two perfect examples of continuous variables prime for establishing a linear relationship between. If you are following along on Python make sure both of your continuous variables are in float form, this will help with later steps. If you are interested in trying this out with an already cleaned dataset you can follow along with the NBA dataset I am using, which is found here. To load in the data I recommend the Pandas package for python: import pandas as pd #Load the Pandas packagedf = pd.read_csv("archive/all_seasons.csv") #Read the NBA filedf.head() #Display the NBA file's data The output should look like the table above. So now that we have our data loaded in let’s take a look at the relationship between the weight and height of the NBA players: df.plot.scatter("player_height","player_weight", figsize=(15,10)) Apart from a few outliers, we can already see that there is a direct correlation between the height of the player and the weight of the player. As we explained above, linear regression is like drawing a line from the left of the plot to the right of the plot that best follows the relationship of the data. For our NBA example, we can guess that a line of best fit would start somewhere around the 60kg mark and head towards the top right corner of the plot. The problem is that we humans are nowhere near precise enough to draw the line that would perfectly capture the trend of the data. Instead, let's use a tool. Scikit-Learn, or SKLearn, is a python package with a variety of machine learning tools- including one for building linear regression models in a simple and effective manner. To use SKLearn we need to isolate our two variables from the pandas dataframe: from sklearn import linear_model#By calling to_numpy() we convert the series into a numpy array#We then reshape the numpy array into a format parsable for sklearnX = df["player_height"].to_numpy().reshape(-1, 1)y = df["player_weight"].to_numpy().reshape(-1, 1) As you can see, the β€œX” array contains all of the heights and the β€œy” array contains all of the weights. Now we can fit the model. Fitting the model, in this case, means we are presenting the data to the function and allowing SKLearn to find the line that best captures the relationship between β€œX” and β€œy”. #First we call the linear regression function from SKLearn linear_model#Then using this object we fit the data to a linear model.lm = linear_model.LinearRegression()model = lm.fit(X,y) Now that the model is fitted let's take a look at what it came up with. With our model fitted, it's time for us to take a look at what it has established from the data we provided. First, let's look at the parameters it has evaluated for the data: print(model.coef_) #prints the slope of the line[1]: [[1.13557995]]print(model.intercept_) #prints the intercept of the line[2]: [-127.40114263] For those familiar with math, you might remember the equation for the slope of a line, y = mx + b. In this case, β€œb” is the intercept, which can be thought of where the line crosses the y-axis, and β€œm” is the slope of the line. So for our fitted linear regression model the equation would roughly be y = 1.13x -127.4. This means that for every one digit β€œx” increases by β€œy” increases by, 1.13, or rather for every cm taller a player is, the weight of the player should increase by 1.13 kg. Visually, if we plot this line over the scatterplot of player height and weight we get: import numpy as np #numpy can be used for creating a lsit of numbersX = np.arange(150,250) # create a list of example values#plotdf.plot.scatter("player_height","player_weight", figsize=(15,10)).plot(X, model.predict(X.reshape(-1,1)),color='k') In this case, the black line is the line we have fitted to our data. Based on this line, we can surmise that a player at 180 cm will roughly weigh around 70 kg. However, using SKLearn and the model we have created, we can estimate this: model.predict(np.array(180).reshape(-1,1))[3]: array([[77.00324856]]) Hence, a player at 180 cm should roughly weigh 77 kg. Now that the model is trained you can try this on any value. Here would be my NBA weight: model.predict(np.array(188).reshape(-1,1))[4]: array([[86.08788817]]) Whilst this is just a trivial example, linear regression can be very useful for a number of tasks and projects and hence should be as accessible as possible to everyone. My full code for this project can be found below and I encourage you to try it out on your own. Furthermore, I have included some additional readings below if you want to learn more. import pandas as pd from sklearn import linear_modeldf = pd.read_csv("archive/all_seasons.csv")X = df["player_height"].to_numpy().reshape(-1, 1)y = df["player_weight"].to_numpy().reshape(-1, 1)lm = linear_model.LinearRegression()model = lm.fit(X,y)model.predict(np.array(188).reshape(-1,1)) Wow! Just 8 lines of code. Yale course page that goes into a bit more depth: http://www.stat.yale.edu/Courses/1997-98/101/linreg.htm A Youtube video with a great explanation:https://www.youtube.com/watch?v=zPG4NjIkCjc&ab_channel=statisticsfun A special thanks to Justinas Cirtautas for supplying the dataset. All images used are either created by myself or used with the explicit permission of the authors. Links to the author’s material are included under each image.
[ { "code": null, "e": 858, "s": 172, "text": "Mathematical modeling and machine learning can often feel like difficult topics to explore and learn, especially to those unfamiliar with the fields of computer science and mathematics. It surprises me to hear from my non-STEM friends that they feel overwhelmed trying to use basic modeling techniques in their own projects and that they can get caught up in the semantics of the field. This is a shame because linear modeling can be very helpful in a number of instances, and with all the open-source code on the internet, implementing your own model has never been easier. Hence, here is my no-frills guide to understanding and implementing a basic linear regression model in Python." }, { "code": null, "e": 868, "s": 858, "text": "Contents:" }, { "code": null, "e": 895, "s": 868, "text": "What is Linear Regression?" }, { "code": null, "e": 943, "s": 895, "text": "How to Prepare Your Data for Linear Regression." }, { "code": null, "e": 973, "s": 943, "text": "Performing Linear Regression." }, { "code": null, "e": 999, "s": 973, "text": "Interpreting the Results:" }, { "code": null, "e": 1034, "s": 999, "text": "Final Thoughts and Further Reading" }, { "code": null, "e": 1756, "s": 1034, "text": "Linear regression is a form of mathematical modeling commonly used to evaluate the relationship between a dependent variable, such as weight, and an independent variable, such as height. Our brains do this naturally, just in a less precise manner. If I asked you to decide who the heavier person is between someone who is 6'2\" and someone who is 5'2\", you would likely pick the 6'2\" person. Sure, the 5'2\" person could weigh more, but I’ll bet that in your experiences interacting with people, you have established some sort of a relationship between the height of the person and the weight of the person. Linear regression is just a precise and mathematical way of creating this relationship and drawing meaning from it." }, { "code": null, "e": 1777, "s": 1756, "text": "So how does it work?" }, { "code": null, "e": 2007, "s": 1777, "text": "Linear regression works by creating a line of best fit. The line of best fit is the line that best captures the relationship between the x and y-axis. For example, that relationship could be, as β€œX” increases, β€œY” also increases:" }, { "code": null, "e": 2082, "s": 2007, "text": "Alternatively, this relationship could be as β€œX” increases, β€œY” decreases." }, { "code": null, "e": 2531, "s": 2082, "text": "Establishing the general direction of the trend is easy enough in the examples above, however, depending on the data, it can become much more complex. Furthermore, the precise details of the line can be hard to calculate by hand. In many cases, having the exact equation of the line can be very helpful, allowing us to understand the relationship between two variables and surmising the value of one variable based on the value of another variable." }, { "code": null, "e": 2815, "s": 2531, "text": "For linear regression to work effectively, you’ll need at least two things: a variable you think might be dependent, such as the weight in kilograms of an NBA player, and a variable you think might influence the dependent variable, such as the height in centimeters of an NBA player." }, { "code": null, "e": 3257, "s": 2815, "text": "Linear regression works best if both of these variables are continuous. By continuous I mean that there is a continuation between the values. Someone can weigh 151 lbs or 152 lbs or 151.5 lbs or 151.72 lbs, etc. This is unlike discrete or categorical variables such as movie ratings in stars or grades given in a classroom. There are other techniques for handling these types of data however we will be focusing on linear regression for now." }, { "code": null, "e": 3511, "s": 3257, "text": "Height and weight are two perfect examples of continuous variables prime for establishing a linear relationship between. If you are following along on Python make sure both of your continuous variables are in float form, this will help with later steps." }, { "code": null, "e": 3659, "s": 3511, "text": "If you are interested in trying this out with an already cleaned dataset you can follow along with the NBA dataset I am using, which is found here." }, { "code": null, "e": 3722, "s": 3659, "text": "To load in the data I recommend the Pandas package for python:" }, { "code": null, "e": 3867, "s": 3722, "text": "import pandas as pd #Load the Pandas packagedf = pd.read_csv(\"archive/all_seasons.csv\") #Read the NBA filedf.head() #Display the NBA file's data" }, { "code": null, "e": 3912, "s": 3867, "text": "The output should look like the table above." }, { "code": null, "e": 4039, "s": 3912, "text": "So now that we have our data loaded in let’s take a look at the relationship between the weight and height of the NBA players:" }, { "code": null, "e": 4105, "s": 4039, "text": "df.plot.scatter(\"player_height\",\"player_weight\", figsize=(15,10))" }, { "code": null, "e": 4722, "s": 4105, "text": "Apart from a few outliers, we can already see that there is a direct correlation between the height of the player and the weight of the player. As we explained above, linear regression is like drawing a line from the left of the plot to the right of the plot that best follows the relationship of the data. For our NBA example, we can guess that a line of best fit would start somewhere around the 60kg mark and head towards the top right corner of the plot. The problem is that we humans are nowhere near precise enough to draw the line that would perfectly capture the trend of the data. Instead, let's use a tool." }, { "code": null, "e": 4975, "s": 4722, "text": "Scikit-Learn, or SKLearn, is a python package with a variety of machine learning tools- including one for building linear regression models in a simple and effective manner. To use SKLearn we need to isolate our two variables from the pandas dataframe:" }, { "code": null, "e": 5236, "s": 4975, "text": "from sklearn import linear_model#By calling to_numpy() we convert the series into a numpy array#We then reshape the numpy array into a format parsable for sklearnX = df[\"player_height\"].to_numpy().reshape(-1, 1)y = df[\"player_weight\"].to_numpy().reshape(-1, 1)" }, { "code": null, "e": 5544, "s": 5236, "text": "As you can see, the β€œX” array contains all of the heights and the β€œy” array contains all of the weights. Now we can fit the model. Fitting the model, in this case, means we are presenting the data to the function and allowing SKLearn to find the line that best captures the relationship between β€œX” and β€œy”." }, { "code": null, "e": 5729, "s": 5544, "text": "#First we call the linear regression function from SKLearn linear_model#Then using this object we fit the data to a linear model.lm = linear_model.LinearRegression()model = lm.fit(X,y)" }, { "code": null, "e": 5801, "s": 5729, "text": "Now that the model is fitted let's take a look at what it came up with." }, { "code": null, "e": 5977, "s": 5801, "text": "With our model fitted, it's time for us to take a look at what it has established from the data we provided. First, let's look at the parameters it has evaluated for the data:" }, { "code": null, "e": 6122, "s": 5977, "text": "print(model.coef_) #prints the slope of the line[1]: [[1.13557995]]print(model.intercept_) #prints the intercept of the line[2]: [-127.40114263]" }, { "code": null, "e": 6701, "s": 6122, "text": "For those familiar with math, you might remember the equation for the slope of a line, y = mx + b. In this case, β€œb” is the intercept, which can be thought of where the line crosses the y-axis, and β€œm” is the slope of the line. So for our fitted linear regression model the equation would roughly be y = 1.13x -127.4. This means that for every one digit β€œx” increases by β€œy” increases by, 1.13, or rather for every cm taller a player is, the weight of the player should increase by 1.13 kg. Visually, if we plot this line over the scatterplot of player height and weight we get:" }, { "code": null, "e": 6946, "s": 6701, "text": "import numpy as np #numpy can be used for creating a lsit of numbersX = np.arange(150,250) # create a list of example values#plotdf.plot.scatter(\"player_height\",\"player_weight\", figsize=(15,10)).plot(X, model.predict(X.reshape(-1,1)),color='k')" }, { "code": null, "e": 7183, "s": 6946, "text": "In this case, the black line is the line we have fitted to our data. Based on this line, we can surmise that a player at 180 cm will roughly weigh around 70 kg. However, using SKLearn and the model we have created, we can estimate this:" }, { "code": null, "e": 7253, "s": 7183, "text": "model.predict(np.array(180).reshape(-1,1))[3]: array([[77.00324856]])" }, { "code": null, "e": 7307, "s": 7253, "text": "Hence, a player at 180 cm should roughly weigh 77 kg." }, { "code": null, "e": 7397, "s": 7307, "text": "Now that the model is trained you can try this on any value. Here would be my NBA weight:" }, { "code": null, "e": 7467, "s": 7397, "text": "model.predict(np.array(188).reshape(-1,1))[4]: array([[86.08788817]])" }, { "code": null, "e": 7820, "s": 7467, "text": "Whilst this is just a trivial example, linear regression can be very useful for a number of tasks and projects and hence should be as accessible as possible to everyone. My full code for this project can be found below and I encourage you to try it out on your own. Furthermore, I have included some additional readings below if you want to learn more." }, { "code": null, "e": 8111, "s": 7820, "text": "import pandas as pd from sklearn import linear_modeldf = pd.read_csv(\"archive/all_seasons.csv\")X = df[\"player_height\"].to_numpy().reshape(-1, 1)y = df[\"player_weight\"].to_numpy().reshape(-1, 1)lm = linear_model.LinearRegression()model = lm.fit(X,y)model.predict(np.array(188).reshape(-1,1))" }, { "code": null, "e": 8138, "s": 8111, "text": "Wow! Just 8 lines of code." }, { "code": null, "e": 8244, "s": 8138, "text": "Yale course page that goes into a bit more depth: http://www.stat.yale.edu/Courses/1997-98/101/linreg.htm" }, { "code": null, "e": 8354, "s": 8244, "text": "A Youtube video with a great explanation:https://www.youtube.com/watch?v=zPG4NjIkCjc&ab_channel=statisticsfun" }, { "code": null, "e": 8420, "s": 8354, "text": "A special thanks to Justinas Cirtautas for supplying the dataset." } ]
CICS - REWRITE
REWRITE command is used to modify a record that is already present in a file. Prior to this command, the record must be read with a READ UPDATE command. The parameters are same as described before. The syntax for the Rewrite command is as follows βˆ’ EXEC CICS REWRITE FILE (name) FROM (data-area) LENGTH (data-value) END-EXEC. The following example shows how to write a record in 'FL001' file where Studentid is the primary key. A new record with 101 student id will be written in the file βˆ’ IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-STD-REC-LEN PIC S9(4) COMP. 01 WS-STD-KEY-LEN PIC S9(4) COMP. 01 WS-STD-REC-KEY PIC 9(3). 01 WS-STD-REC PIC X(70). PROCEDURE DIVISION. MOVE +70 TO WS-STD-REC-LEN. MOVE β€˜101’ TO WS-STD-REC-KEY. MOVE 3 TO WS-STD-KEY-LEN. EXEC CICS READ FILE ('FL001') INTO (WS-STD-REC) LENGTH (WS-STD-REC-LEN) RIDFLD (WS-STD-REC-KEY) KEYLENGTH (WS-STD-KEY-LEN) UPDATE END-EXEC. MOVE '100Mohtahim M TutorialsPnt' TO WS-STD-REC. EXEC CICS REWRITE FILE ('FL001') FROM (WS-STD-REC) LENGTH (WS-STD-REC-LEN) END-EXEC. The following table lists the exceptions that arise during a REWRITE statement βˆ’ NOTOPEN File is not open. LENGERR Mismatch between the length specified in command and actual length of the record. NOTAUTH If the user does not have enough permissions to use the file. INVREQ Rewrite without prior READ with UPDATE. NOSPACE There is not enough space in the dataset. Print Add Notes Bookmark this page
[ { "code": null, "e": 2175, "s": 1926, "text": "REWRITE command is used to modify a record that is already present in a file. Prior to this command, the record must be read with a READ UPDATE command. The parameters are same as described before. The syntax for the Rewrite command is as follows βˆ’" }, { "code": null, "e": 2263, "s": 2175, "text": "EXEC CICS REWRITE\n FILE (name)\n FROM (data-area) \n LENGTH (data-value)\nEND-EXEC.\n" }, { "code": null, "e": 2428, "s": 2263, "text": "The following example shows how to write a record in 'FL001' file where Studentid is the primary key. A new record with 101 student id will be written in the file βˆ’" }, { "code": null, "e": 3173, "s": 2428, "text": "IDENTIFICATION DIVISION. \nPROGRAM-ID. HELLO. \nDATA DIVISION. \nWORKING-STORAGE SECTION.\n01 WS-STD-REC-LEN PIC S9(4) COMP.\n01 WS-STD-KEY-LEN PIC S9(4) COMP.\n01 WS-STD-REC-KEY PIC 9(3).\n01 WS-STD-REC PIC X(70).\nPROCEDURE DIVISION.\nMOVE +70 TO WS-STD-REC-LEN.\nMOVE β€˜101’ TO WS-STD-REC-KEY.\nMOVE 3 TO WS-STD-KEY-LEN.\nEXEC CICS READ\n FILE ('FL001')\n INTO (WS-STD-REC)\n LENGTH (WS-STD-REC-LEN)\n RIDFLD (WS-STD-REC-KEY)\n KEYLENGTH (WS-STD-KEY-LEN)\n UPDATE\nEND-EXEC.\nMOVE '100Mohtahim M TutorialsPnt' TO WS-STD-REC.\nEXEC CICS REWRITE\n FILE ('FL001')\n FROM (WS-STD-REC)\n LENGTH (WS-STD-REC-LEN)\nEND-EXEC." }, { "code": null, "e": 3254, "s": 3173, "text": "The following table lists the exceptions that arise during a REWRITE statement βˆ’" }, { "code": null, "e": 3262, "s": 3254, "text": "NOTOPEN" }, { "code": null, "e": 3280, "s": 3262, "text": "File is not open." }, { "code": null, "e": 3288, "s": 3280, "text": "LENGERR" }, { "code": null, "e": 3370, "s": 3288, "text": "Mismatch between the length specified in command and actual length of the record." }, { "code": null, "e": 3378, "s": 3370, "text": "NOTAUTH" }, { "code": null, "e": 3440, "s": 3378, "text": "If the user does not have enough permissions to use the file." }, { "code": null, "e": 3447, "s": 3440, "text": "INVREQ" }, { "code": null, "e": 3487, "s": 3447, "text": "Rewrite without prior READ with UPDATE." }, { "code": null, "e": 3495, "s": 3487, "text": "NOSPACE" }, { "code": null, "e": 3537, "s": 3495, "text": "There is not enough space in the dataset." }, { "code": null, "e": 3544, "s": 3537, "text": " Print" }, { "code": null, "e": 3555, "s": 3544, "text": " Add Notes" } ]
How to get the values of a particular row in a table in Selenium with python?
We can get the values of a particular row in a table in Selenium. The rows of a table are represented by <tr> tag in html code. The data in each row is enclosed with the <td> tag in html. Thus a <td> tag’s parent is always a <tr> tag. The logic is get all the rows, we shall use the locator xpath and then use find_elements_by_xpath method. The list of rows will be returned. Next we need to compute the size of the list with the help of len method. The <td> is not normally present in the first row of the table. In place of <td>, there is the <th> tag. driver.find_elements_by_xpath("//table/tbody/tr[2]/td") The html code snippet of a table header is as described below βˆ’ Coding Implementation to get the second row data. from selenium import webdriver #browser exposes an executable file #Through Selenium test we will invoke the executable file which will then #invoke actual browser driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe") # to maximize the browser window driver.maximize_window() #get method to launch the URL driver.get("https://www.tutorialspoint.com/plsql/plsql_basic_syntax.htm") #to refresh the browser driver.refresh() # identifying the from row2 having <td> tag rwdata = driver.find_elements_by_xpath("//table/tbody/tr[2]/td") # len method is used to get the size of that list print(len(rwdata)) for r in rwdata: print(r.text) #to close the browser driver.close()
[ { "code": null, "e": 1297, "s": 1062, "text": "We can get the values of a particular row in a table in Selenium. The rows\nof a table are represented by <tr> tag in html code. The data in each row is enclosed\nwith the <td> tag in html. Thus a <td> tag’s parent is always a <tr> tag." }, { "code": null, "e": 1512, "s": 1297, "text": "The logic is get all the rows, we shall use the locator xpath and then use find_elements_by_xpath method. The list of rows will be returned. Next we need to compute the size of the list with the help of len method." }, { "code": null, "e": 1617, "s": 1512, "text": "The <td> is not normally present in the first row of the table. In place of <td>, there\nis the <th> tag." }, { "code": null, "e": 1673, "s": 1617, "text": "driver.find_elements_by_xpath(\"//table/tbody/tr[2]/td\")" }, { "code": null, "e": 1737, "s": 1673, "text": "The html code snippet of a table header is as described below βˆ’" }, { "code": null, "e": 1787, "s": 1737, "text": "Coding Implementation to get the second row data." }, { "code": null, "e": 2469, "s": 1787, "text": "from selenium import webdriver\n#browser exposes an executable file\n#Through Selenium test we will invoke the executable file which will then\n#invoke actual browser\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n# to maximize the browser window\ndriver.maximize_window()\n#get method to launch the URL\ndriver.get(\"https://www.tutorialspoint.com/plsql/plsql_basic_syntax.htm\")\n#to refresh the browser\ndriver.refresh()\n# identifying the from row2 having <td> tag\nrwdata = driver.find_elements_by_xpath(\"//table/tbody/tr[2]/td\")\n# len method is used to get the size of that list\nprint(len(rwdata))\nfor r in rwdata:\n print(r.text)\n#to close the browser\ndriver.close()" } ]
Clear a Hashtable in C#
Clear a Hashtable, using the Clear() method in C#. The following is our Hashtable βˆ’ Hashtable h = new Hashtable(); h.Add(1, "Amit"); h.Add(2, "Sachin"); h.Add(3, "Rahul"); Use the clear method. h.Clear(); If you will now try to display the Hashtable, nothing would get display since the Hashtable is empty. Live Demo using System; using System.Collections; public class Demo { public static void Main() { Hashtable h = new Hashtable(); h.Add(1, "Amit"); h.Add(2, "Sachin"); h.Add(3, "Rahul"); Console.WriteLine("Keys and Values list:"); foreach (var key in h.Keys ) { Console.WriteLine("Key = {0}, Value = {1}",key , h[key]); } // clear all key value pairs Console.WriteLine("The Hashtable key and Value Pairs are empty now..."); h.Clear(); foreach (var key in h.Keys ) { Console.WriteLine("Key = {0}, Value = {1}",key , h[key]); } } } Keys and Values list: Key = 3, Value = Rahul Key = 2, Value = Sachin Key = 1, Value = Amit The Hashtable key and Value Pairs are empty now...
[ { "code": null, "e": 1113, "s": 1062, "text": "Clear a Hashtable, using the Clear() method in C#." }, { "code": null, "e": 1146, "s": 1113, "text": "The following is our Hashtable βˆ’" }, { "code": null, "e": 1234, "s": 1146, "text": "Hashtable h = new Hashtable();\nh.Add(1, \"Amit\");\nh.Add(2, \"Sachin\");\nh.Add(3, \"Rahul\");" }, { "code": null, "e": 1256, "s": 1234, "text": "Use the clear method." }, { "code": null, "e": 1267, "s": 1256, "text": "h.Clear();" }, { "code": null, "e": 1369, "s": 1267, "text": "If you will now try to display the Hashtable, nothing would get display since the Hashtable is empty." }, { "code": null, "e": 1380, "s": 1369, "text": " Live Demo" }, { "code": null, "e": 1995, "s": 1380, "text": "using System;\nusing System.Collections;\npublic class Demo {\n public static void Main() {\n Hashtable h = new Hashtable();\n h.Add(1, \"Amit\");\n h.Add(2, \"Sachin\");\n h.Add(3, \"Rahul\");\n Console.WriteLine(\"Keys and Values list:\");\n foreach (var key in h.Keys ) {\n Console.WriteLine(\"Key = {0}, Value = {1}\",key , h[key]);\n }\n // clear all key value pairs\n Console.WriteLine(\"The Hashtable key and Value Pairs are empty now...\");\n h.Clear();\n foreach (var key in h.Keys ) {\n Console.WriteLine(\"Key = {0}, Value = {1}\",key , h[key]);\n }\n }\n}" }, { "code": null, "e": 2137, "s": 1995, "text": "Keys and Values list:\nKey = 3, Value = Rahul\nKey = 2, Value = Sachin\nKey = 1, Value = Amit\nThe Hashtable key and Value Pairs are empty now..." } ]
Lexicographically largest string possible in one swap - GeeksforGeeks
03 Aug, 2021 Given string str of length N, the task is to obtain the lexicographically largest string by at most one swap. Note: The swapping characters might not be adjacent. Examples: Input: str = β€œstring” Output: tsring Explanation: Lexicographically largest string obtained by swapping string -> tsring. Input: str = β€œzyxw” Output: zyxw Explanation: The given string is already lexicographically largest Approach: To solve the above-mentioned problem, the main idea is to use Sorting and compute the largest lexicographical string possible for the given string. After sorting the given string in descending order, find the first unmatched character from the given string and replace it with the last occurrence of the unmatched character in the sorted string. Illustration: str = β€œgeeks” Sorted string in descending order = β€œskgee”. The first unmatched character is in the first place. This character needs to be swapped with the character at this position in the sorted string which results in the lexicographically largest string. On replacing β€œg” with the β€œs”, the string obtained is β€œseekg” which is lexicographically largest after one swap. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to find the// lexicographically largest string// by atmost at most one swap #include <bits/stdc++.h>using namespace std; // Function to return the// lexicographically largest// string possible by swapping// at most one characterstring findLargest(string s){ int len = s.size(); // Stores last occurrence // of every character int loccur[26]; // Initialize with -1 for // every character memset(loccur, -1, sizeof(loccur)); for (int i = len - 1; i >= 0; --i) { // Keep updating the last // occurrence of each character int chI = s[i] - 'a'; // If a previously unvisited // character occurs if (loccur[chI] == -1) { loccur[chI] = i; } } // Stores the sorted string string sorted_s = s; sort(sorted_s.begin(), sorted_s.end(), greater<int>()); for (int i = 0; i < len; ++i) { if (s[i] != sorted_s[i]) { // Character to replace int chI = sorted_s[i] - 'a'; // Find the last occurrence // of this character int last_occ = loccur[chI]; // Swap this with the last // occurrence swap(s[i], s[last_occ]); break; } } return s;} // Driver Programint main(){ string s = "yrstvw"; cout << findLargest(s); return 0;} // Java implementation to find the// lexicographically largest string// by atmost at most one swapimport java.util.*;import java.lang.*; class GFG{ // Function to return the// lexicographically largest// string possible by swapping// at most one characterstatic String findLargest(StringBuilder s){ int len = s.length(); // Stores last occurrence // of every character int[] loccur = new int[26]; // Initialize with -1 for // every character Arrays.fill(loccur, -1); for(int i = len - 1; i >= 0; --i) { // Keep updating the last // occurrence of each character int chI = s.charAt(i) - 'a'; // If a previously unvisited // character occurs if (loccur[chI] == -1) { loccur[chI] = i; } } // Stores the sorted string char[] sorted_s = s.toString().toCharArray(); Arrays.sort(sorted_s); reverse(sorted_s); for(int i = 0; i < len; ++i) { if (s.charAt(i) != sorted_s[i]) { // Character to replace int chI = sorted_s[i] - 'a'; // Find the last occurrence // of this character int last_occ = loccur[chI]; // Swap this with the last // occurrence char tmp = s.charAt(i); s.setCharAt(i, s.charAt(last_occ)); s.setCharAt(last_occ, tmp); break; } } return s.toString();} // Function to reverse arraystatic void reverse(char a[]){ int i, n = a.length; for(i = 0; i < n / 2; i++) { char t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; }} // Driver Codepublic static void main(String[] args){ StringBuilder s = new StringBuilder("yrstvw"); System.out.println(findLargest(s));}} // This code is contributed by offbeat # Python3 implementation to find the # lexicographically largest string # by atmost at most one swap # Function to return the # lexicographically largest # string possible by swapping # at most one characterdef findLargest(s): Len = len(s) # Stores last occurrence # of every character # Initialize with -1 for # every character loccur = [-1 for i in range(26)] for i in range(Len - 1, -1, -1): # Keep updating the last # occurrence of each character chI = ord(s[i]) - ord('a') # If a previously unvisited # character occurs if(loccur[chI] == -1): loccur[chI] = i # Stores the sorted string sorted_s = sorted(s, reverse = True) for i in range(Len): if(s[i] != sorted_s[i]): # Character to replace chI = (ord(sorted_s[i]) - ord('a')) # Find the last occurrence # of this character last_occ = loccur[chI] temp = list(s) # Swap this with the last # occurrence temp[i], temp[last_occ] = (temp[last_occ], temp[i]) s = "".join(temp) break return s # Driver codes = "yrstvw"print(findLargest(s)) # This code is contributed by avanitrachhadiya2155 // C# implementation to find the// lexicographically largest string// by atmost at most one swapusing System;using System.Collections.Generic; class GFG{ // Function to return the// lexicographically largest// string possible by swapping// at most one characterstatic string findLargest(char[] s){ int len = s.Length; // Stores last occurrence // of every character int[] loccur = new int[26]; // Initialize with -1 for // every character Array.Fill(loccur, -1); for(int i = len - 1; i >= 0; --i) { // Keep updating the last // occurrence of each character int chI = s[i] - 'a'; // If a previously unvisited // character occurs if (loccur[chI] == -1) { loccur[chI] = i; } } // Stores the sorted string char[] sorted_s = (new string(s)).ToCharArray(); Array.Sort(sorted_s); Array.Reverse(sorted_s); for(int i = 0; i < len; ++i) { if (s[i] != sorted_s[i]) { // Character to replace int chI = sorted_s[i] - 'a'; // Find the last occurrence // of this character int last_occ = loccur[chI]; // Swap this with the last // occurrence char temp = s[i]; s[i] = s[last_occ]; s[last_occ] = temp; break; } } return (new string(s));} // Driver Codestatic void Main(){ string str = "yrstvw"; char[] s = str.ToCharArray(); Console.WriteLine(findLargest(s));}} // This code is contributed by divyesh072019 <script> // Javascript implementation to find the // lexicographically largest string // by atmost at most one swap // Function to return the // lexicographically largest // string possible by swapping // at most one character function findLargest(s) { let len = s.length; // Stores last occurrence // of every character let loccur = new Array(26); // Initialize with -1 for // every character loccur.fill(-1); for(let i = len - 1; i >= 0; --i) { // Keep updating the last // occurrence of each character let chI = s[i].charCodeAt() - 'a'.charCodeAt(); // If a previously unvisited // character occurs if (loccur[chI] == -1) { loccur[chI] = i; } } // Stores the sorted string let sorted_s = s.join("").split(''); sorted_s.sort(); sorted_s.reverse(); for(let i = 0; i < len; ++i) { if (s[i] != sorted_s[i]) { // Character to replace let chI = sorted_s[i].charCodeAt() - 'a'.charCodeAt(); // Find the last occurrence // of this character let last_occ = loccur[chI]; // Swap this with the last // occurrence let temp = s[i]; s[i] = s[last_occ]; s[last_occ] = temp; break; } } return (s.join("")); } let str = "yrstvw"; let s = str.split(''); document.write(findLargest(s)); </script> ywstvr offbeat avanitrachhadiya2155 divyesh072019 mukesh07 sagartomar9927 lexicographic-ordering Swap-Program Competitive Programming Greedy Sorting Strings Strings Greedy Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multistage Graph (Shortest Path) Breadth First Traversal ( BFS ) on a 2D array Difference between Backtracking and Branch-N-Bound technique Minimum changes required to make all Array elements Prime Most important type of Algorithms Dijkstra's shortest path algorithm | Greedy Algo-7 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Program for array rotation Huffman Coding | Greedy Algo-3
[ { "code": null, "e": 26908, "s": 26880, "text": "\n03 Aug, 2021" }, { "code": null, "e": 27019, "s": 26908, "text": "Given string str of length N, the task is to obtain the lexicographically largest string by at most one swap. " }, { "code": null, "e": 27072, "s": 27019, "text": "Note: The swapping characters might not be adjacent." }, { "code": null, "e": 27082, "s": 27072, "text": "Examples:" }, { "code": null, "e": 27204, "s": 27082, "text": "Input: str = β€œstring” Output: tsring Explanation: Lexicographically largest string obtained by swapping string -> tsring." }, { "code": null, "e": 27304, "s": 27204, "text": "Input: str = β€œzyxw” Output: zyxw Explanation: The given string is already lexicographically largest" }, { "code": null, "e": 27660, "s": 27304, "text": "Approach: To solve the above-mentioned problem, the main idea is to use Sorting and compute the largest lexicographical string possible for the given string. After sorting the given string in descending order, find the first unmatched character from the given string and replace it with the last occurrence of the unmatched character in the sorted string." }, { "code": null, "e": 28046, "s": 27660, "text": "Illustration: str = β€œgeeks” Sorted string in descending order = β€œskgee”. The first unmatched character is in the first place. This character needs to be swapped with the character at this position in the sorted string which results in the lexicographically largest string. On replacing β€œg” with the β€œs”, the string obtained is β€œseekg” which is lexicographically largest after one swap." }, { "code": null, "e": 28097, "s": 28046, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28101, "s": 28097, "text": "C++" }, { "code": null, "e": 28106, "s": 28101, "text": "Java" }, { "code": null, "e": 28114, "s": 28106, "text": "Python3" }, { "code": null, "e": 28117, "s": 28114, "text": "C#" }, { "code": null, "e": 28128, "s": 28117, "text": "Javascript" }, { "code": "// C++ implementation to find the// lexicographically largest string// by atmost at most one swap #include <bits/stdc++.h>using namespace std; // Function to return the// lexicographically largest// string possible by swapping// at most one characterstring findLargest(string s){ int len = s.size(); // Stores last occurrence // of every character int loccur[26]; // Initialize with -1 for // every character memset(loccur, -1, sizeof(loccur)); for (int i = len - 1; i >= 0; --i) { // Keep updating the last // occurrence of each character int chI = s[i] - 'a'; // If a previously unvisited // character occurs if (loccur[chI] == -1) { loccur[chI] = i; } } // Stores the sorted string string sorted_s = s; sort(sorted_s.begin(), sorted_s.end(), greater<int>()); for (int i = 0; i < len; ++i) { if (s[i] != sorted_s[i]) { // Character to replace int chI = sorted_s[i] - 'a'; // Find the last occurrence // of this character int last_occ = loccur[chI]; // Swap this with the last // occurrence swap(s[i], s[last_occ]); break; } } return s;} // Driver Programint main(){ string s = \"yrstvw\"; cout << findLargest(s); return 0;}", "e": 29495, "s": 28128, "text": null }, { "code": "// Java implementation to find the// lexicographically largest string// by atmost at most one swapimport java.util.*;import java.lang.*; class GFG{ // Function to return the// lexicographically largest// string possible by swapping// at most one characterstatic String findLargest(StringBuilder s){ int len = s.length(); // Stores last occurrence // of every character int[] loccur = new int[26]; // Initialize with -1 for // every character Arrays.fill(loccur, -1); for(int i = len - 1; i >= 0; --i) { // Keep updating the last // occurrence of each character int chI = s.charAt(i) - 'a'; // If a previously unvisited // character occurs if (loccur[chI] == -1) { loccur[chI] = i; } } // Stores the sorted string char[] sorted_s = s.toString().toCharArray(); Arrays.sort(sorted_s); reverse(sorted_s); for(int i = 0; i < len; ++i) { if (s.charAt(i) != sorted_s[i]) { // Character to replace int chI = sorted_s[i] - 'a'; // Find the last occurrence // of this character int last_occ = loccur[chI]; // Swap this with the last // occurrence char tmp = s.charAt(i); s.setCharAt(i, s.charAt(last_occ)); s.setCharAt(last_occ, tmp); break; } } return s.toString();} // Function to reverse arraystatic void reverse(char a[]){ int i, n = a.length; for(i = 0; i < n / 2; i++) { char t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; }} // Driver Codepublic static void main(String[] args){ StringBuilder s = new StringBuilder(\"yrstvw\"); System.out.println(findLargest(s));}} // This code is contributed by offbeat", "e": 31413, "s": 29495, "text": null }, { "code": "# Python3 implementation to find the # lexicographically largest string # by atmost at most one swap # Function to return the # lexicographically largest # string possible by swapping # at most one characterdef findLargest(s): Len = len(s) # Stores last occurrence # of every character # Initialize with -1 for # every character loccur = [-1 for i in range(26)] for i in range(Len - 1, -1, -1): # Keep updating the last # occurrence of each character chI = ord(s[i]) - ord('a') # If a previously unvisited # character occurs if(loccur[chI] == -1): loccur[chI] = i # Stores the sorted string sorted_s = sorted(s, reverse = True) for i in range(Len): if(s[i] != sorted_s[i]): # Character to replace chI = (ord(sorted_s[i]) - ord('a')) # Find the last occurrence # of this character last_occ = loccur[chI] temp = list(s) # Swap this with the last # occurrence temp[i], temp[last_occ] = (temp[last_occ], temp[i]) s = \"\".join(temp) break return s # Driver codes = \"yrstvw\"print(findLargest(s)) # This code is contributed by avanitrachhadiya2155", "e": 32741, "s": 31413, "text": null }, { "code": "// C# implementation to find the// lexicographically largest string// by atmost at most one swapusing System;using System.Collections.Generic; class GFG{ // Function to return the// lexicographically largest// string possible by swapping// at most one characterstatic string findLargest(char[] s){ int len = s.Length; // Stores last occurrence // of every character int[] loccur = new int[26]; // Initialize with -1 for // every character Array.Fill(loccur, -1); for(int i = len - 1; i >= 0; --i) { // Keep updating the last // occurrence of each character int chI = s[i] - 'a'; // If a previously unvisited // character occurs if (loccur[chI] == -1) { loccur[chI] = i; } } // Stores the sorted string char[] sorted_s = (new string(s)).ToCharArray(); Array.Sort(sorted_s); Array.Reverse(sorted_s); for(int i = 0; i < len; ++i) { if (s[i] != sorted_s[i]) { // Character to replace int chI = sorted_s[i] - 'a'; // Find the last occurrence // of this character int last_occ = loccur[chI]; // Swap this with the last // occurrence char temp = s[i]; s[i] = s[last_occ]; s[last_occ] = temp; break; } } return (new string(s));} // Driver Codestatic void Main(){ string str = \"yrstvw\"; char[] s = str.ToCharArray(); Console.WriteLine(findLargest(s));}} // This code is contributed by divyesh072019", "e": 34383, "s": 32741, "text": null }, { "code": "<script> // Javascript implementation to find the // lexicographically largest string // by atmost at most one swap // Function to return the // lexicographically largest // string possible by swapping // at most one character function findLargest(s) { let len = s.length; // Stores last occurrence // of every character let loccur = new Array(26); // Initialize with -1 for // every character loccur.fill(-1); for(let i = len - 1; i >= 0; --i) { // Keep updating the last // occurrence of each character let chI = s[i].charCodeAt() - 'a'.charCodeAt(); // If a previously unvisited // character occurs if (loccur[chI] == -1) { loccur[chI] = i; } } // Stores the sorted string let sorted_s = s.join(\"\").split(''); sorted_s.sort(); sorted_s.reverse(); for(let i = 0; i < len; ++i) { if (s[i] != sorted_s[i]) { // Character to replace let chI = sorted_s[i].charCodeAt() - 'a'.charCodeAt(); // Find the last occurrence // of this character let last_occ = loccur[chI]; // Swap this with the last // occurrence let temp = s[i]; s[i] = s[last_occ]; s[last_occ] = temp; break; } } return (s.join(\"\")); } let str = \"yrstvw\"; let s = str.split(''); document.write(findLargest(s)); </script>", "e": 36062, "s": 34383, "text": null }, { "code": null, "e": 36069, "s": 36062, "text": "ywstvr" }, { "code": null, "e": 36079, "s": 36071, "text": "offbeat" }, { "code": null, "e": 36100, "s": 36079, "text": "avanitrachhadiya2155" }, { "code": null, "e": 36114, "s": 36100, "text": "divyesh072019" }, { "code": null, "e": 36123, "s": 36114, "text": "mukesh07" }, { "code": null, "e": 36138, "s": 36123, "text": "sagartomar9927" }, { "code": null, "e": 36161, "s": 36138, "text": "lexicographic-ordering" }, { "code": null, "e": 36174, "s": 36161, "text": "Swap-Program" }, { "code": null, "e": 36198, "s": 36174, "text": "Competitive Programming" }, { "code": null, "e": 36205, "s": 36198, "text": "Greedy" }, { "code": null, "e": 36213, "s": 36205, "text": "Sorting" }, { "code": null, "e": 36221, "s": 36213, "text": "Strings" }, { "code": null, "e": 36229, "s": 36221, "text": "Strings" }, { "code": null, "e": 36236, "s": 36229, "text": "Greedy" }, { "code": null, "e": 36244, "s": 36236, "text": "Sorting" }, { "code": null, "e": 36342, "s": 36244, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36375, "s": 36342, "text": "Multistage Graph (Shortest Path)" }, { "code": null, "e": 36421, "s": 36375, "text": "Breadth First Traversal ( BFS ) on a 2D array" }, { "code": null, "e": 36482, "s": 36421, "text": "Difference between Backtracking and Branch-N-Bound technique" }, { "code": null, "e": 36540, "s": 36482, "text": "Minimum changes required to make all Array elements Prime" }, { "code": null, "e": 36574, "s": 36540, "text": "Most important type of Algorithms" }, { "code": null, "e": 36625, "s": 36574, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 36683, "s": 36625, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 36734, "s": 36683, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 36761, "s": 36734, "text": "Program for array rotation" } ]
Python - String with most unique characters - GeeksforGeeks
06 Mar, 2020 Sometimes, while working with python strings, we can have a problem in which we desire to extract particular list which has most number of unique characters. This kind of problem can have application in competitive programming and web development domain. Lets discuss certain ways in which this task can be performed. Method #1 : Using max() + dictionary comprehensionThe combination of above functionalities can be used to perform this task. In this, we firstly collect the frequency of each character using dictionary and then employ max() to compute the string with most unique characters. # Python3 code to demonstrate # String with most unique characters# using max() + dictionary comprehension # Initializing listtest_list = ['gfg', 'is', 'best', 'for', 'geeksc'] # printing original listprint("The original list is : " + str(test_list)) # String with most unique characters# using max() + dictionary comprehensiontemp = {idx : len(set(idx)) for idx in test_list}res = max(temp, key = temp.get) # printing result print ("The string with most unique characters is : " + str(res)) The original list is : ['gfg', 'is', 'best', 'for', 'geeksc'] The string with most unique characters is : geeksc Method #2 : Using max() + key + lambdaThe combination of above methods can be used to perform this task. In this, we perform this task in similar way as above, just the difference is instead of using comprehension we use lambda function to extend logic to each string for computation. # Python3 code to demonstrate # String with most unique characters# using max() + key + lambda # Initializing listtest_list = ['gfg', 'is', 'best', 'for', 'geeksc'] # printing original listprint("The original list is : " + str(test_list)) # String with most unique characters# using max() + key + lambdares = max(test_list, key = lambda sub: len(set(sub)), default = None) # printing result print ("The string with most unique characters is : " + str(res)) The original list is : ['gfg', 'is', 'best', 'for', 'geeksc'] The string with most unique characters is : geeksc Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25647, "s": 25619, "text": "\n06 Mar, 2020" }, { "code": null, "e": 25965, "s": 25647, "text": "Sometimes, while working with python strings, we can have a problem in which we desire to extract particular list which has most number of unique characters. This kind of problem can have application in competitive programming and web development domain. Lets discuss certain ways in which this task can be performed." }, { "code": null, "e": 26240, "s": 25965, "text": "Method #1 : Using max() + dictionary comprehensionThe combination of above functionalities can be used to perform this task. In this, we firstly collect the frequency of each character using dictionary and then employ max() to compute the string with most unique characters." }, { "code": "# Python3 code to demonstrate # String with most unique characters# using max() + dictionary comprehension # Initializing listtest_list = ['gfg', 'is', 'best', 'for', 'geeksc'] # printing original listprint(\"The original list is : \" + str(test_list)) # String with most unique characters# using max() + dictionary comprehensiontemp = {idx : len(set(idx)) for idx in test_list}res = max(temp, key = temp.get) # printing result print (\"The string with most unique characters is : \" + str(res))", "e": 26737, "s": 26240, "text": null }, { "code": null, "e": 26851, "s": 26737, "text": "The original list is : ['gfg', 'is', 'best', 'for', 'geeksc']\nThe string with most unique characters is : geeksc\n" }, { "code": null, "e": 27138, "s": 26853, "text": "Method #2 : Using max() + key + lambdaThe combination of above methods can be used to perform this task. In this, we perform this task in similar way as above, just the difference is instead of using comprehension we use lambda function to extend logic to each string for computation." }, { "code": "# Python3 code to demonstrate # String with most unique characters# using max() + key + lambda # Initializing listtest_list = ['gfg', 'is', 'best', 'for', 'geeksc'] # printing original listprint(\"The original list is : \" + str(test_list)) # String with most unique characters# using max() + key + lambdares = max(test_list, key = lambda sub: len(set(sub)), default = None) # printing result print (\"The string with most unique characters is : \" + str(res))", "e": 27599, "s": 27138, "text": null }, { "code": null, "e": 27713, "s": 27599, "text": "The original list is : ['gfg', 'is', 'best', 'for', 'geeksc']\nThe string with most unique characters is : geeksc\n" }, { "code": null, "e": 27734, "s": 27713, "text": "Python list-programs" }, { "code": null, "e": 27741, "s": 27734, "text": "Python" }, { "code": null, "e": 27757, "s": 27741, "text": "Python Programs" }, { "code": null, "e": 27855, "s": 27757, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27887, "s": 27855, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27929, "s": 27887, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27971, "s": 27929, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28027, "s": 27971, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28054, "s": 28027, "text": "Python Classes and Objects" }, { "code": null, "e": 28076, "s": 28054, "text": "Defaultdict in Python" }, { "code": null, "e": 28115, "s": 28076, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28161, "s": 28115, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28199, "s": 28161, "text": "Python | Convert a list to dictionary" } ]
How to set vertical gap between elements in a GridLayout with Java?
Use the setVgap() method to set the vertical gap between elements in a GridLayout. Let’s say we have a GridLaypout βˆ’ GridLayout layout = new GridLayout(3,3); Set the horizontal gap βˆ’ layout.setVgap(30); The following is an example βˆ’ package my; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.WindowConstants; public class SwingDemo { public static void main(String[] args) { JFrame frame = new JFrame("Sections"); JPanel panel = new JPanel(); panel.setBackground(Color.blue); GridLayout layout = new GridLayout(3,3); layout.setVgap(30); panel.setLayout(layout); panel.add(new JButton("Overview")); panel.add(new JButton("Samples")); panel.add(new JButton("Tutorials")); panel.add(new JButton("Support")); panel.add(new JButton("InterviewQA")); panel.add(new JButton("Tools")); panel.add(new JButton("Editors")); frame.add(panel); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setSize(500, 300); frame.setVisible(true); } }
[ { "code": null, "e": 1179, "s": 1062, "text": "Use the setVgap() method to set the vertical gap between elements in a GridLayout. Let’s say we have a GridLaypout βˆ’" }, { "code": null, "e": 1220, "s": 1179, "text": "GridLayout layout = new GridLayout(3,3);" }, { "code": null, "e": 1245, "s": 1220, "text": "Set the horizontal gap βˆ’" }, { "code": null, "e": 1265, "s": 1245, "text": "layout.setVgap(30);" }, { "code": null, "e": 1295, "s": 1265, "text": "The following is an example βˆ’" }, { "code": null, "e": 2355, "s": 1295, "text": "package my;\nimport java.awt.Color;\nimport java.awt.Dimension;\nimport java.awt.FlowLayout;\nimport java.awt.Font;\nimport java.awt.GridLayout;\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JPanel;\nimport javax.swing.JTextArea;\nimport javax.swing.WindowConstants;\npublic class SwingDemo {\n public static void main(String[] args) {\n JFrame frame = new JFrame(\"Sections\");\n JPanel panel = new JPanel();\n panel.setBackground(Color.blue);\n GridLayout layout = new GridLayout(3,3);\n layout.setVgap(30);\n panel.setLayout(layout);\n panel.add(new JButton(\"Overview\"));\n panel.add(new JButton(\"Samples\"));\n panel.add(new JButton(\"Tutorials\"));\n panel.add(new JButton(\"Support\"));\n panel.add(new JButton(\"InterviewQA\"));\n panel.add(new JButton(\"Tools\"));\n panel.add(new JButton(\"Editors\"));\n frame.add(panel);\n frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);\n frame.setSize(500, 300);\n frame.setVisible(true);\n }\n}" } ]
Boolean Algebraic Theorems - GeeksforGeeks
01 Apr, 2021 Boolean algebraic theorems are the theorems that are used to change the form of a boolean expression. Sometimes these theorems are used to minimize the terms of the expression, and sometimes they are used just to transfer the expression from one form to another. There are boolean algebraic theorems in digital logic: 1. De Morgan’s Theorem : DE Morgan’s Theorem represents two of the most important rules of boolean algebra. (i). (A . B)' = A' + B' Thus, the complement of the product of variables is equal to the sum of their individual complements. (ii). (A + B)' = A' . B' Thus, the complement of the sum of variables is equal to the product of their individual complements. The above two laws can be extended for n variables as (A1 . A2 . A3 ... An)' = A1' + A2' + ... + An' And (A1 + A2 + ... + An)' = A1' . A2' . A3' ... An' 2. Transposition Theorem : It states that: AB + A'C = (A + C) (A' + B) Proof: RHS = (A + C) (A' + B) = AA' + A'C + AB + CB = 0 + A'C + AB + BC = A'C + AB + BC(A + A') = AB + ABC + A'C + A'BC = AB + A'C = LHS 3. Redundancy Theorem : This theorem is used to eliminate the redundant terms. A variable is associated with some variable and its complement is associated with some other variable and the next term is formed by the left over variables, then the term becomes redundant. Example: AB + BC' + AC = AC + BC' Proof: LHS = AB + BC' + AC = AB(C + C') + BC'(A + A') + AC(B + B') = ABC + ABC' + ABC' + A'BC' + ABC + AB'c = ABC + ABC' + A'BC' + AB'C = AC(B + B') + BC'(A + A') = AC + BC' = RHS 4. Duality Theorem : Dual expression is equivalent to write a negative logic of the given boolean relation. For this, Change each OR sign by and AND sign and vice-versa. Complement any 0 or 1 appearing in the expression. Keep literals as it is. Change each OR sign by and AND sign and vice-versa. Complement any 0 or 1 appearing in the expression. Keep literals as it is. Example: Dual of A(B+C) = A+(B.C) = (A+B)(A+C) 5. Complementary Theorem : For obtaining complement expression, Change each OR sign by AND sign and vice-versa. Complement any 0 or 1 appearing in the expression. Complement the individual literals. Change each OR sign by AND sign and vice-versa. Complement any 0 or 1 appearing in the expression. Complement the individual literals. Example: Complement of A(B+C) = A'+(B'.C') = (A'+B')(A'+C') sk944795 Digital Electronics & Logic Design Engineering Mathematics GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to memory and memory units Analog to Digital Conversion Introduction of Sequential Circuits Latches in Digital Logic Restoring Division Algorithm For Unsigned Integer Inequalities in LaTeX Relationship between number of nodes and height of binary tree Activation Functions Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph Arrow Symbols in LaTeX
[ { "code": null, "e": 25706, "s": 25678, "text": "\n01 Apr, 2021" }, { "code": null, "e": 25970, "s": 25706, "text": "Boolean algebraic theorems are the theorems that are used to change the form of a boolean expression. Sometimes these theorems are used to minimize the terms of the expression, and sometimes they are used just to transfer the expression from one form to another. " }, { "code": null, "e": 26026, "s": 25970, "text": "There are boolean algebraic theorems in digital logic: " }, { "code": null, "e": 26135, "s": 26026, "text": "1. De Morgan’s Theorem : DE Morgan’s Theorem represents two of the most important rules of boolean algebra. " }, { "code": null, "e": 26160, "s": 26135, "text": "(i). (A . B)' = A' + B' " }, { "code": null, "e": 26264, "s": 26160, "text": "Thus, the complement of the product of variables is equal to the sum of their individual complements. " }, { "code": null, "e": 26290, "s": 26264, "text": "(ii). (A + B)' = A' . B' " }, { "code": null, "e": 26393, "s": 26290, "text": "Thus, the complement of the sum of variables is equal to the product of their individual complements. " }, { "code": null, "e": 26448, "s": 26393, "text": "The above two laws can be extended for n variables as " }, { "code": null, "e": 26550, "s": 26448, "text": "(A1 . A2 . A3 ... An)' = A1' + A2' + ... + An'\n\nAnd\n\n(A1 + A2 + ... + An)' = A1' . A2' . A3' ... An' " }, { "code": null, "e": 26594, "s": 26550, "text": "2. Transposition Theorem : It states that: " }, { "code": null, "e": 26622, "s": 26594, "text": "AB + A'C = (A + C) (A' + B)" }, { "code": null, "e": 26630, "s": 26622, "text": "Proof: " }, { "code": null, "e": 26762, "s": 26630, "text": "RHS \n= (A + C) (A' + B)\n= AA' + A'C + AB + CB\n= 0 + A'C + AB + BC\n= A'C + AB + BC(A + A')\n= AB + ABC + A'C + A'BC\n= AB + A'C\n= LHS " }, { "code": null, "e": 27033, "s": 26762, "text": "3. Redundancy Theorem : This theorem is used to eliminate the redundant terms. A variable is associated with some variable and its complement is associated with some other variable and the next term is formed by the left over variables, then the term becomes redundant. " }, { "code": null, "e": 27043, "s": 27033, "text": "Example: " }, { "code": null, "e": 27069, "s": 27043, "text": "AB + BC' + AC = AC + BC' " }, { "code": null, "e": 27077, "s": 27069, "text": "Proof: " }, { "code": null, "e": 27252, "s": 27077, "text": "LHS \n= AB + BC' + AC\n= AB(C + C') + BC'(A + A') + AC(B + B')\n= ABC + ABC' + ABC' + A'BC' + ABC + AB'c\n= ABC + ABC' + A'BC' + AB'C\n= AC(B + B') + BC'(A + A')\n= AC + BC'\n= RHS " }, { "code": null, "e": 27371, "s": 27252, "text": "4. Duality Theorem : Dual expression is equivalent to write a negative logic of the given boolean relation. For this, " }, { "code": null, "e": 27500, "s": 27371, "text": "Change each OR sign by and AND sign and vice-versa. Complement any 0 or 1 appearing in the expression. Keep literals as it is. " }, { "code": null, "e": 27553, "s": 27500, "text": "Change each OR sign by and AND sign and vice-versa. " }, { "code": null, "e": 27605, "s": 27553, "text": "Complement any 0 or 1 appearing in the expression. " }, { "code": null, "e": 27631, "s": 27605, "text": "Keep literals as it is. " }, { "code": null, "e": 27641, "s": 27631, "text": "Example: " }, { "code": null, "e": 27679, "s": 27641, "text": "Dual of A(B+C) = A+(B.C) = (A+B)(A+C)" }, { "code": null, "e": 27744, "s": 27679, "text": "5. Complementary Theorem : For obtaining complement expression, " }, { "code": null, "e": 27881, "s": 27744, "text": "Change each OR sign by AND sign and vice-versa. Complement any 0 or 1 appearing in the expression. Complement the individual literals. " }, { "code": null, "e": 27930, "s": 27881, "text": "Change each OR sign by AND sign and vice-versa. " }, { "code": null, "e": 27982, "s": 27930, "text": "Complement any 0 or 1 appearing in the expression. " }, { "code": null, "e": 28020, "s": 27982, "text": "Complement the individual literals. " }, { "code": null, "e": 28030, "s": 28020, "text": "Example: " }, { "code": null, "e": 28081, "s": 28030, "text": "Complement of A(B+C) = A'+(B'.C') = (A'+B')(A'+C')" }, { "code": null, "e": 28090, "s": 28081, "text": "sk944795" }, { "code": null, "e": 28125, "s": 28090, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 28149, "s": 28125, "text": "Engineering Mathematics" }, { "code": null, "e": 28157, "s": 28149, "text": "GATE CS" }, { "code": null, "e": 28255, "s": 28157, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28295, "s": 28255, "text": "Introduction to memory and memory units" }, { "code": null, "e": 28324, "s": 28295, "text": "Analog to Digital Conversion" }, { "code": null, "e": 28360, "s": 28324, "text": "Introduction of Sequential Circuits" }, { "code": null, "e": 28385, "s": 28360, "text": "Latches in Digital Logic" }, { "code": null, "e": 28435, "s": 28385, "text": "Restoring Division Algorithm For Unsigned Integer" }, { "code": null, "e": 28457, "s": 28435, "text": "Inequalities in LaTeX" }, { "code": null, "e": 28520, "s": 28457, "text": "Relationship between number of nodes and height of binary tree" }, { "code": null, "e": 28541, "s": 28520, "text": "Activation Functions" }, { "code": null, "e": 28606, "s": 28541, "text": "Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph" } ]
Difference between hardware serial and software serial in Arduino
A hardware serial, as the name suggests, denotes that a dedicated piece of hardware (UART) enables Serial communication. In Arduino Uno, for instance, pins 0 and 1 have UART support,and they are connected to the USB via a USB-to-UART converter. That facilitates communication between your computer/laptop and the Arduino. While Arduino Uno has a single Hardware Serial, other boards like Mega have multiple. They are accessed using Serial, Serial1, Serial2, and so on. You can have a look at an example of using Multiple Hardware Serials by going to File β†’ Examples β†’ Communication β†’ MultiSerial Software serial is a library that replicates the hardware serial behavior on other digital pins of the Arduino, using (you guessed it) software. You can have more than one software serials running in parallel, with the limitation being that only one can receive data at a time. The SoftwareSerial library is inbuilt from Arduino IDE 1.0 and above. To use it, all you need to include is βˆ’ #include <SoftwareSerial.h> The other limitations (board specific) of SoftwareSerial library can be found here. Speeds up to 115200 bps are possible using the SoftwareSerial library. You can find examples related to the usage of SoftwareSerial by going to File β†’ Examples β†’SoftwareSerial
[ { "code": null, "e": 1531, "s": 1062, "text": "A hardware serial, as the name suggests, denotes that a dedicated piece of hardware (UART) enables Serial communication. In Arduino Uno, for instance, pins 0 and 1 have UART support,and they are connected to the USB via a USB-to-UART converter. That facilitates communication between your computer/laptop and the Arduino. While Arduino Uno has a single Hardware Serial, other boards like Mega have multiple. They are accessed using Serial,\nSerial1, Serial2, and so on." }, { "code": null, "e": 1658, "s": 1531, "text": "You can have a look at an example of using Multiple Hardware Serials by going to File β†’ Examples β†’ Communication β†’ MultiSerial" }, { "code": null, "e": 1936, "s": 1658, "text": "Software serial is a library that replicates the hardware serial behavior on other digital pins of the Arduino, using (you guessed it) software. You can have more than one software serials running in parallel, with the limitation being that only one can receive data at a time." }, { "code": null, "e": 2046, "s": 1936, "text": "The SoftwareSerial library is inbuilt from Arduino IDE 1.0 and above. To use it, all you need to include is βˆ’" }, { "code": null, "e": 2074, "s": 2046, "text": "#include <SoftwareSerial.h>" }, { "code": null, "e": 2158, "s": 2074, "text": "The other limitations (board specific) of SoftwareSerial library can be found here." }, { "code": null, "e": 2334, "s": 2158, "text": "Speeds up to 115200 bps are possible using the SoftwareSerial library. You can find examples related to the usage of SoftwareSerial by going to File β†’ Examples β†’SoftwareSerial" } ]
Mastering User Management on Linux
Are you working as Linux admin? Do you create/delete users in Linux Command line? If yes, then this article is for you guys! After reading the below content, you will be able to manipulate users and group permissions in Linux system. In the below example sai is the username. The usermod command modifies the approach account records to reflect the alterations which can be targeted on the command line. To get more information about usermod, use the following command – $ usermod --help The sample output should be like this – -c, --comment COMMENT new value of the GECOS field -d, --home HOME_DIR new home directory for the user account -e, --expiredate EXPIRE_DATE set account expiration date to EXPIRE_DATE -f, --inactive INACTIVE set password inactive after expiration to INACTIVE -g, --gid GROUP force use GROUP as new primary group -G, --groups GROUPS new list of supplementary GROUPS -a, --append append the user to the supplemental GROUPS mentioned by the -G option without removing him/her from other groups ..................................................................... The usage of usermod should be like this – $sudo usermod [options] [user Name] To create a new home directory for the user account, use the following command – $ sudo usermod --home /home sai To set account expiration date to EXPIRE_DATE, use the following command – $ sudo usermod --expiredate 20017-2-24 sai To lock the user account, use the following command – $ sudo usermod --lock sai To unlock the user account, use the following command – $ sudo usermod --unlock sai To set the password for the user, use the following command – $ sudo usermod --password 123456 sai To add the user to group, use the following command – $ sudo usermod --append --groups root,users sai Useradd is a low degree utility for adding users. On Debian, Admins normally use adduser to create the users on Linux system. To get more information about user add, use the following command – $ sudo useradd --help The sample output should be like this – -b, --base-dir BASE_DIR base directory for the home directory of the new account -c, --comment COMMENT GECOS field of the new account -d, --home-dir HOME_DIR home directory of the new account -D, --defaults print or change default useradd configuration -e, --expiredate EXPIRE_DATE expiration date of the new account -f, --inactive INACTIVE password inactivity period of the new account -g, --gid GROUP name or ID of the primary group of the new account ..................................................................................... The usage of useradd, should be like as shown below – $ sudo useradd [options] [user name] To create base directory for new account, use the following command – $ sudo useradd --base-dir /tmp sai To create home directory of the new account, use the following command – $ sudo useradd --home-dir /home sai To set account expiration date to EXPIRE_DATE, use the following command – $ sudo useradd --expiredate 20017-2-24 sai To set the password for the user, use the following command – $ sudo useradd --password 123456 sai To add the user to group, use the following command – $ sudo usermod --append --groups root,users sai Userdel is a low-level utility for disposing of users On Debian, Linux admins most of the time use deluser to delete a consumer on Linux. To get the more information about userdel, use the following command – $ userdel --help The sample output should be like this – -f, --force force removal of files, even if not owned by user -h, --help display this help message and exit -r, --remove remove home directory and mail spool -R, --root CHROOT_DIR directory to chroot into -Z, --selinux-user remove any SELinux user mapping for the user The usage of userdel should be like this – $sudo userdel [options] [user name] To delete the user, use the following command – $ sudo userdel sai To delete the user with files, use the following command – $ sudo userdel --force sai To remove the user of home directory, use the following command $ sudo userdel --remove sai To change the time the user’s password will expire, use the following command as shown below – $ sudo chage sai The sample output should be like this – Changing the aging information for sai Enter the new value, or press ENTER for the default Minimum Password Age [0]: 20 Maximum Password Age [99999]: 20 Last Password Change (YYYY-MM-DD) [2017-02-01]: Password Expiration Warning [7]: 7 Password Inactive [-1]: -1 Account Expiration Date (YYYY-MM-DD) [-1]: 2017-02-28 To change the user full name field finger information, use the following command as shown below – $ sudo chfn sai The sample output should be like this – Changing the user information for sai Enter the new value, or press ENTER for the default Full Name [sai]: sairamkrishna mammahe Room Number []: Work Phone []: Home Phone []: Other []: To change the owner of file(s ) to another user.In the below command, we are changing owner file of home directory to sai(user) as shown below – $ sudo chown sai /home To examine faillog, use the following command as shown below – $ sudo faillog -a The sample output should be like this – Login Failures Maximum Latest On root 0 0 01/01/70 05:30:00 +0530 daemon 0 0 01/01/70 05:30:00 +0530 bin 0 0 01/01/70 05:30:00 +0530 sys 0 0 01/01/70 05:30:00 +0530 sync 0 0 01/01/70 05:30:00 +0530 games 0 0 01/01/70 05:30:00 +0530 man 0 0 01/01/70 05:30:00 +0530 lp 0 0 01/01/70 05:30:00 +0530 mail 0 0 01/01/70 05:30:00 +0530 news 0 0 01/01/70 05:30:00 +0530 uucp 0 0 01/01/70 05:30:00 +0530 ....................................................................... To create a new group, use the following command as shown below – $ sudo groupadd sai In the above command sai is the group name. To verify the integrity of group files. use the following command as shown below – $ sudo grpck To delete a group, use the following command as shown below – $ sudo groupdel sai To print the groups a user is in, use the following command as shown below – $ sudo groups The sample output should be like this – root To print real and effective user id and group ids, use the following command as shown below – $ sudo id The sample output should be like this – uid=0(root) gid=0(root) groups=0(root) To display the last users logged on and how long, use the following command as shown below – $ sudo last The sample output should be like this – linux tty7 :0 Wed Feb 1 09:49 gone - no logout reboot system boot 4.4.0-59-generic Wed Feb 1 09:48 still running guest-er tty8 :1 Mon Jan 30 15:47 - down (00:00) linux tty7 :0 Fri Jan 27 09:33 - down (3+06:15) reboot system boot 4.4.0-59-generic Fri Jan 27 09:32 - 15:48 (3+06:16) linux tty7 :0 Mon Jan 23 09:10 - down (2+08:51) reboot system boot 4.4.0-59-generic Mon Jan 23 09:09 - 18:01 (2+08:52) linux tty7 :0 Fri Jan 20 09:17 - crash (2+23:51) reboot system boot 4.4.0-59-generic Fri Jan 20 09:17 - 18:01 (5+08:44) linux tty7 :0 Wed Jan 18 14:21 - down (03:38) ........................................................................... To should the failed login attempts, use the following command as shown below – $ sudo lastb The sample output should be like this – linux tty8 :1 Wed Jan 25 11:16 - 11:16 (00:00) sai tty8 :1 Wed Jan 25 11:15 - 11:15 (00:00) sai Wed Jan 25 11:15 - 11:15 (00:00) linux tty8 :1 Wed Jan 25 11:15 - 11:15 (00:00) sai tty8 :1 Wed Jan 25 11:15 - 11:15 (00:00) sai tty8 :1 Wed Jan 25 11:15 - 11:15 (00:00) sai Wed Jan 25 11:14 - 11:14 (00:00) linux tty7 :0 Mon Jan 9 11:04 - 11:04 (00:00) btmp begins Mon Jan 9 11:04:59 2017 To login with root, use the following command as shown below – $ sudo sulogin The sample output should be like this – Give root password for maintenance (or press Control-D to continue): To display users logged in and what they are doing, use the following command as shown below – $ sudo w The sample output should be like this – 11:45:38 up 1:57, 1 user, load average: 0.10, 0.39, 0.37 USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT linux tty7 :0 09:49 1:57m 3:22 0.28s /sbin/upstart - To display the users logged in, use the following command as shown below – $sudo who The sample output should be like this – linux tty7 2017-02-01 09:49 (:0) To display the user id infromation, use the following command as shown below – $sudo whoami The sample output should be like this – root In this article, we have learnt about – Mastering user management on Linux, we will come up with more Linux based tricks and tips. Keep reading!
[ { "code": null, "e": 1296, "s": 1062, "text": "Are you working as Linux admin? Do you create/delete users in Linux Command line? If yes, then this article is for you guys! After reading the below content, you will be able to manipulate users and group permissions in Linux system." }, { "code": null, "e": 1338, "s": 1296, "text": "In the below example sai is the username." }, { "code": null, "e": 1466, "s": 1338, "text": "The usermod command modifies the approach account records to reflect the alterations which can be targeted on the command line." }, { "code": null, "e": 1533, "s": 1466, "text": "To get more information about usermod, use the following command –" }, { "code": null, "e": 1550, "s": 1533, "text": "$ usermod --help" }, { "code": null, "e": 1590, "s": 1550, "text": "The sample output should be like this –" }, { "code": null, "e": 2237, "s": 1590, "text": "-c, --comment COMMENT new value of the GECOS field\n-d, --home HOME_DIR new home directory for the user account\n-e, --expiredate EXPIRE_DATE set account expiration date to EXPIRE_DATE\n-f, --inactive INACTIVE set password inactive after expiration to INACTIVE\n-g, --gid GROUP force use GROUP as new primary group\n-G, --groups GROUPS new list of supplementary GROUPS\n-a, --append append the user to the supplemental GROUPS\n mentioned by the -G option without removing\n him/her from other groups\n....................................................................." }, { "code": null, "e": 2280, "s": 2237, "text": "The usage of usermod should be like this –" }, { "code": null, "e": 2316, "s": 2280, "text": "$sudo usermod [options] [user Name]" }, { "code": null, "e": 2397, "s": 2316, "text": "To create a new home directory for the user account, use the following command –" }, { "code": null, "e": 2429, "s": 2397, "text": "$ sudo usermod --home /home sai" }, { "code": null, "e": 2504, "s": 2429, "text": "To set account expiration date to EXPIRE_DATE, use the following command –" }, { "code": null, "e": 2547, "s": 2504, "text": "$ sudo usermod --expiredate 20017-2-24 sai" }, { "code": null, "e": 2601, "s": 2547, "text": "To lock the user account, use the following command –" }, { "code": null, "e": 2627, "s": 2601, "text": "$ sudo usermod --lock sai" }, { "code": null, "e": 2683, "s": 2627, "text": "To unlock the user account, use the following command –" }, { "code": null, "e": 2711, "s": 2683, "text": "$ sudo usermod --unlock sai" }, { "code": null, "e": 2773, "s": 2711, "text": "To set the password for the user, use the following command –" }, { "code": null, "e": 2810, "s": 2773, "text": "$ sudo usermod --password 123456 sai" }, { "code": null, "e": 2864, "s": 2810, "text": "To add the user to group, use the following command –" }, { "code": null, "e": 2912, "s": 2864, "text": "$ sudo usermod --append --groups root,users sai" }, { "code": null, "e": 3038, "s": 2912, "text": "Useradd is a low degree utility for adding users. On Debian, Admins normally use adduser to create the users on Linux system." }, { "code": null, "e": 3106, "s": 3038, "text": "To get more information about user add, use the following command –" }, { "code": null, "e": 3128, "s": 3106, "text": "$ sudo useradd --help" }, { "code": null, "e": 3168, "s": 3128, "text": "The sample output should be like this –" }, { "code": null, "e": 3733, "s": 3168, "text": "-b, --base-dir BASE_DIR base directory for the home directory of the new account\n-c, --comment COMMENT GECOS field of the new account\n-d, --home-dir HOME_DIR home directory of the new account\n-D, --defaults print or change default useradd configuration\n-e, --expiredate EXPIRE_DATE expiration date of the new account\n-f, --inactive INACTIVE password inactivity period of the new account\n-g, --gid GROUP name or ID of the primary group of the new\naccount\n....................................................................................." }, { "code": null, "e": 3787, "s": 3733, "text": "The usage of useradd, should be like as shown below –" }, { "code": null, "e": 3824, "s": 3787, "text": "$ sudo useradd [options] [user name]" }, { "code": null, "e": 3894, "s": 3824, "text": "To create base directory for new account, use the following command –" }, { "code": null, "e": 3929, "s": 3894, "text": "$ sudo useradd --base-dir /tmp sai" }, { "code": null, "e": 4002, "s": 3929, "text": "To create home directory of the new account, use the following command –" }, { "code": null, "e": 4038, "s": 4002, "text": "$ sudo useradd --home-dir /home sai" }, { "code": null, "e": 4113, "s": 4038, "text": "To set account expiration date to EXPIRE_DATE, use the following command –" }, { "code": null, "e": 4156, "s": 4113, "text": "$ sudo useradd --expiredate 20017-2-24 sai" }, { "code": null, "e": 4218, "s": 4156, "text": "To set the password for the user, use the following command –" }, { "code": null, "e": 4255, "s": 4218, "text": "$ sudo useradd --password 123456 sai" }, { "code": null, "e": 4309, "s": 4255, "text": "To add the user to group, use the following command –" }, { "code": null, "e": 4357, "s": 4309, "text": "$ sudo usermod --append --groups root,users sai" }, { "code": null, "e": 4495, "s": 4357, "text": "Userdel is a low-level utility for disposing of users On Debian, Linux admins most of the time use deluser to delete a consumer on Linux." }, { "code": null, "e": 4566, "s": 4495, "text": "To get the more information about userdel, use the following command –" }, { "code": null, "e": 4583, "s": 4566, "text": "$ userdel --help" }, { "code": null, "e": 4623, "s": 4583, "text": "The sample output should be like this –" }, { "code": null, "e": 4946, "s": 4623, "text": "-f, --force force removal of files,\n even if not owned by user\n-h, --help display this help message and exit\n-r, --remove remove home directory and mail spool\n-R, --root CHROOT_DIR directory to chroot into\n-Z, --selinux-user remove any SELinux user mapping for the user" }, { "code": null, "e": 4989, "s": 4946, "text": "The usage of userdel should be like this –" }, { "code": null, "e": 5025, "s": 4989, "text": "$sudo userdel [options] [user name]" }, { "code": null, "e": 5073, "s": 5025, "text": "To delete the user, use the following command –" }, { "code": null, "e": 5092, "s": 5073, "text": "$ sudo userdel sai" }, { "code": null, "e": 5151, "s": 5092, "text": "To delete the user with files, use the following command –" }, { "code": null, "e": 5178, "s": 5151, "text": "$ sudo userdel --force sai" }, { "code": null, "e": 5242, "s": 5178, "text": "To remove the user of home directory, use the following command" }, { "code": null, "e": 5270, "s": 5242, "text": "$ sudo userdel --remove sai" }, { "code": null, "e": 5365, "s": 5270, "text": "To change the time the user’s password will expire, use the following command as shown below –" }, { "code": null, "e": 5382, "s": 5365, "text": "$ sudo chage sai" }, { "code": null, "e": 5422, "s": 5382, "text": "The sample output should be like this –" }, { "code": null, "e": 5758, "s": 5422, "text": "Changing the aging information for sai\nEnter the new value, or press ENTER for the default\n\n Minimum Password Age [0]: 20\n Maximum Password Age [99999]: 20\n Last Password Change (YYYY-MM-DD) [2017-02-01]:\n Password Expiration Warning [7]: 7\n Password Inactive [-1]: -1\n Account Expiration Date (YYYY-MM-DD) [-1]: 2017-02-28" }, { "code": null, "e": 5856, "s": 5758, "text": "To change the user full name field finger information, use the following command as shown below –" }, { "code": null, "e": 5872, "s": 5856, "text": "$ sudo chfn sai" }, { "code": null, "e": 5912, "s": 5872, "text": "The sample output should be like this –" }, { "code": null, "e": 6112, "s": 5912, "text": "Changing the user information for sai\nEnter the new value, or press ENTER for the default\n Full Name [sai]: sairamkrishna mammahe\n Room Number []:\n Work Phone []:\n Home Phone []:\n Other []:" }, { "code": null, "e": 6257, "s": 6112, "text": "To change the owner of file(s ) to another user.In the below command, we are changing owner file of home directory to sai(user) as shown below –" }, { "code": null, "e": 6280, "s": 6257, "text": "$ sudo chown sai /home" }, { "code": null, "e": 6343, "s": 6280, "text": "To examine faillog, use the following command as shown below –" }, { "code": null, "e": 6361, "s": 6343, "text": "$ sudo faillog -a" }, { "code": null, "e": 6401, "s": 6361, "text": "The sample output should be like this –" }, { "code": null, "e": 7306, "s": 6401, "text": "Login Failures Maximum Latest On\n\nroot 0 0 01/01/70 05:30:00 +0530\ndaemon 0 0 01/01/70 05:30:00 +0530\nbin 0 0 01/01/70 05:30:00 +0530\nsys 0 0 01/01/70 05:30:00 +0530\nsync 0 0 01/01/70 05:30:00 +0530\ngames 0 0 01/01/70 05:30:00 +0530\nman 0 0 01/01/70 05:30:00 +0530\nlp 0 0 01/01/70 05:30:00 +0530\nmail 0 0 01/01/70 05:30:00 +0530\nnews 0 0 01/01/70 05:30:00 +0530\nuucp 0 0 01/01/70 05:30:00 +0530\n......................................................................." }, { "code": null, "e": 7372, "s": 7306, "text": "To create a new group, use the following command as shown below –" }, { "code": null, "e": 7392, "s": 7372, "text": "$ sudo groupadd sai" }, { "code": null, "e": 7436, "s": 7392, "text": "In the above command sai is the group name." }, { "code": null, "e": 7519, "s": 7436, "text": "To verify the integrity of group files. use the following command as shown below –" }, { "code": null, "e": 7532, "s": 7519, "text": "$ sudo grpck" }, { "code": null, "e": 7594, "s": 7532, "text": "To delete a group, use the following command as shown below –" }, { "code": null, "e": 7614, "s": 7594, "text": "$ sudo groupdel sai" }, { "code": null, "e": 7691, "s": 7614, "text": "To print the groups a user is in, use the following command as shown below –" }, { "code": null, "e": 7705, "s": 7691, "text": "$ sudo groups" }, { "code": null, "e": 7745, "s": 7705, "text": "The sample output should be like this –" }, { "code": null, "e": 7750, "s": 7745, "text": "root" }, { "code": null, "e": 7844, "s": 7750, "text": "To print real and effective user id and group ids, use the following command as shown below –" }, { "code": null, "e": 7854, "s": 7844, "text": "$ sudo id" }, { "code": null, "e": 7894, "s": 7854, "text": "The sample output should be like this –" }, { "code": null, "e": 7933, "s": 7894, "text": "uid=0(root) gid=0(root) groups=0(root)" }, { "code": null, "e": 8026, "s": 7933, "text": "To display the last users logged on and how long, use the following command as shown below –" }, { "code": null, "e": 8038, "s": 8026, "text": "$ sudo last" }, { "code": null, "e": 8078, "s": 8038, "text": "The sample output should be like this –" }, { "code": null, "e": 8720, "s": 8078, "text": "linux tty7 :0 Wed Feb 1 09:49 gone - no logout\nreboot system boot 4.4.0-59-generic Wed Feb 1 09:48 still running\nguest-er tty8 :1 Mon Jan 30 15:47 - down (00:00)\nlinux tty7 :0 Fri Jan 27 09:33 - down (3+06:15)\nreboot system boot 4.4.0-59-generic Fri Jan 27 09:32 - 15:48 (3+06:16)\nlinux tty7 :0 Mon Jan 23 09:10 - down (2+08:51)\nreboot system boot 4.4.0-59-generic Mon Jan 23 09:09 - 18:01 (2+08:52)\nlinux tty7 :0 Fri Jan 20 09:17 - crash (2+23:51)\nreboot system boot 4.4.0-59-generic Fri Jan 20 09:17 - 18:01 (5+08:44)\nlinux tty7 :0 Wed Jan 18 14:21 - down (03:38)\n..........................................................................." }, { "code": null, "e": 8800, "s": 8720, "text": "To should the failed login attempts, use the following command as shown below –" }, { "code": null, "e": 8813, "s": 8800, "text": "$ sudo lastb" }, { "code": null, "e": 8853, "s": 8813, "text": "The sample output should be like this –" }, { "code": null, "e": 9239, "s": 8853, "text": "linux tty8 :1 Wed Jan 25 11:16 - 11:16 (00:00)\nsai tty8 :1 Wed Jan 25 11:15 - 11:15 (00:00)\nsai Wed Jan 25 11:15 - 11:15 (00:00)\nlinux tty8 :1 Wed Jan 25 11:15 - 11:15 (00:00)\nsai tty8 :1 Wed Jan 25 11:15 - 11:15 (00:00)\nsai tty8 :1 Wed Jan 25 11:15 - 11:15 (00:00)\nsai Wed Jan 25 11:14 - 11:14 (00:00)\nlinux tty7 :0 Mon Jan 9 11:04 - 11:04 (00:00)\n\nbtmp begins Mon Jan 9 11:04:59 2017" }, { "code": null, "e": 9302, "s": 9239, "text": "To login with root, use the following command as shown below –" }, { "code": null, "e": 9317, "s": 9302, "text": "$ sudo sulogin" }, { "code": null, "e": 9357, "s": 9317, "text": "The sample output should be like this –" }, { "code": null, "e": 9426, "s": 9357, "text": "Give root password for maintenance\n(or press Control-D to continue):" }, { "code": null, "e": 9521, "s": 9426, "text": "To display users logged in and what they are doing, use the following command as shown below –" }, { "code": null, "e": 9530, "s": 9521, "text": "$ sudo w" }, { "code": null, "e": 9570, "s": 9530, "text": "The sample output should be like this –" }, { "code": null, "e": 9721, "s": 9570, "text": "11:45:38 up 1:57, 1 user, load average: 0.10, 0.39, 0.37\nUSER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT\nlinux tty7 :0 09:49 1:57m 3:22 0.28s /sbin/upstart -" }, { "code": null, "e": 9796, "s": 9721, "text": "To display the users logged in, use the following command as shown below –" }, { "code": null, "e": 9806, "s": 9796, "text": "$sudo who" }, { "code": null, "e": 9846, "s": 9806, "text": "The sample output should be like this –" }, { "code": null, "e": 9879, "s": 9846, "text": "linux tty7 2017-02-01 09:49 (:0)" }, { "code": null, "e": 9958, "s": 9879, "text": "To display the user id infromation, use the following command as shown below –" }, { "code": null, "e": 9971, "s": 9958, "text": "$sudo whoami" }, { "code": null, "e": 10011, "s": 9971, "text": "The sample output should be like this –" }, { "code": null, "e": 10016, "s": 10011, "text": "root" }, { "code": null, "e": 10161, "s": 10016, "text": "In this article, we have learnt about – Mastering user management on Linux, we will come up with more Linux based tricks and tips. Keep reading!" } ]
C - nested if statements
It is always legal in C programming to nest if-else statements, which means you can use one if or else if statement inside another if or else if statement(s). The syntax for a nested if statement is as follows βˆ’ if( boolean_expression 1) { /* Executes when the boolean expression 1 is true */ if(boolean_expression 2) { /* Executes when the boolean expression 2 is true */ } } You can nest else if...else in the similar way as you have nested if statements. #include <stdio.h> int main () { /* local variable definition */ int a = 100; int b = 200; /* check the boolean condition */ if( a == 100 ) { /* if condition is true then check the following */ if( b == 200 ) { /* if condition is true then print the following */ printf("Value of a is 100 and b is 200\n" ); } } printf("Exact value of a is : %d\n", a ); printf("Exact value of b is : %d\n", b ); return 0; } When the above code is compiled and executed, it produces the following result βˆ’ Value of a is 100 and b is 200 Exact value of a is : 100 Exact value of b is : 200 Print Add Notes Bookmark this page
[ { "code": null, "e": 2243, "s": 2084, "text": "It is always legal in C programming to nest if-else statements, which means you can use one if or else if statement inside another if or else if statement(s)." }, { "code": null, "e": 2296, "s": 2243, "text": "The syntax for a nested if statement is as follows βˆ’" }, { "code": null, "e": 2478, "s": 2296, "text": "if( boolean_expression 1) {\n\n /* Executes when the boolean expression 1 is true */\n if(boolean_expression 2) {\n /* Executes when the boolean expression 2 is true */\n }\n}\n" }, { "code": null, "e": 2559, "s": 2478, "text": "You can nest else if...else in the similar way as you have nested if statements." }, { "code": null, "e": 3045, "s": 2559, "text": "#include <stdio.h>\n \nint main () {\n\n /* local variable definition */\n int a = 100;\n int b = 200;\n \n /* check the boolean condition */\n if( a == 100 ) {\n \n /* if condition is true then check the following */\n if( b == 200 ) {\n /* if condition is true then print the following */\n printf(\"Value of a is 100 and b is 200\\n\" );\n }\n }\n \n printf(\"Exact value of a is : %d\\n\", a );\n printf(\"Exact value of b is : %d\\n\", b );\n \n return 0;\n}" }, { "code": null, "e": 3126, "s": 3045, "text": "When the above code is compiled and executed, it produces the following result βˆ’" }, { "code": null, "e": 3210, "s": 3126, "text": "Value of a is 100 and b is 200\nExact value of a is : 100\nExact value of b is : 200\n" }, { "code": null, "e": 3217, "s": 3210, "text": " Print" }, { "code": null, "e": 3228, "s": 3217, "text": " Add Notes" } ]
Algorithm for non recursive Predictive Parsing - GeeksforGeeks
24 May, 2021 Prerequisite – Classification of Top Down Parsers Predictive parsing is a special form of recursive descent parsing, where no backtracking is required, so this can predict which products to use to replace the input string. Non-recursive predictive parsing or table-driven is also known as LL(1) parser. This parser follows the leftmost derivation (LMD). LL(1): here, first L is for Left to Right scanning of inputs, the second L is for left most derivation procedure, 1 = Number of Look Ahead Symbols The main problem during predictive parsing is that of determining the production to be applied for a non-terminal. This non-recursive parser looks up which product to be applied in a parsing table. A LL(1) parser has the following components: (1) buffer: an input buffer which contains the string to be passed (2) stack: a pushdown stack which contains a sequence of grammar symbols (3) A parsing table: a 2d array M[A, a] where A->non-terminal, a->terminal or $ (4) output stream: end of the stack and an end of the input symbols are both denoted with $ Algorithm for non recursive Predictive Parsing: The main Concept ->With the help of FIRST() and FOLLOW() sets, this parsing can be done using just a stack that avoids the recursive calls. For each rule, A->x in grammar G: For each terminal β€˜a’ contained in FIRST(A) add A->x to M[A, a] in the parsing table if x derives β€˜a’ as the first symbol. If FIRST(A) contains null production for each terminal β€˜b’ in FOLLOW(A), add this production (A->null) to M[A, b] in the parsing table. For each terminal β€˜a’ contained in FIRST(A) add A->x to M[A, a] in the parsing table if x derives β€˜a’ as the first symbol. If FIRST(A) contains null production for each terminal β€˜b’ in FOLLOW(A), add this production (A->null) to M[A, b] in the parsing table. The Procedure: In the beginning, the pushdown stack holds the start symbol of the grammar G. At each step a symbol X is popped from the stack: if X is a terminal then it is matched with the lookahead and lookahead is advanced one step, if X is a nonterminal symbol, then using lookahead and a parsing table (implementing the FIRST sets) a production is chosen and its right-hand side is pushed into the stack. This process repeats until the stack and the input string become null (empty). In the beginning, the pushdown stack holds the start symbol of the grammar G. At each step a symbol X is popped from the stack: if X is a terminal then it is matched with the lookahead and lookahead is advanced one step, if X is a nonterminal symbol, then using lookahead and a parsing table (implementing the FIRST sets) a production is chosen and its right-hand side is pushed into the stack. This process repeats until the stack and the input string become null (empty). Table-driven Parsing algorithm: Input: a string w and a parsing table M for G. tos top of the stack Stack[tos++] <-$ Stack[tos++] <-Start Symbol token <-next_token() X <-Stack[tos] repeat if X is a terminal or $ then if X = token then pop X token is next of token() else error() else /* X is a non-terminal */ if M[x, token] = X -> y1y2...yk then pop x push else error() X Stack[tos] until X = $ // Non-recursive parser model diagram: So according to the given diagram the non-recursive parsing algorithm. Input: A input string β€˜w’ and a parsing table(β€˜M’) for grammar G. Output: If w is in L(G), an LMD of w; otherwise an error indication. Set input pointer to point to the first symbol of the string $; repeat let X be the symbol pointed by the stack pointer, and a is the symbol pointed to by input pointer; if X is a terminal or $ then if X=a then pop X from the stack and increment the input pointer; else error() end if else /*if X is a non terminal */ if then begin pop X from the stack; push onto the stack, with Y1 on top; output the production end else error() end if end if until X=$ /* stack is empty */ Example: Consider the subsequent LL(1) grammar: S -> A S -> ( S * A) A -> id Now let’s parse the given input: ( id * id ) The parsing table: row-> for each and every non-terminal symbol, column-> for each and every terminal (including the special terminal). Each cell of this table will contain at most one rule of the given grammar: Now let’s see using the algorithm, how the parser uses this parsing table to process the given input. Procedure: The parser thus ends because there remains only β€˜$’ on both its stack and its input stream. In this case, the parser reports that it has accepted the input string and writes the following list of rules to the output stream: S -> ( S * A), S -> A, A -> id, A -> id This is indeed a list of rules for an LMD of the input string, which is: S -> ( S * A ) -> ( A * A ) -> ( id * A ) -> ( id * id ) ruhelaa48 Compiler Design GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Intermediate Code Generation in Compiler Design Difference between Compiler and Interpreter Difference between Top down parsing and Bottom up parsing Loop Optimization in Compiler Design Input Buffering in Compiler Design Layers of OSI Model ACID Properties in DBMS Normal Forms in DBMS Types of Operating Systems Page Replacement Algorithms in Operating Systems
[ { "code": null, "e": 24414, "s": 24386, "text": "\n24 May, 2021" }, { "code": null, "e": 24770, "s": 24414, "text": "Prerequisite – Classification of Top Down Parsers Predictive parsing is a special form of recursive descent parsing, where no backtracking is required, so this can predict which products to use to replace the input string. Non-recursive predictive parsing or table-driven is also known as LL(1) parser. This parser follows the leftmost derivation (LMD). " }, { "code": null, "e": 24921, "s": 24770, "text": "LL(1):\nhere, first L is for Left to Right scanning of inputs,\n the second L is for left most derivation procedure,\n 1 = Number of Look Ahead Symbols " }, { "code": null, "e": 25165, "s": 24921, "text": "The main problem during predictive parsing is that of determining the production to be applied for a non-terminal. This non-recursive parser looks up which product to be applied in a parsing table. A LL(1) parser has the following components: " }, { "code": null, "e": 25490, "s": 25165, "text": "(1) buffer: an input buffer which contains the string to be passed \n(2) stack: a pushdown stack which contains a sequence of grammar symbols \n(3) A parsing table: a 2d array M[A, a] \n where\n A->non-terminal, a->terminal or $\n(4) output stream:\n end of the stack and an end of the input symbols are both denoted with $ " }, { "code": null, "e": 25679, "s": 25490, "text": "Algorithm for non recursive Predictive Parsing: The main Concept ->With the help of FIRST() and FOLLOW() sets, this parsing can be done using just a stack that avoids the recursive calls. " }, { "code": null, "e": 25715, "s": 25679, "text": "For each rule, A->x in grammar G: " }, { "code": null, "e": 25977, "s": 25715, "text": "For each terminal β€˜a’ contained in FIRST(A) add A->x to M[A, a] in the parsing table if x derives β€˜a’ as the first symbol. If FIRST(A) contains null production for each terminal β€˜b’ in FOLLOW(A), add this production (A->null) to M[A, b] in the parsing table. " }, { "code": null, "e": 26102, "s": 25977, "text": "For each terminal β€˜a’ contained in FIRST(A) add A->x to M[A, a] in the parsing table if x derives β€˜a’ as the first symbol. " }, { "code": null, "e": 26240, "s": 26102, "text": "If FIRST(A) contains null production for each terminal β€˜b’ in FOLLOW(A), add this production (A->null) to M[A, b] in the parsing table. " }, { "code": null, "e": 26257, "s": 26240, "text": "The Procedure: " }, { "code": null, "e": 26735, "s": 26257, "text": "In the beginning, the pushdown stack holds the start symbol of the grammar G. At each step a symbol X is popped from the stack: if X is a terminal then it is matched with the lookahead and lookahead is advanced one step, if X is a nonterminal symbol, then using lookahead and a parsing table (implementing the FIRST sets) a production is chosen and its right-hand side is pushed into the stack. This process repeats until the stack and the input string become null (empty). " }, { "code": null, "e": 26815, "s": 26735, "text": "In the beginning, the pushdown stack holds the start symbol of the grammar G. " }, { "code": null, "e": 27134, "s": 26815, "text": "At each step a symbol X is popped from the stack: if X is a terminal then it is matched with the lookahead and lookahead is advanced one step, if X is a nonterminal symbol, then using lookahead and a parsing table (implementing the FIRST sets) a production is chosen and its right-hand side is pushed into the stack. " }, { "code": null, "e": 27215, "s": 27134, "text": "This process repeats until the stack and the input string become null (empty). " }, { "code": null, "e": 27248, "s": 27215, "text": "Table-driven Parsing algorithm: " }, { "code": null, "e": 27297, "s": 27248, "text": "Input: a string w and a parsing table M for G. " }, { "code": null, "e": 27702, "s": 27297, "text": "tos top of the stack\nStack[tos++] <-$\nStack[tos++] <-Start Symbol\ntoken <-next_token()\nX <-Stack[tos]\n repeat\n if X is a terminal or $ then\n if X = token then\n pop X\n token is next of token() \n else error()\n else /* X is a non-terminal */\n if M[x, token] = X -> y1y2...yk then\n pop x\n push\n\n else error()\n\n X Stack[tos]\n\nuntil X = $ " }, { "code": null, "e": 27742, "s": 27702, "text": "// Non-recursive parser model diagram: " }, { "code": null, "e": 27816, "s": 27744, "text": "So according to the given diagram the non-recursive parsing algorithm. " }, { "code": null, "e": 27953, "s": 27816, "text": "Input: A input string β€˜w’ and a parsing table(β€˜M’) for grammar G. Output: If w is in L(G), an LMD of w; otherwise an error indication. " }, { "code": null, "e": 28515, "s": 27953, "text": "Set input pointer to point to the first symbol of the string $;\nrepeat\nlet X be the symbol pointed by the stack pointer,\nand a is the symbol pointed to by input pointer;\n if X is a terminal or $ then\n if X=a then\n pop X from the stack and increment the input pointer;\n else error()\n end if\n else /*if X is a non terminal */\n if then\n\n begin\n\n pop X from the stack;\n\n push onto the stack, with Y1 on top;\n\n output the production\n\n end\n\n else error()\n\n end if\n\n end if\n\n\n\nuntil X=$ /* stack is empty */ " }, { "code": null, "e": 28564, "s": 28515, "text": "Example: Consider the subsequent LL(1) grammar: " }, { "code": null, "e": 28597, "s": 28564, "text": "S -> A \nS -> ( S * A) \nA -> id " }, { "code": null, "e": 28631, "s": 28597, "text": "Now let’s parse the given input: " }, { "code": null, "e": 28644, "s": 28631, "text": "( id * id ) " }, { "code": null, "e": 28664, "s": 28644, "text": "The parsing table: " }, { "code": null, "e": 28711, "s": 28664, "text": "row-> for each and every non-terminal symbol, " }, { "code": null, "e": 28784, "s": 28711, "text": "column-> for each and every terminal (including the special terminal). " }, { "code": null, "e": 28861, "s": 28784, "text": "Each cell of this table will contain at most one rule of the given grammar: " }, { "code": null, "e": 28964, "s": 28861, "text": "Now let’s see using the algorithm, how the parser uses this parsing table to process the given input. " }, { "code": null, "e": 28976, "s": 28964, "text": "Procedure: " }, { "code": null, "e": 29204, "s": 28978, "text": "The parser thus ends because there remains only β€˜$’ on both its stack and its input stream. In this case, the parser reports that it has accepted the input string and writes the following list of rules to the output stream: " }, { "code": null, "e": 29248, "s": 29204, "text": "S -> ( S * A), \nS -> A, \nA -> id, \nA -> id " }, { "code": null, "e": 29322, "s": 29248, "text": "This is indeed a list of rules for an LMD of the input string, which is: " }, { "code": null, "e": 29381, "s": 29322, "text": "S -> ( S * A ) -> ( A * A ) -> ( id * A ) -> ( id * id ) " }, { "code": null, "e": 29391, "s": 29381, "text": "ruhelaa48" }, { "code": null, "e": 29407, "s": 29391, "text": "Compiler Design" }, { "code": null, "e": 29415, "s": 29407, "text": "GATE CS" }, { "code": null, "e": 29513, "s": 29415, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29522, "s": 29513, "text": "Comments" }, { "code": null, "e": 29535, "s": 29522, "text": "Old Comments" }, { "code": null, "e": 29583, "s": 29535, "text": "Intermediate Code Generation in Compiler Design" }, { "code": null, "e": 29627, "s": 29583, "text": "Difference between Compiler and Interpreter" }, { "code": null, "e": 29685, "s": 29627, "text": "Difference between Top down parsing and Bottom up parsing" }, { "code": null, "e": 29722, "s": 29685, "text": "Loop Optimization in Compiler Design" }, { "code": null, "e": 29757, "s": 29722, "text": "Input Buffering in Compiler Design" }, { "code": null, "e": 29777, "s": 29757, "text": "Layers of OSI Model" }, { "code": null, "e": 29801, "s": 29777, "text": "ACID Properties in DBMS" }, { "code": null, "e": 29822, "s": 29801, "text": "Normal Forms in DBMS" }, { "code": null, "e": 29849, "s": 29822, "text": "Types of Operating Systems" } ]
How to Add GIFs on README .md File in a GitHub Repository? - GeeksforGeeks
10 Nov, 2021 Git is a free and open-source distributed version control system designed to handle everything from small to very large projects. Github is a highly used software that is used for version control. It is more helpful when more than one person is working on a project. GIF as we all know stands for Graphics Interchange Format is a bitmap image format. This format supports 8 bits per pixel. Proceeding further Git and Github basics are a must pre-requisite to go where here we will be getting how we can add GIFs in the README.md file of a GitHub repository. Step 1: First of all, create a GitHub repository on Github, for illustration purposes we are taking a custom repository as depicted below: For example, We have created a Github repository with the name GeeksForGeeks. Step 2: Upload the GIF in the repository which you want to add in README. For example, custom GIF have ben uploaded in above repository named β€œGeeks For Geeks”. Step 3: Click on the β€œAdd a README” button. A new window will open. Step 4: Open the added GIF file in your repository and copy the URL. Step 5: Now paste it inside your README.md file with command below as follows: ![](https://github.com/Your_Repository_Name/Your_GIF_Name.gif) Example: Custom readme in the directory 1.1 Click on the commit changes button at the bottom. 1.2 Your GIF will appear along with other README.md file contents. Note: It is recommended to use GIFs size to be less than 30 MB. GitHub Git Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference Between Git Push Origin and Git Push Origin Master How to Push Git Branch to Remote? Git - Difference Between Git Fetch and Git Pull How to Export Eclipse projects to GitHub? Merge Conflicts and How to handle them How to Add Git Credentials in Eclipse? What is README.md File? Top 10 GitHub Alternatives That You Can Consider Git - Merge Using Patches in Git
[ { "code": null, "e": 24666, "s": 24638, "text": "\n10 Nov, 2021" }, { "code": null, "e": 25056, "s": 24666, "text": "Git is a free and open-source distributed version control system designed to handle everything from small to very large projects. Github is a highly used software that is used for version control. It is more helpful when more than one person is working on a project. GIF as we all know stands for Graphics Interchange Format is a bitmap image format. This format supports 8 bits per pixel." }, { "code": null, "e": 25224, "s": 25056, "text": "Proceeding further Git and Github basics are a must pre-requisite to go where here we will be getting how we can add GIFs in the README.md file of a GitHub repository." }, { "code": null, "e": 25364, "s": 25224, "text": "Step 1: First of all, create a GitHub repository on Github, for illustration purposes we are taking a custom repository as depicted below: " }, { "code": null, "e": 25442, "s": 25364, "text": "For example, We have created a Github repository with the name GeeksForGeeks." }, { "code": null, "e": 25516, "s": 25442, "text": "Step 2: Upload the GIF in the repository which you want to add in README." }, { "code": null, "e": 25603, "s": 25516, "text": "For example, custom GIF have ben uploaded in above repository named β€œGeeks For Geeks”." }, { "code": null, "e": 25647, "s": 25603, "text": "Step 3: Click on the β€œAdd a README” button." }, { "code": null, "e": 25671, "s": 25647, "text": "A new window will open." }, { "code": null, "e": 25740, "s": 25671, "text": "Step 4: Open the added GIF file in your repository and copy the URL." }, { "code": null, "e": 25819, "s": 25740, "text": "Step 5: Now paste it inside your README.md file with command below as follows:" }, { "code": null, "e": 25882, "s": 25819, "text": "![](https://github.com/Your_Repository_Name/Your_GIF_Name.gif)" }, { "code": null, "e": 25923, "s": 25882, "text": "Example: Custom readme in the directory " }, { "code": null, "e": 25977, "s": 25923, "text": "1.1 Click on the commit changes button at the bottom." }, { "code": null, "e": 26044, "s": 25977, "text": "1.2 Your GIF will appear along with other README.md file contents." }, { "code": null, "e": 26108, "s": 26044, "text": "Note: It is recommended to use GIFs size to be less than 30 MB." }, { "code": null, "e": 26115, "s": 26108, "text": "GitHub" }, { "code": null, "e": 26119, "s": 26115, "text": "Git" }, { "code": null, "e": 26217, "s": 26119, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26279, "s": 26217, "text": "Difference Between Git Push Origin and Git Push Origin Master" }, { "code": null, "e": 26313, "s": 26279, "text": "How to Push Git Branch to Remote?" }, { "code": null, "e": 26361, "s": 26313, "text": "Git - Difference Between Git Fetch and Git Pull" }, { "code": null, "e": 26403, "s": 26361, "text": "How to Export Eclipse projects to GitHub?" }, { "code": null, "e": 26442, "s": 26403, "text": "Merge Conflicts and How to handle them" }, { "code": null, "e": 26481, "s": 26442, "text": "How to Add Git Credentials in Eclipse?" }, { "code": null, "e": 26505, "s": 26481, "text": "What is README.md File?" }, { "code": null, "e": 26554, "s": 26505, "text": "Top 10 GitHub Alternatives That You Can Consider" }, { "code": null, "e": 26566, "s": 26554, "text": "Git - Merge" } ]
Creating a list of range of dates in Python - GeeksforGeeks
09 May, 2021 Given a date, and the task is to write a Python program to create a list of range of dates with the next K dates starting from the current date. Examples: Input : test_date = datetime.datetime(1997, 1, 4), K = 5 Output : [datetime.datetime(1997, 1, 4, 0, 0), datetime.datetime(1997, 1, 5, 0, 0), datetime.datetime(1997, 1, 6, 0, 0), datetime.datetime(1997, 1, 7, 0, 0), datetime.datetime(1997, 1, 8, 0, 0)] Explanation : 5 dates after 4 January are extracted in list. Input : test_date = datetime.datetime(1997, 1, 4), K = 4 Output : [datetime.datetime(1997, 1, 4, 0, 0), datetime.datetime(1997, 1, 5, 0, 0), datetime.datetime(1997, 1, 6, 0, 0), datetime.datetime(1997, 1, 7, 0, 0)] Explanation : 4 dates after 4 January are extracted in list. In this, we get to add consecutive deltas to day using timedelta(), and list comprehension is used to iterate through the required size and construct the required result. Python3 # Python3 code to demonstrate working of# Get Construct Next K dates List# Using timedelta() + list comphehensionimport datetime # initializing datetest_date = datetime.datetime(1997, 1, 4) # printing original dateprint("The original date is : " + str(test_date)) # initializing K K = 5 # timedelta() gets successive dates with # appropriate differenceres = [test_date + datetime.timedelta(days=idx) for idx in range(K)] # printing resultprint("Next K dates list : " + str(res)) Output: The original date is : 1997-01-04 00:00:00 Next K dates list : [datetime.datetime(1997, 1, 4, 0, 0), datetime.datetime(1997, 1, 5, 0, 0), datetime.datetime(1997, 1, 6, 0, 0), datetime.datetime(1997, 1, 7, 0, 0), datetime.datetime(1997, 1, 8, 0, 0)] In this, we perform a similar task as the above function, using a generator to perform the task of date successions. Python3 # Python3 code to demonstrate working of# Get Construct Next K dates List# Using count() + generator functionimport datetimeimport itertools # initializing datetest_date = datetime.datetime(1997, 1, 4) # printing original dateprint("The original date is : " + str(test_date)) # initializing K K = 5 # timedelta() gets successive dates with # appropriate differencegen_fnc = ( test_date - datetime.timedelta(days=idx) for idx in itertools.count()) # islice passes counterres = itertools.islice(gen_fnc, K) # printing resultprint("Next K dates list : " + str(list(res))) Output: The original date is : 1997-01-04 00:00:00 Next K dates list : [datetime.datetime(1997, 1, 4, 0, 0), datetime.datetime(1997, 1, 3, 0, 0), datetime.datetime(1997, 1, 2, 0, 0), datetime.datetime(1997, 1, 1, 0, 0), datetime.datetime(1996, 12, 31, 0, 0)] Python datetime-program Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary Python program to check whether a number is Prime or not
[ { "code": null, "e": 24292, "s": 24264, "text": "\n09 May, 2021" }, { "code": null, "e": 24437, "s": 24292, "text": "Given a date, and the task is to write a Python program to create a list of range of dates with the next K dates starting from the current date." }, { "code": null, "e": 24447, "s": 24437, "text": "Examples:" }, { "code": null, "e": 24504, "s": 24447, "text": "Input : test_date = datetime.datetime(1997, 1, 4), K = 5" }, { "code": null, "e": 24699, "s": 24504, "text": "Output : [datetime.datetime(1997, 1, 4, 0, 0), datetime.datetime(1997, 1, 5, 0, 0), datetime.datetime(1997, 1, 6, 0, 0), datetime.datetime(1997, 1, 7, 0, 0), datetime.datetime(1997, 1, 8, 0, 0)]" }, { "code": null, "e": 24760, "s": 24699, "text": "Explanation : 5 dates after 4 January are extracted in list." }, { "code": null, "e": 24817, "s": 24760, "text": "Input : test_date = datetime.datetime(1997, 1, 4), K = 4" }, { "code": null, "e": 24975, "s": 24817, "text": "Output : [datetime.datetime(1997, 1, 4, 0, 0), datetime.datetime(1997, 1, 5, 0, 0), datetime.datetime(1997, 1, 6, 0, 0), datetime.datetime(1997, 1, 7, 0, 0)]" }, { "code": null, "e": 25036, "s": 24975, "text": "Explanation : 4 dates after 4 January are extracted in list." }, { "code": null, "e": 25207, "s": 25036, "text": "In this, we get to add consecutive deltas to day using timedelta(), and list comprehension is used to iterate through the required size and construct the required result." }, { "code": null, "e": 25215, "s": 25207, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Get Construct Next K dates List# Using timedelta() + list comphehensionimport datetime # initializing datetest_date = datetime.datetime(1997, 1, 4) # printing original dateprint(\"The original date is : \" + str(test_date)) # initializing K K = 5 # timedelta() gets successive dates with # appropriate differenceres = [test_date + datetime.timedelta(days=idx) for idx in range(K)] # printing resultprint(\"Next K dates list : \" + str(res))", "e": 25712, "s": 25215, "text": null }, { "code": null, "e": 25720, "s": 25712, "text": "Output:" }, { "code": null, "e": 25763, "s": 25720, "text": "The original date is : 1997-01-04 00:00:00" }, { "code": null, "e": 25859, "s": 25763, "text": "Next K dates list : [datetime.datetime(1997, 1, 4, 0, 0), datetime.datetime(1997, 1, 5, 0, 0), " }, { "code": null, "e": 25970, "s": 25859, "text": "datetime.datetime(1997, 1, 6, 0, 0), datetime.datetime(1997, 1, 7, 0, 0), datetime.datetime(1997, 1, 8, 0, 0)]" }, { "code": null, "e": 26087, "s": 25970, "text": "In this, we perform a similar task as the above function, using a generator to perform the task of date successions." }, { "code": null, "e": 26095, "s": 26087, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Get Construct Next K dates List# Using count() + generator functionimport datetimeimport itertools # initializing datetest_date = datetime.datetime(1997, 1, 4) # printing original dateprint(\"The original date is : \" + str(test_date)) # initializing K K = 5 # timedelta() gets successive dates with # appropriate differencegen_fnc = ( test_date - datetime.timedelta(days=idx) for idx in itertools.count()) # islice passes counterres = itertools.islice(gen_fnc, K) # printing resultprint(\"Next K dates list : \" + str(list(res)))", "e": 26684, "s": 26095, "text": null }, { "code": null, "e": 26692, "s": 26684, "text": "Output:" }, { "code": null, "e": 26735, "s": 26692, "text": "The original date is : 1997-01-04 00:00:00" }, { "code": null, "e": 26831, "s": 26735, "text": "Next K dates list : [datetime.datetime(1997, 1, 4, 0, 0), datetime.datetime(1997, 1, 3, 0, 0), " }, { "code": null, "e": 26944, "s": 26831, "text": "datetime.datetime(1997, 1, 2, 0, 0), datetime.datetime(1997, 1, 1, 0, 0), datetime.datetime(1996, 12, 31, 0, 0)]" }, { "code": null, "e": 26968, "s": 26944, "text": "Python datetime-program" }, { "code": null, "e": 26975, "s": 26968, "text": "Python" }, { "code": null, "e": 26991, "s": 26975, "text": "Python Programs" }, { "code": null, "e": 27089, "s": 26991, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27098, "s": 27089, "text": "Comments" }, { "code": null, "e": 27111, "s": 27098, "text": "Old Comments" }, { "code": null, "e": 27143, "s": 27111, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27198, "s": 27143, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 27254, "s": 27198, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27296, "s": 27254, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27338, "s": 27296, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27360, "s": 27338, "text": "Defaultdict in Python" }, { "code": null, "e": 27399, "s": 27360, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27445, "s": 27399, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27483, "s": 27445, "text": "Python | Convert a list to dictionary" } ]
C | Pointer Basics | Question 12 - GeeksforGeeks
05 Feb, 2013 Consider this C code to swap two integers and these five statements after it: void swap(int *px, int *py) { *px = *px - *py; *py = *px + *py; *px = *py - *px; } S1: will generate a compilation errorS2: may generate a segmentation fault at runtime depending on the arguments passedS3: correctly implements the swap procedure for all input pointers referring to integers stored in memory locations accessible to the processS4: implements the swap procedure correctly for some but not all valid input pointersS5: may add or subtract integers and pointers. (A) S1(B) S2 and S3(C) S2 and S4 (D) S2 and S5Answer: (C)Explanation: S2: May generate segmentation fault if value at pointers px or py is constant or px or py points to a memory location that is invalidS4: May not work for all inputs as arithmetic overflow can occur C-Pointers Pointers C Language C Quiz Pointers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Function Pointer in C TCP Server-Client implementation in C Structures in C std::string class in C++ Exception Handling in C++ Compiling a C program:- Behind the Scenes Operator Precedence and Associativity in C C | Structure & Union | Question 4 C | File Handling | Question 5 C | File Handling | Question 1
[ { "code": null, "e": 24268, "s": 24240, "text": "\n05 Feb, 2013" }, { "code": null, "e": 24346, "s": 24268, "text": "Consider this C code to swap two integers and these five statements after it:" }, { "code": "void swap(int *px, int *py) { *px = *px - *py; *py = *px + *py; *px = *py - *px; }", "e": 24438, "s": 24346, "text": null }, { "code": null, "e": 24830, "s": 24438, "text": "S1: will generate a compilation errorS2: may generate a segmentation fault at runtime depending on the arguments passedS3: correctly implements the swap procedure for all input pointers referring to integers stored in memory locations accessible to the processS4: implements the swap procedure correctly for some but not all valid input pointersS5: may add or subtract integers and pointers." }, { "code": null, "e": 24863, "s": 24830, "text": "(A) S1(B) S2 and S3(C) S2 and S4" }, { "code": null, "e": 25098, "s": 24863, "text": "(D) S2 and S5Answer: (C)Explanation: S2: May generate segmentation fault if value at pointers px or py is constant or px or py points to a memory location that is invalidS4: May not work for all inputs as arithmetic overflow can occur" }, { "code": null, "e": 25109, "s": 25098, "text": "C-Pointers" }, { "code": null, "e": 25118, "s": 25109, "text": "Pointers" }, { "code": null, "e": 25129, "s": 25118, "text": "C Language" }, { "code": null, "e": 25136, "s": 25129, "text": "C Quiz" }, { "code": null, "e": 25145, "s": 25136, "text": "Pointers" }, { "code": null, "e": 25243, "s": 25145, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25252, "s": 25243, "text": "Comments" }, { "code": null, "e": 25265, "s": 25252, "text": "Old Comments" }, { "code": null, "e": 25287, "s": 25265, "text": "Function Pointer in C" }, { "code": null, "e": 25325, "s": 25287, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 25341, "s": 25325, "text": "Structures in C" }, { "code": null, "e": 25366, "s": 25341, "text": "std::string class in C++" }, { "code": null, "e": 25392, "s": 25366, "text": "Exception Handling in C++" }, { "code": null, "e": 25434, "s": 25392, "text": "Compiling a C program:- Behind the Scenes" }, { "code": null, "e": 25477, "s": 25434, "text": "Operator Precedence and Associativity in C" }, { "code": null, "e": 25512, "s": 25477, "text": "C | Structure & Union | Question 4" }, { "code": null, "e": 25543, "s": 25512, "text": "C | File Handling | Question 5" } ]
Get elapsed time in minutes in Java
To get the elapsed time of an operation in minutes in Java, we use the System.currentTimeMillis() method. The java.lang.System.currentTimeMillis() returns the current time in milliseconds. Declaration βˆ’The java.lang.System.currentTimeMillis() is declared as follows βˆ’ public static long currentTimeMillis() The method returns time difference in milliseconds between the current time and midnight, January 1, 1970 (UTC or epoch time). Let us see a program to compute the elapsed time of an operation in minutes in Java βˆ’ Live Demo public class Example { public static void main(String[] args) throws Exception { // finding the time before the operation is executed long start = System.currentTimeMillis(); for (int i = 0; i <5; i++) { Thread.sleep(60); } // finding the time after the operation is executed long end = System.currentTimeMillis(); // finding the time difference float msec = end - start; // converting it into seconds float sec= msec/1000F; // converting it into minutes float minutes=sec/60F; System.out.println(minutes + " minutes"); } } 0.0050000004 minutes
[ { "code": null, "e": 1251, "s": 1062, "text": "To get the elapsed time of an operation in minutes in Java, we use the System.currentTimeMillis() method. The java.lang.System.currentTimeMillis() returns the current time in milliseconds." }, { "code": null, "e": 1330, "s": 1251, "text": "Declaration βˆ’The java.lang.System.currentTimeMillis() is declared as follows βˆ’" }, { "code": null, "e": 1369, "s": 1330, "text": "public static long currentTimeMillis()" }, { "code": null, "e": 1496, "s": 1369, "text": "The method returns time difference in milliseconds between the current time and midnight, January 1, 1970 (UTC or epoch time)." }, { "code": null, "e": 1582, "s": 1496, "text": "Let us see a program to compute the elapsed time of an operation in minutes in Java βˆ’" }, { "code": null, "e": 1593, "s": 1582, "text": " Live Demo" }, { "code": null, "e": 2210, "s": 1593, "text": "public class Example {\n public static void main(String[] args) throws Exception {\n // finding the time before the operation is executed\n long start = System.currentTimeMillis();\n for (int i = 0; i <5; i++) {\n Thread.sleep(60);\n }\n // finding the time after the operation is executed\n long end = System.currentTimeMillis();\n // finding the time difference\n float msec = end - start;\n // converting it into seconds\n float sec= msec/1000F;\n // converting it into minutes\n float minutes=sec/60F;\n System.out.println(minutes + \" minutes\");\n }\n}" }, { "code": null, "e": 2231, "s": 2210, "text": "0.0050000004 minutes" } ]
Count ordered pairs of numbers with a given LCM - GeeksforGeeks
10 May, 2021 Given an integer N, the task is to count the total number of ordered pairs such that the LCM of each pair is equal to N. Examples: Input: N = 6Output: 9 Explanation: Pairs with LCM equal to N(= 6) are {(1, 6), (2, 6), (2, 3), (3, 6), (6, 6), (6, 3), (3, 2), (6, 2), (6, 1)} Therefore, the output is 9. Input: N = 36Output: 25 Approach: The problem can be solved based on the following observations: Consider an ordered pair(X, Y). X = P1a1 * P2a2 * P3a3 *.....* Pnan Y = P1b1 * P2b2 * P3b3 *.....* PnbnHere, P1, P2, ....., Pn are prime factors of X and Y. LCM(X, Y) = P1max(a1, b1) * P2max(a2, b2) *..........*Pnmax(an, bn)Therefore, LCM(X, Y) = N = P1m1 * P2m2 * P3m3 *.....* Pnmn Therefore, total number of ordered pairs (X, Y) = [{(m1 + 1)2 – m12} * {(m2 + 1)2 – m22} * ......* {(mn + 1)2 – mn2} ]= (2*m1+1) * (2*m2+1) * (2*m3+1) * ........* (2*mn+1). Follow the steps below to solve the problem: Initialize a variable, say, countPower, to store the power of all prime factors of N.Calculate the power of all prime factors of N.Finally, print the count of ordered pairs(X, Y) using the aforementioned formula. Initialize a variable, say, countPower, to store the power of all prime factors of N. Calculate the power of all prime factors of N. Finally, print the count of ordered pairs(X, Y) using the aforementioned formula. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to count the number of// ordered pairs with given LCMint CtOrderedPairs(int N){ // Stores count of // ordered pairs int res = 1; // Calculate power of all // prime factors of N for (int i = 2; i * i <= N; i++) { // Store the power of // prime factors int countPower = 0; while (N % i == 0) { countPower++; N /= i; } res = res * (2 * countPower + 1); } if (N > 1) { res = res * (2 * 1 + 1); } return res;} // Driver Codeint main(){ int N = 36; cout << CtOrderedPairs(N);} // Java program to implement// the above approach class GFG{ // Function to count the number of// ordered pairs with given LCMstatic int CtOrderedPairs(int N){ // Stores count of // ordered pairs int res = 1; // Calculate power of all // prime factors of N for(int i = 2; i * i <= N; i++) { // Store the power of // prime factors int countPower = 0; while (N % i == 0) { countPower++; N /= i; } res = res * (2 * countPower + 1); } if (N > 1) { res = res * (2 * 1 + 1); } return res;} // Driver Codepublic static void main(String[] args){ int N = 36; System.out.println(CtOrderedPairs(N));}} // This code is contributed by aimformohan # Python3 program to implement# the above approach # Function to count the number of# ordered pairs with given LCMdef CtOrderedPairs(N): # Stores count of # ordered pairs res = 1 # Calculate power of all # prime factors of N i = 2 while(i * i <= N): # Store the power of # prime factors countPower = 0 while (N % i == 0): countPower += 1 N //= i res = res * (2 * countPower + 1) i += 1 if (N > 1): res = res * (2 * 1 + 1) return res # Driver CodeN = 36 print(CtOrderedPairs(N)) # This code is contributed by code_hunt // C# program to implement// the above approachusing System; class GFG{ // Function to count the number of// ordered pairs with given LCMstatic int CtOrderedPairs(int N){ // Stores count of // ordered pairs int res = 1; // Calculate power of all // prime factors of N for(int i = 2; i * i <= N; i++) { // Store the power of // prime factors int countPower = 0; while (N % i == 0) { countPower++; N /= i; } res = res * (2 * countPower + 1); } if (N > 1) { res = res * (2 * 1 + 1); } return res;} // Driver Codepublic static void Main(){ int N = 36; Console.WriteLine(CtOrderedPairs(N));}} // This code is contributed by code_hunt <script> // Javascript program to implement// the above approach // Function to count the number of// ordered pairs with given LCMfunction CtOrderedPairs(N){ // Stores count of // ordered pairs let res = 1; // Calculate power of all // prime factors of N for(let i = 2; i * i <= N; i++) { // Store the power of // prime factors let countPower = 0; while (N % i == 0) { countPower++; N /= i; } res = res * (2 * countPower + 1); } if (N > 1) { res = res * (2 * 1 + 1); } return res;} // Driver Code let N = 36; document.write(CtOrderedPairs(N)); </script> 25 Time Complexity: O(√N) Auxiliary Space: O(1) aimformohan code_hunt avijitmondal1998 LCM maths-power prime-factor Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to find GCD or HCF of two numbers Modulo Operator (%) in C/C++ with Examples Merge two sorted arrays Prime Numbers Program to find sum of elements in a given array Program for factorial of a number Operators in C / C++ Sieve of Eratosthenes Program for Decimal to Binary Conversion Euclidean algorithms (Basic and Extended)
[ { "code": null, "e": 25378, "s": 25350, "text": "\n10 May, 2021" }, { "code": null, "e": 25499, "s": 25378, "text": "Given an integer N, the task is to count the total number of ordered pairs such that the LCM of each pair is equal to N." }, { "code": null, "e": 25509, "s": 25499, "text": "Examples:" }, { "code": null, "e": 25680, "s": 25509, "text": "Input: N = 6Output: 9 Explanation: Pairs with LCM equal to N(= 6) are {(1, 6), (2, 6), (2, 3), (3, 6), (6, 6), (6, 3), (3, 2), (6, 2), (6, 1)} Therefore, the output is 9." }, { "code": null, "e": 25704, "s": 25680, "text": "Input: N = 36Output: 25" }, { "code": null, "e": 25777, "s": 25704, "text": "Approach: The problem can be solved based on the following observations:" }, { "code": null, "e": 26061, "s": 25777, "text": "Consider an ordered pair(X, Y). X = P1a1 * P2a2 * P3a3 *.....* Pnan Y = P1b1 * P2b2 * P3b3 *.....* PnbnHere, P1, P2, ....., Pn are prime factors of X and Y. LCM(X, Y) = P1max(a1, b1) * P2max(a2, b2) *..........*Pnmax(an, bn)Therefore, LCM(X, Y) = N = P1m1 * P2m2 * P3m3 *.....* Pnmn" }, { "code": null, "e": 26234, "s": 26061, "text": "Therefore, total number of ordered pairs (X, Y) = [{(m1 + 1)2 – m12} * {(m2 + 1)2 – m22} * ......* {(mn + 1)2 – mn2} ]= (2*m1+1) * (2*m2+1) * (2*m3+1) * ........* (2*mn+1)." }, { "code": null, "e": 26279, "s": 26234, "text": "Follow the steps below to solve the problem:" }, { "code": null, "e": 26492, "s": 26279, "text": "Initialize a variable, say, countPower, to store the power of all prime factors of N.Calculate the power of all prime factors of N.Finally, print the count of ordered pairs(X, Y) using the aforementioned formula." }, { "code": null, "e": 26578, "s": 26492, "text": "Initialize a variable, say, countPower, to store the power of all prime factors of N." }, { "code": null, "e": 26625, "s": 26578, "text": "Calculate the power of all prime factors of N." }, { "code": null, "e": 26707, "s": 26625, "text": "Finally, print the count of ordered pairs(X, Y) using the aforementioned formula." }, { "code": null, "e": 26759, "s": 26707, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26763, "s": 26759, "text": "C++" }, { "code": null, "e": 26768, "s": 26763, "text": "Java" }, { "code": null, "e": 26776, "s": 26768, "text": "Python3" }, { "code": null, "e": 26779, "s": 26776, "text": "C#" }, { "code": null, "e": 26790, "s": 26779, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to count the number of// ordered pairs with given LCMint CtOrderedPairs(int N){ // Stores count of // ordered pairs int res = 1; // Calculate power of all // prime factors of N for (int i = 2; i * i <= N; i++) { // Store the power of // prime factors int countPower = 0; while (N % i == 0) { countPower++; N /= i; } res = res * (2 * countPower + 1); } if (N > 1) { res = res * (2 * 1 + 1); } return res;} // Driver Codeint main(){ int N = 36; cout << CtOrderedPairs(N);}", "e": 27498, "s": 26790, "text": null }, { "code": "// Java program to implement// the above approach class GFG{ // Function to count the number of// ordered pairs with given LCMstatic int CtOrderedPairs(int N){ // Stores count of // ordered pairs int res = 1; // Calculate power of all // prime factors of N for(int i = 2; i * i <= N; i++) { // Store the power of // prime factors int countPower = 0; while (N % i == 0) { countPower++; N /= i; } res = res * (2 * countPower + 1); } if (N > 1) { res = res * (2 * 1 + 1); } return res;} // Driver Codepublic static void main(String[] args){ int N = 36; System.out.println(CtOrderedPairs(N));}} // This code is contributed by aimformohan", "e": 28284, "s": 27498, "text": null }, { "code": "# Python3 program to implement# the above approach # Function to count the number of# ordered pairs with given LCMdef CtOrderedPairs(N): # Stores count of # ordered pairs res = 1 # Calculate power of all # prime factors of N i = 2 while(i * i <= N): # Store the power of # prime factors countPower = 0 while (N % i == 0): countPower += 1 N //= i res = res * (2 * countPower + 1) i += 1 if (N > 1): res = res * (2 * 1 + 1) return res # Driver CodeN = 36 print(CtOrderedPairs(N)) # This code is contributed by code_hunt", "e": 28918, "s": 28284, "text": null }, { "code": "// C# program to implement// the above approachusing System; class GFG{ // Function to count the number of// ordered pairs with given LCMstatic int CtOrderedPairs(int N){ // Stores count of // ordered pairs int res = 1; // Calculate power of all // prime factors of N for(int i = 2; i * i <= N; i++) { // Store the power of // prime factors int countPower = 0; while (N % i == 0) { countPower++; N /= i; } res = res * (2 * countPower + 1); } if (N > 1) { res = res * (2 * 1 + 1); } return res;} // Driver Codepublic static void Main(){ int N = 36; Console.WriteLine(CtOrderedPairs(N));}} // This code is contributed by code_hunt", "e": 29707, "s": 28918, "text": null }, { "code": "<script> // Javascript program to implement// the above approach // Function to count the number of// ordered pairs with given LCMfunction CtOrderedPairs(N){ // Stores count of // ordered pairs let res = 1; // Calculate power of all // prime factors of N for(let i = 2; i * i <= N; i++) { // Store the power of // prime factors let countPower = 0; while (N % i == 0) { countPower++; N /= i; } res = res * (2 * countPower + 1); } if (N > 1) { res = res * (2 * 1 + 1); } return res;} // Driver Code let N = 36; document.write(CtOrderedPairs(N)); </script>", "e": 30434, "s": 29707, "text": null }, { "code": null, "e": 30437, "s": 30434, "text": "25" }, { "code": null, "e": 30484, "s": 30439, "text": "Time Complexity: O(√N) Auxiliary Space: O(1)" }, { "code": null, "e": 30496, "s": 30484, "text": "aimformohan" }, { "code": null, "e": 30506, "s": 30496, "text": "code_hunt" }, { "code": null, "e": 30523, "s": 30506, "text": "avijitmondal1998" }, { "code": null, "e": 30527, "s": 30523, "text": "LCM" }, { "code": null, "e": 30539, "s": 30527, "text": "maths-power" }, { "code": null, "e": 30552, "s": 30539, "text": "prime-factor" }, { "code": null, "e": 30565, "s": 30552, "text": "Mathematical" }, { "code": null, "e": 30578, "s": 30565, "text": "Mathematical" }, { "code": null, "e": 30676, "s": 30578, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30718, "s": 30676, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 30761, "s": 30718, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 30785, "s": 30761, "text": "Merge two sorted arrays" }, { "code": null, "e": 30799, "s": 30785, "text": "Prime Numbers" }, { "code": null, "e": 30848, "s": 30799, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 30882, "s": 30848, "text": "Program for factorial of a number" }, { "code": null, "e": 30903, "s": 30882, "text": "Operators in C / C++" }, { "code": null, "e": 30925, "s": 30903, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 30966, "s": 30925, "text": "Program for Decimal to Binary Conversion" } ]
Handling NetCDF Files using XArray for Absolute Beginners | by Eden Au | Towards Data Science
NetCDF is a machine-independent, array-oriented, multi-dimensional, self-describing, and portable data format used by various scientific communities. It has a filename extension of .nc or .cdf (though it is believed that there are subtle differences between the two). Unlike files in .csv or .xlsx, NetCDF format cannot be accessed and viewed directly using spreadsheet software. Even if you could, you would not do that on a 4-dimensional data with a bunch of metadata. I will take climate data from Atmospheric Radiation Measurement Climate Research Facility (ARM) in the United States, and European Centre for Medium-Range Weather Forecasts (ECMWF) in Europe as an example. Prerequisites Alternatives Data Preview Terminology Coding using XArray Remarks Originally published on my blog edenau.github.io. We will use xarray library in Python for data processing. Long story short, it builds upon numpy (and dask) libraries and leverages the power of pandas, but you probably don’t need to know about it. As you might know, package dependency is a pain in Python. That is why the most convenient way to get everything installed is to use the following command: $ conda install xarray dask netCDF4 bottleneck Experienced Python programmers are recommended check the relevant documentation for more details. If you are a beginner, no worries. I made a list of dependencies that you need to check: Python 2.7/3.5+ required numpy 1.12+ required pandas 0.19.2+ required scipy for interpolation features bottleneck for speeding up NaN-skipping netCDF4-python for basic netCDF operation such as reading/writing dask-array 0.16+ for parallel computing with dask If you want to visualize your dataset, you will probably need these: matplotlib 1.5+ for plotting cartopy for maps seaborn for better colour palettes For absolute beginners, you can check your default version of Python by $ python --versionPython 2.7.5 You can also check if Python3 is installed by $ python3 --versionPython 3.4.9 To check the version of packages, use pip freeze or conda list. Things should check out if you install xarray through conda. iris is an alternative to xarray, but some works need to be done to make it work on Windows, and it does not work well on Mac OS. Iris is also an English word, so googling β€˜iris’ gives you many irrelevant results. It was a pain for me to use iris. It is always a good idea to β€˜preview’ and β€˜get to know’ your data, its metadata and data structures. Assume you have installed netCDF4-python and the only two commands you need are ncdump and ncview. The former gives text representation of your netCDF dataset (basically metadata and the data itself), while the latter is a very powerful graphical interface for instant data visualization. Go to the directory of your dataset and try $ ncdump -h twparmbeatmC1.c1.20050101.000000.cdf As we do not need to see the values of every data entry at the moment, -h ensures only header (metadata) is shown. You will get netcdf twparmbeatmC1.c1.20050101.000000 {dimensions: time = UNLIMITED ; // (8760 currently) range = 2 ; p = 37 ; z = 512 ;variables: double base_time ; base_time:long_name = "Base time in Epoch" ; base_time:units = "seconds since 1970-1-1 0:00:00 0:00" ; base_time:string = "2005-01-01 00.00, GMT" ; base_time:ancillary_variables = "time_offset" ; float prec_sfc(time) ; prec_sfc:long_name = "Precipitation Rate" ; prec_sfc:standard_name = "lwe_precipitation_rate" ; prec_sfc:units = "mm/hour" ; prec_sfc:missing_value = -9999.f ; prec_sfc:_FillValue = -9999.f ; prec_sfc:source = "twpsmet60sC1.b1" ; float T_p(time, p) ; T_p:long_name = "Dry Bulb Temperature, from sounding in p coordinate" ; T_p:standard_name = "air_temperature" ; T_p:units = "K" ; T_p:missing_value = -9999.f ; T_p:_FillValue = -9999.f ; T_p:source = "twpsondewnpnC1.b1:tdry" ;// global attributes:< OTHER METADATA >} You can see dimensions, variables, and other metadata which are quite self-explanatory. Global attributes (not printed above) tells us how the data is collected and pre-processed. In this example, they are measurement data taken at 147.4E 2.1S, Manus, Papua New Guinea by ARM. When we look into the list of variables: 1-dim prec_sfc and 2-dim T_p, we realize that they have different dimensions(!). Precipitation rate is a scalar measurement at each time, whereas temperature is a column (measurements at different pressure levels instead of altitude levels this time) at every time. It is quite common to see 4-dim data in climate science β€” latitude, longitude, altitude/pressure level, time. Try the following command and it gives you a graphical interface that lists all variables in your dataset, and it is quite straightforward. $ ncview twparmbeatmC1.c1.20050101.000000.cdf xarray.DataArray is an implementation of a labelled, multi-dimensional array for a single variable, such as precipitation, temperature etc.. It has the following key properties: values: a numpy.ndarray holding the array’s values dims: dimension names for each axis (e.g., ('lat', 'lon', 'z', 'time')) coords: a dict-like container of arrays (coordinates) that label each point (e.g., 1-dim arrays of numbers, DateTime objects, or strings) attrs: an OrderedDict to hold arbitrary metadata (attributes) xarray.DataSet is a collection of DataArrays. Each NetCDF file contains a DataSet. You cannot play with the data until you read it. Use open_dataset or open_mfdataset to read a single or multiple NetCDF files, and store it in a DataSet called DS. import xarray as xr# single filedataDIR = '../data/ARM/twparmbeatmC1.c1.20050101.000000.cdf'DS = xr.open_dataset(dataDIR)# OR multiple filesmfdataDIR = '../data/ARM/twparmbeatmC1.c1.*.000000.cdf'DS = xr.open_mfdataset(mfdataDIR) Remember the 4 key properties of DataArrays? You can useDS.values, DS.var, DS.dims, DS.coords, and DS.attrs for data inspection. This will become very handy in interactive Python. Their functionalities are quite obvious and are left as an exercise to the reader(!). Extracting DataArrays from DataSet DS is very straightforward, as DS.<var_name> will suffice. You might consider dropping NaN entries by dropna() and selecting data with sel(). The method parameter in sel() allows us to enable the nearest neighbour (inexact) lookups by use of the methods 'pad', 'backfill', or 'nearest'. To specify a range, use slice(). You can transform xr.DataArray to numpy.ndarray by da.values. # Extract Dry Bulb Temperature in z-coordinate (T_z)# Select the altitude nearest to 500m above surface# Drop NaN, convert to Celciusda = DS.T_z.sel(z=500,method='nearest').dropna(dim='time') - 273.15 # or .ffill(dim='time')# Select data in 2000sda = da.sel(time=slice('2000-01-01', '2009-12-31'))da_numpy = da.values It is a convention to name DataSet as DS in upper case and DataArray as da in lower case. Assume DataArray da has a dimension timein DateTime format, We can extract the year/month/day/dayofyear/dayofweek by da.time.dt.<year/month/day/...>. Note that the output is still in DataArray. The following example takes one step further and tries to compute the mean/sum of any variable for each month. We first define a new coordinate system with assign_coords(). Why? Try looking into how year and month performs in DateTime. If we need the system to be aware of the differences between January 2000 and January 2001, we need both year and month to define a new coordinate, which we call it year_month. We can then group data by groupby('year_month') based on our newly defined coordinate system, followed by mean()or sum() operations. # Contract the DataArray by taking mean for each Year-Monthdef mean_in_year_month(da): # Index of Year-Month starts at Jan 1991 month_cnt_1991 = (da.time.dt.year.to_index() - 1991) * 12 + da.time.dt.month.to_index() # Assign newly defined Year-Month to coordinates, then group by it, then take the mean return da.assign_coords(year_month = month_cnt_1991).groupby('year_month').mean()da_1 = mean_in_year_month(da1) We can merge multiple DataArrays using xr.merge(). If you attempt to merge two variables with the same name but with different values, xr.MergeError will be raised. This ensures xr.merge()is non-destructive. DS_new = xr.merge([da_1,da_2,da_3]).dropna(dim='year_month') You can simply take DataArrays as arguments of matplotlib.pyplot methods. For absolute beginners, try plt.plot(), or plt.scatter() for line or scatter plots. Remember to show figures by plt.show(), or save figures by plt.savefig(). If you need maps, cartopy library can generate one easily. import cartopy.crs as ccrsimport matplotlib.pyplot as pltda = DS.t_sfc# Draw coastlines of the Earthax = plt.axes(projection=ccrs.PlateCarree())ax.coastlines() da.plot()plt.show() With a few extra lines of codes, you can generate something like this: You can convert DataArray to numpy.ndarray as explained earlier, or convert DataSet or DataArray to pandas.DataFrame as illustrated below. df = DS.to_dataframe() You can also export DataArray or DataSet to NetCDF file by dataDIR = '../data/new.nc'DS.to_netcdf(dataDIR) If you are interested in Python or programming in general, the following articles might be helpful: towardsdatascience.com towardsdatascience.com This tutorial was written for teaching purpose and only included the very basics of xarray. Hope this helps! Originally published on my blog edenau.github.io.
[ { "code": null, "e": 552, "s": 172, "text": "NetCDF is a machine-independent, array-oriented, multi-dimensional, self-describing, and portable data format used by various scientific communities. It has a filename extension of .nc or .cdf (though it is believed that there are subtle differences between the two). Unlike files in .csv or .xlsx, NetCDF format cannot be accessed and viewed directly using spreadsheet software." }, { "code": null, "e": 643, "s": 552, "text": "Even if you could, you would not do that on a 4-dimensional data with a bunch of metadata." }, { "code": null, "e": 849, "s": 643, "text": "I will take climate data from Atmospheric Radiation Measurement Climate Research Facility (ARM) in the United States, and European Centre for Medium-Range Weather Forecasts (ECMWF) in Europe as an example." }, { "code": null, "e": 863, "s": 849, "text": "Prerequisites" }, { "code": null, "e": 876, "s": 863, "text": "Alternatives" }, { "code": null, "e": 889, "s": 876, "text": "Data Preview" }, { "code": null, "e": 901, "s": 889, "text": "Terminology" }, { "code": null, "e": 921, "s": 901, "text": "Coding using XArray" }, { "code": null, "e": 929, "s": 921, "text": "Remarks" }, { "code": null, "e": 979, "s": 929, "text": "Originally published on my blog edenau.github.io." }, { "code": null, "e": 1334, "s": 979, "text": "We will use xarray library in Python for data processing. Long story short, it builds upon numpy (and dask) libraries and leverages the power of pandas, but you probably don’t need to know about it. As you might know, package dependency is a pain in Python. That is why the most convenient way to get everything installed is to use the following command:" }, { "code": null, "e": 1381, "s": 1334, "text": "$ conda install xarray dask netCDF4 bottleneck" }, { "code": null, "e": 1568, "s": 1381, "text": "Experienced Python programmers are recommended check the relevant documentation for more details. If you are a beginner, no worries. I made a list of dependencies that you need to check:" }, { "code": null, "e": 1593, "s": 1568, "text": "Python 2.7/3.5+ required" }, { "code": null, "e": 1614, "s": 1593, "text": "numpy 1.12+ required" }, { "code": null, "e": 1638, "s": 1614, "text": "pandas 0.19.2+ required" }, { "code": null, "e": 1671, "s": 1638, "text": "scipy for interpolation features" }, { "code": null, "e": 1711, "s": 1671, "text": "bottleneck for speeding up NaN-skipping" }, { "code": null, "e": 1777, "s": 1711, "text": "netCDF4-python for basic netCDF operation such as reading/writing" }, { "code": null, "e": 1827, "s": 1777, "text": "dask-array 0.16+ for parallel computing with dask" }, { "code": null, "e": 1896, "s": 1827, "text": "If you want to visualize your dataset, you will probably need these:" }, { "code": null, "e": 1925, "s": 1896, "text": "matplotlib 1.5+ for plotting" }, { "code": null, "e": 1942, "s": 1925, "text": "cartopy for maps" }, { "code": null, "e": 1977, "s": 1942, "text": "seaborn for better colour palettes" }, { "code": null, "e": 2049, "s": 1977, "text": "For absolute beginners, you can check your default version of Python by" }, { "code": null, "e": 2080, "s": 2049, "text": "$ python --versionPython 2.7.5" }, { "code": null, "e": 2126, "s": 2080, "text": "You can also check if Python3 is installed by" }, { "code": null, "e": 2158, "s": 2126, "text": "$ python3 --versionPython 3.4.9" }, { "code": null, "e": 2283, "s": 2158, "text": "To check the version of packages, use pip freeze or conda list. Things should check out if you install xarray through conda." }, { "code": null, "e": 2531, "s": 2283, "text": "iris is an alternative to xarray, but some works need to be done to make it work on Windows, and it does not work well on Mac OS. Iris is also an English word, so googling β€˜iris’ gives you many irrelevant results. It was a pain for me to use iris." }, { "code": null, "e": 2921, "s": 2531, "text": "It is always a good idea to β€˜preview’ and β€˜get to know’ your data, its metadata and data structures. Assume you have installed netCDF4-python and the only two commands you need are ncdump and ncview. The former gives text representation of your netCDF dataset (basically metadata and the data itself), while the latter is a very powerful graphical interface for instant data visualization." }, { "code": null, "e": 2965, "s": 2921, "text": "Go to the directory of your dataset and try" }, { "code": null, "e": 3014, "s": 2965, "text": "$ ncdump -h twparmbeatmC1.c1.20050101.000000.cdf" }, { "code": null, "e": 3142, "s": 3014, "text": "As we do not need to see the values of every data entry at the moment, -h ensures only header (metadata) is shown. You will get" }, { "code": null, "e": 4047, "s": 3142, "text": "netcdf twparmbeatmC1.c1.20050101.000000 {dimensions: time = UNLIMITED ; // (8760 currently) range = 2 ; p = 37 ; z = 512 ;variables: double base_time ; base_time:long_name = \"Base time in Epoch\" ; base_time:units = \"seconds since 1970-1-1 0:00:00 0:00\" ; base_time:string = \"2005-01-01 00.00, GMT\" ; base_time:ancillary_variables = \"time_offset\" ; float prec_sfc(time) ; prec_sfc:long_name = \"Precipitation Rate\" ; prec_sfc:standard_name = \"lwe_precipitation_rate\" ; prec_sfc:units = \"mm/hour\" ; prec_sfc:missing_value = -9999.f ; prec_sfc:_FillValue = -9999.f ; prec_sfc:source = \"twpsmet60sC1.b1\" ; float T_p(time, p) ; T_p:long_name = \"Dry Bulb Temperature, from sounding in p coordinate\" ; T_p:standard_name = \"air_temperature\" ; T_p:units = \"K\" ; T_p:missing_value = -9999.f ; T_p:_FillValue = -9999.f ; T_p:source = \"twpsondewnpnC1.b1:tdry\" ;// global attributes:< OTHER METADATA >}" }, { "code": null, "e": 4324, "s": 4047, "text": "You can see dimensions, variables, and other metadata which are quite self-explanatory. Global attributes (not printed above) tells us how the data is collected and pre-processed. In this example, they are measurement data taken at 147.4E 2.1S, Manus, Papua New Guinea by ARM." }, { "code": null, "e": 4741, "s": 4324, "text": "When we look into the list of variables: 1-dim prec_sfc and 2-dim T_p, we realize that they have different dimensions(!). Precipitation rate is a scalar measurement at each time, whereas temperature is a column (measurements at different pressure levels instead of altitude levels this time) at every time. It is quite common to see 4-dim data in climate science β€” latitude, longitude, altitude/pressure level, time." }, { "code": null, "e": 4881, "s": 4741, "text": "Try the following command and it gives you a graphical interface that lists all variables in your dataset, and it is quite straightforward." }, { "code": null, "e": 4927, "s": 4881, "text": "$ ncview twparmbeatmC1.c1.20050101.000000.cdf" }, { "code": null, "e": 5105, "s": 4927, "text": "xarray.DataArray is an implementation of a labelled, multi-dimensional array for a single variable, such as precipitation, temperature etc.. It has the following key properties:" }, { "code": null, "e": 5156, "s": 5105, "text": "values: a numpy.ndarray holding the array’s values" }, { "code": null, "e": 5228, "s": 5156, "text": "dims: dimension names for each axis (e.g., ('lat', 'lon', 'z', 'time'))" }, { "code": null, "e": 5366, "s": 5228, "text": "coords: a dict-like container of arrays (coordinates) that label each point (e.g., 1-dim arrays of numbers, DateTime objects, or strings)" }, { "code": null, "e": 5428, "s": 5366, "text": "attrs: an OrderedDict to hold arbitrary metadata (attributes)" }, { "code": null, "e": 5511, "s": 5428, "text": "xarray.DataSet is a collection of DataArrays. Each NetCDF file contains a DataSet." }, { "code": null, "e": 5675, "s": 5511, "text": "You cannot play with the data until you read it. Use open_dataset or open_mfdataset to read a single or multiple NetCDF files, and store it in a DataSet called DS." }, { "code": null, "e": 5904, "s": 5675, "text": "import xarray as xr# single filedataDIR = '../data/ARM/twparmbeatmC1.c1.20050101.000000.cdf'DS = xr.open_dataset(dataDIR)# OR multiple filesmfdataDIR = '../data/ARM/twparmbeatmC1.c1.*.000000.cdf'DS = xr.open_mfdataset(mfdataDIR)" }, { "code": null, "e": 6170, "s": 5904, "text": "Remember the 4 key properties of DataArrays? You can useDS.values, DS.var, DS.dims, DS.coords, and DS.attrs for data inspection. This will become very handy in interactive Python. Their functionalities are quite obvious and are left as an exercise to the reader(!)." }, { "code": null, "e": 6525, "s": 6170, "text": "Extracting DataArrays from DataSet DS is very straightforward, as DS.<var_name> will suffice. You might consider dropping NaN entries by dropna() and selecting data with sel(). The method parameter in sel() allows us to enable the nearest neighbour (inexact) lookups by use of the methods 'pad', 'backfill', or 'nearest'. To specify a range, use slice()." }, { "code": null, "e": 6587, "s": 6525, "text": "You can transform xr.DataArray to numpy.ndarray by da.values." }, { "code": null, "e": 6906, "s": 6587, "text": "# Extract Dry Bulb Temperature in z-coordinate (T_z)# Select the altitude nearest to 500m above surface# Drop NaN, convert to Celciusda = DS.T_z.sel(z=500,method='nearest').dropna(dim='time') - 273.15 # or .ffill(dim='time')# Select data in 2000sda = da.sel(time=slice('2000-01-01', '2009-12-31'))da_numpy = da.values" }, { "code": null, "e": 6996, "s": 6906, "text": "It is a convention to name DataSet as DS in upper case and DataArray as da in lower case." }, { "code": null, "e": 7190, "s": 6996, "text": "Assume DataArray da has a dimension timein DateTime format, We can extract the year/month/day/dayofyear/dayofweek by da.time.dt.<year/month/day/...>. Note that the output is still in DataArray." }, { "code": null, "e": 7603, "s": 7190, "text": "The following example takes one step further and tries to compute the mean/sum of any variable for each month. We first define a new coordinate system with assign_coords(). Why? Try looking into how year and month performs in DateTime. If we need the system to be aware of the differences between January 2000 and January 2001, we need both year and month to define a new coordinate, which we call it year_month." }, { "code": null, "e": 7736, "s": 7603, "text": "We can then group data by groupby('year_month') based on our newly defined coordinate system, followed by mean()or sum() operations." }, { "code": null, "e": 8163, "s": 7736, "text": "# Contract the DataArray by taking mean for each Year-Monthdef mean_in_year_month(da): # Index of Year-Month starts at Jan 1991 month_cnt_1991 = (da.time.dt.year.to_index() - 1991) * 12 + da.time.dt.month.to_index() # Assign newly defined Year-Month to coordinates, then group by it, then take the mean return da.assign_coords(year_month = month_cnt_1991).groupby('year_month').mean()da_1 = mean_in_year_month(da1)" }, { "code": null, "e": 8371, "s": 8163, "text": "We can merge multiple DataArrays using xr.merge(). If you attempt to merge two variables with the same name but with different values, xr.MergeError will be raised. This ensures xr.merge()is non-destructive." }, { "code": null, "e": 8432, "s": 8371, "text": "DS_new = xr.merge([da_1,da_2,da_3]).dropna(dim='year_month')" }, { "code": null, "e": 8664, "s": 8432, "text": "You can simply take DataArrays as arguments of matplotlib.pyplot methods. For absolute beginners, try plt.plot(), or plt.scatter() for line or scatter plots. Remember to show figures by plt.show(), or save figures by plt.savefig()." }, { "code": null, "e": 8723, "s": 8664, "text": "If you need maps, cartopy library can generate one easily." }, { "code": null, "e": 8903, "s": 8723, "text": "import cartopy.crs as ccrsimport matplotlib.pyplot as pltda = DS.t_sfc# Draw coastlines of the Earthax = plt.axes(projection=ccrs.PlateCarree())ax.coastlines() da.plot()plt.show()" }, { "code": null, "e": 8974, "s": 8903, "text": "With a few extra lines of codes, you can generate something like this:" }, { "code": null, "e": 9113, "s": 8974, "text": "You can convert DataArray to numpy.ndarray as explained earlier, or convert DataSet or DataArray to pandas.DataFrame as illustrated below." }, { "code": null, "e": 9136, "s": 9113, "text": "df = DS.to_dataframe()" }, { "code": null, "e": 9195, "s": 9136, "text": "You can also export DataArray or DataSet to NetCDF file by" }, { "code": null, "e": 9243, "s": 9195, "text": "dataDIR = '../data/new.nc'DS.to_netcdf(dataDIR)" }, { "code": null, "e": 9343, "s": 9243, "text": "If you are interested in Python or programming in general, the following articles might be helpful:" }, { "code": null, "e": 9366, "s": 9343, "text": "towardsdatascience.com" }, { "code": null, "e": 9389, "s": 9366, "text": "towardsdatascience.com" }, { "code": null, "e": 9498, "s": 9389, "text": "This tutorial was written for teaching purpose and only included the very basics of xarray. Hope this helps!" } ]
OOAD - Quick Guide
The object-oriented paradigm took its shape from the initial concept of a new programming approach, while the interest in design and analysis methods came much later. The first object–oriented language was Simula (Simulation of real systems) that was developed in 1960 by researchers at the Norwegian Computing Center. The first object–oriented language was Simula (Simulation of real systems) that was developed in 1960 by researchers at the Norwegian Computing Center. In 1970, Alan Kay and his research group at Xerox PARK created a personal computer named Dynabook and the first pure object-oriented programming language (OOPL) - Smalltalk, for programming the Dynabook. In 1970, Alan Kay and his research group at Xerox PARK created a personal computer named Dynabook and the first pure object-oriented programming language (OOPL) - Smalltalk, for programming the Dynabook. In the 1980s, Grady Booch published a paper titled Object Oriented Design that mainly presented a design for the programming language, Ada. In the ensuing editions, he extended his ideas to a complete object–oriented design method. In the 1980s, Grady Booch published a paper titled Object Oriented Design that mainly presented a design for the programming language, Ada. In the ensuing editions, he extended his ideas to a complete object–oriented design method. In the 1990s, Coad incorporated behavioral ideas to object-oriented methods. In the 1990s, Coad incorporated behavioral ideas to object-oriented methods. The other significant innovations were Object Modelling Techniques (OMT) by James Rumbaugh and Object-Oriented Software Engineering (OOSE) by Ivar Jacobson. Object–Oriented Analysis (OOA) is the procedure of identifying software engineering requirements and developing software specifications in terms of a software system’s object model, which comprises of interacting objects. The main difference between object-oriented analysis and other forms of analysis is that in object-oriented approach, requirements are organized around objects, which integrate both data and functions. They are modelled after real-world objects that the system interacts with. In traditional analysis methodologies, the two aspects - functions and data - are considered separately. Grady Booch has defined OOA as, β€œObject-oriented analysis is a method of analysis that examines requirements from the perspective of the classes and objects found in the vocabulary of the problem domain”. The primary tasks in object-oriented analysis (OOA) are βˆ’ Identifying objects Organizing the objects by creating object model diagram Defining the internals of the objects, or object attributes Defining the behavior of the objects, i.e., object actions Describing how the objects interact The common models used in OOA are use cases and object models. Object–Oriented Design (OOD) involves implementation of the conceptual model produced during object-oriented analysis. In OOD, concepts in the analysis model, which are technologyβˆ’independent, are mapped onto implementing classes, constraints are identified and interfaces are designed, resulting in a model for the solution domain, i.e., a detailed description of how the system is to be built on concrete technologies. The implementation details generally include βˆ’ Restructuring the class data (if necessary), Implementation of methods, i.e., internal data structures and algorithms, Implementation of control, and Implementation of associations. Grady Booch has defined object-oriented design as β€œa method of design encompassing the process of object-oriented decomposition and a notation for depicting both logical and physical as well as static and dynamic models of the system under design”. Object-oriented programming (OOP) is a programming paradigm based upon objects (having both data and methods) that aims to incorporate the advantages of modularity and reusability. Objects, which are usually instances of classes, are used to interact with one another to design applications and computer programs. The important features of object–oriented programming are βˆ’ Bottom–up approach in program design Programs organized around objects, grouped in classes Focus on data with methods to operate upon object’s data Interaction between objects through functions Reusability of design through creation of new classes by adding features to existing classes Some examples of object-oriented programming languages are C++, Java, Smalltalk, Delphi, C#, Perl, Python, Ruby, and PHP. Grady Booch has defined object–oriented programming as β€œa method of implementation in which programs are organized as cooperative collections of objects, each of which represents an instance of some class, and whose classes are all members of a hierarchy of classes united via inheritance relationships”. The object model visualizes the elements in a software application in terms of objects. In this chapter, we will look into the basic concepts and terminologies of object–oriented systems. The concepts of objects and classes are intrinsically linked with each other and form the foundation of object–oriented paradigm. An object is a real-world element in an object–oriented environment that may have a physical or a conceptual existence. Each object has βˆ’ Identity that distinguishes it from other objects in the system. Identity that distinguishes it from other objects in the system. State that determines the characteristic properties of an object as well as the values of the properties that the object holds. State that determines the characteristic properties of an object as well as the values of the properties that the object holds. Behavior that represents externally visible activities performed by an object in terms of changes in its state. Behavior that represents externally visible activities performed by an object in terms of changes in its state. Objects can be modelled according to the needs of the application. An object may have a physical existence, like a customer, a car, etc.; or an intangible conceptual existence, like a project, a process, etc. A class represents a collection of objects having same characteristic properties that exhibit common behavior. It gives the blueprint or description of the objects that can be created from it. Creation of an object as a member of a class is called instantiation. Thus, object is an instance of a class. The constituents of a class are βˆ’ A set of attributes for the objects that are to be instantiated from the class. Generally, different objects of a class have some difference in the values of the attributes. Attributes are often referred as class data. A set of attributes for the objects that are to be instantiated from the class. Generally, different objects of a class have some difference in the values of the attributes. Attributes are often referred as class data. A set of operations that portray the behavior of the objects of the class. Operations are also referred as functions or methods. A set of operations that portray the behavior of the objects of the class. Operations are also referred as functions or methods. Example Let us consider a simple class, Circle, that represents the geometrical figure circle in a two–dimensional space. The attributes of this class can be identified as follows βˆ’ x–coord, to denote x–coordinate of the center y–coord, to denote y–coordinate of the center a, to denote the radius of the circle Some of its operations can be defined as follows βˆ’ findArea(), method to calculate area findCircumference(), method to calculate circumference scale(), method to increase or decrease the radius During instantiation, values are assigned for at least some of the attributes. If we create an object my_circle, we can assign values like x-coord : 2, y-coord : 3, and a : 4 to depict its state. Now, if the operation scale() is performed on my_circle with a scaling factor of 2, the value of the variable a will become 8. This operation brings a change in the state of my_circle, i.e., the object has exhibited certain behavior. Encapsulation is the process of binding both attributes and methods together within a class. Through encapsulation, the internal details of a class can be hidden from outside. It permits the elements of the class to be accessed from outside only through the interface provided by the class. Typically, a class is designed such that its data (attributes) can be accessed only by its class methods and insulated from direct outside access. This process of insulating an object’s data is called data hiding or information hiding. Example In the class Circle, data hiding can be incorporated by making attributes invisible from outside the class and adding two more methods to the class for accessing class data, namely βˆ’ setValues(), method to assign values to x-coord, y-coord, and a getValues(), method to retrieve values of x-coord, y-coord, and a Here the private data of the object my_circle cannot be accessed directly by any method that is not encapsulated within the class Circle. It should instead be accessed through the methods setValues() and getValues(). Any application requires a number of objects interacting in a harmonious manner. Objects in a system may communicate with each other using message passing. Suppose a system has two objects: obj1 and obj2. The object obj1 sends a message to object obj2, if obj1 wants obj2 to execute one of its methods. The features of message passing are βˆ’ Message passing between two objects is generally unidirectional. Message passing enables all interactions between objects. Message passing essentially involves invoking class methods. Objects in different processes can be involved in message passing. Inheritance is the mechanism that permits new classes to be created out of existing classes by extending and refining its capabilities. The existing classes are called the base classes/parent classes/super-classes, and the new classes are called the derived classes/child classes/subclasses. The subclass can inherit or derive the attributes and methods of the super-class(es) provided that the super-class allows so. Besides, the subclass may add its own attributes and methods and may modify any of the super-class methods. Inheritance defines an β€œis – a” relationship. Example From a class Mammal, a number of classes can be derived such as Human, Cat, Dog, Cow, etc. Humans, cats, dogs, and cows all have the distinct characteristics of mammals. In addition, each has its own particular characteristics. It can be said that a cow β€œis – a” mammal. Single Inheritance βˆ’ A subclass derives from a single super-class. Single Inheritance βˆ’ A subclass derives from a single super-class. Multiple Inheritance βˆ’ A subclass derives from more than one super-classes. Multiple Inheritance βˆ’ A subclass derives from more than one super-classes. Multilevel Inheritance βˆ’ A subclass derives from a super-class which in turn is derived from another class and so on. Multilevel Inheritance βˆ’ A subclass derives from a super-class which in turn is derived from another class and so on. Hierarchical Inheritance βˆ’ A class has a number of subclasses each of which may have subsequent subclasses, continuing for a number of levels, so as to form a tree structure. Hierarchical Inheritance βˆ’ A class has a number of subclasses each of which may have subsequent subclasses, continuing for a number of levels, so as to form a tree structure. Hybrid Inheritance βˆ’ A combination of multiple and multilevel inheritance so as to form a lattice structure. Hybrid Inheritance βˆ’ A combination of multiple and multilevel inheritance so as to form a lattice structure. The following figure depicts the examples of different types of inheritance. Polymorphism is originally a Greek word that means the ability to take multiple forms. In object-oriented paradigm, polymorphism implies using operations in different ways, depending upon the instance they are operating upon. Polymorphism allows objects with different internal structures to have a common external interface. Polymorphism is particularly effective while implementing inheritance. Example Let us consider two classes, Circle and Square, each with a method findArea(). Though the name and purpose of the methods in the classes are same, the internal implementation, i.e., the procedure of calculating area is different for each class. When an object of class Circle invokes its findArea() method, the operation finds the area of the circle without any conflict with the findArea() method of the Square class. Generalization and specialization represent a hierarchy of relationships between classes, where subclasses inherit from super-classes. In the generalization process, the common characteristics of classes are combined to form a class in a higher level of hierarchy, i.e., subclasses are combined to form a generalized super-class. It represents an β€œis – a – kind – of” relationship. For example, β€œcar is a kind of land vehicle”, or β€œship is a kind of water vehicle”. Specialization is the reverse process of generalization. Here, the distinguishing features of groups of objects are used to form specialized classes from existing classes. It can be said that the subclasses are the specialized versions of the super-class. The following figure shows an example of generalization and specialization. A link represents a connection through which an object collaborates with other objects. Rumbaugh has defined it as β€œa physical or conceptual connection between objects”. Through a link, one object may invoke the methods or navigate through another object. A link depicts the relationship between two or more objects. Association is a group of links having common structure and common behavior. Association depicts the relationship between objects of one or more classes. A link can be defined as an instance of an association. Degree of an association denotes the number of classes involved in a connection. Degree may be unary, binary, or ternary. A unary relationship connects objects of the same class. A unary relationship connects objects of the same class. A binary relationship connects objects of two classes. A binary relationship connects objects of two classes. A ternary relationship connects objects of three or more classes. A ternary relationship connects objects of three or more classes. Cardinality of a binary association denotes the number of instances participating in an association. There are three types of cardinality ratios, namely βˆ’ One–to–One βˆ’ A single object of class A is associated with a single object of class B. One–to–One βˆ’ A single object of class A is associated with a single object of class B. One–to–Many βˆ’ A single object of class A is associated with many objects of class B. One–to–Many βˆ’ A single object of class A is associated with many objects of class B. Many–to–Many βˆ’ An object of class A may be associated with many objects of class B and conversely an object of class B may be associated with many objects of class A. Many–to–Many βˆ’ An object of class A may be associated with many objects of class B and conversely an object of class B may be associated with many objects of class A. Aggregation or composition is a relationship among classes by which a class can be made up of any combination of objects of other classes. It allows objects to be placed directly within the body of other classes. Aggregation is referred as a β€œpart–of” or β€œhas–a” relationship, with the ability to navigate from the whole to its parts. An aggregate object is an object that is composed of one or more other objects. Example In the relationship, β€œa car has–a motor”, car is the whole object or the aggregate, and the motor is a β€œpart–of” the car. Aggregation may denote βˆ’ Physical containment βˆ’ Example, a computer is composed of monitor, CPU, mouse, keyboard, and so on. Physical containment βˆ’ Example, a computer is composed of monitor, CPU, mouse, keyboard, and so on. Conceptual containment βˆ’ Example, shareholder has–a share. Conceptual containment βˆ’ Example, shareholder has–a share. Now that we have gone through the core concepts pertaining to object orientation, it would be worthwhile to note the advantages that this model has to offer. The benefits of using the object model are βˆ’ It helps in faster development of software. It helps in faster development of software. It is easy to maintain. Suppose a module develops an error, then a programmer can fix that particular module, while the other parts of the software are still up and running. It is easy to maintain. Suppose a module develops an error, then a programmer can fix that particular module, while the other parts of the software are still up and running. It supports relatively hassle-free upgrades. It supports relatively hassle-free upgrades. It enables reuse of objects, designs, and functions. It enables reuse of objects, designs, and functions. It reduces development risks, particularly in integration of complex systems. It reduces development risks, particularly in integration of complex systems. We know that the Object-Oriented Modelling (OOM) technique visualizes things in an application by using models organized around objects. Any software development approach goes through the following stages βˆ’ Analysis, Design, and Implementation. In object-oriented software engineering, the software developer identifies and organizes the application in terms of object-oriented concepts, prior to their final representation in any specific programming language or software tools. The major phases of software development using object–oriented methodology are object-oriented analysis, object-oriented design, and object-oriented implementation. In this stage, the problem is formulated, user requirements are identified, and then a model is built based upon real–world objects. The analysis produces models on how the desired system should function and how it must be developed. The models do not include any implementation details so that it can be understood and examined by any non–technical application expert. Object-oriented design includes two main stages, namely, system design and object design. System Design In this stage, the complete architecture of the desired system is designed. The system is conceived as a set of interacting subsystems that in turn is composed of a hierarchy of interacting objects, grouped into classes. System design is done according to both the system analysis model and the proposed system architecture. Here, the emphasis is on the objects comprising the system rather than the processes in the system. Object Design In this phase, a design model is developed based on both the models developed in the system analysis phase and the architecture designed in the system design phase. All the classes required are identified. The designer decides whether βˆ’ new classes are to be created from scratch, any existing classes can be used in their original form, or new classes should be inherited from the existing classes. The associations between the identified classes are established and the hierarchies of classes are identified. Besides, the developer designs the internal details of the classes and their associations, i.e., the data structure for each attribute and the algorithms for the operations. In this stage, the design model developed in the object design is translated into code in an appropriate programming language or software tool. The databases are created and the specific hardware requirements are ascertained. Once the code is in shape, it is tested using specialized techniques to identify and remove the errors in the code. The conceptual framework of object–oriented systems is based upon the object model. There are two categories of elements in an object-oriented system βˆ’ Major Elements βˆ’ By major, it is meant that if a model does not have any one of these elements, it ceases to be object oriented. The four major elements are βˆ’ Abstraction Encapsulation Modularity Hierarchy Minor Elements βˆ’ By minor, it is meant that these elements are useful, but not indispensable part of the object model. The three minor elements are βˆ’ Typing Concurrency Persistence Abstraction means to focus on the essential features of an element or object in OOP, ignoring its extraneous or accidental properties. The essential features are relative to the context in which the object is being used. Grady Booch has defined abstraction as follows βˆ’ β€œAn abstraction denotes the essential characteristics of an object that distinguish it from all other kinds of objects and thus provide crisply defined conceptual boundaries, relative to the perspective of the viewer.” Example βˆ’ When a class Student is designed, the attributes enrolment_number, name, course, and address are included while characteristics like pulse_rate and size_of_shoe are eliminated, since they are irrelevant in the perspective of the educational institution. Encapsulation is the process of binding both attributes and methods together within a class. Through encapsulation, the internal details of a class can be hidden from outside. The class has methods that provide user interfaces by which the services provided by the class may be used. Modularity is the process of decomposing a problem (program) into a set of modules so as to reduce the overall complexity of the problem. Booch has defined modularity as βˆ’ β€œModularity is the property of a system that has been decomposed into a set of cohesive and loosely coupled modules.” Modularity is intrinsically linked with encapsulation. Modularity can be visualized as a way of mapping encapsulated abstractions into real, physical modules having high cohesion within the modules and their inter–module interaction or coupling is low. In Grady Booch’s words, β€œHierarchy is the ranking or ordering of abstraction”. Through hierarchy, a system can be made up of interrelated subsystems, which can have their own subsystems and so on until the smallest level components are reached. It uses the principle of β€œdivide and conquer”. Hierarchy allows code reusability. The two types of hierarchies in OOA are βˆ’ β€œIS–A” hierarchy βˆ’ It defines the hierarchical relationship in inheritance, whereby from a super-class, a number of subclasses may be derived which may again have subclasses and so on. For example, if we derive a class Rose from a class Flower, we can say that a rose β€œis–a” flower. β€œIS–A” hierarchy βˆ’ It defines the hierarchical relationship in inheritance, whereby from a super-class, a number of subclasses may be derived which may again have subclasses and so on. For example, if we derive a class Rose from a class Flower, we can say that a rose β€œis–a” flower. β€œPART–OF” hierarchy βˆ’ It defines the hierarchical relationship in aggregation by which a class may be composed of other classes. For example, a flower is composed of sepals, petals, stamens, and carpel. It can be said that a petal is a β€œpart–of” flower. β€œPART–OF” hierarchy βˆ’ It defines the hierarchical relationship in aggregation by which a class may be composed of other classes. For example, a flower is composed of sepals, petals, stamens, and carpel. It can be said that a petal is a β€œpart–of” flower. According to the theories of abstract data type, a type is a characterization of a set of elements. In OOP, a class is visualized as a type having properties distinct from any other types. Typing is the enforcement of the notion that an object is an instance of a single class or type. It also enforces that objects of different types may not be generally interchanged; and can be interchanged only in a very restricted manner if absolutely required to do so. The two types of typing are βˆ’ Strong Typing βˆ’ Here, the operation on an object is checked at the time of compilation, as in the programming language Eiffel. Strong Typing βˆ’ Here, the operation on an object is checked at the time of compilation, as in the programming language Eiffel. Weak Typing βˆ’ Here, messages may be sent to any class. The operation is checked only at the time of execution, as in the programming language Smalltalk. Weak Typing βˆ’ Here, messages may be sent to any class. The operation is checked only at the time of execution, as in the programming language Smalltalk. Concurrency in operating systems allows performing multiple tasks or processes simultaneously. When a single process exists in a system, it is said that there is a single thread of control. However, most systems have multiple threads, some active, some waiting for CPU, some suspended, and some terminated. Systems with multiple CPUs inherently permit concurrent threads of control; but systems running on a single CPU use appropriate algorithms to give equitable CPU time to the threads so as to enable concurrency. In an object-oriented environment, there are active and inactive objects. The active objects have independent threads of control that can execute concurrently with threads of other objects. The active objects synchronize with one another as well as with purely sequential objects. An object occupies a memory space and exists for a particular period of time. In traditional programming, the lifespan of an object was typically the lifespan of the execution of the program that created it. In files or databases, the object lifespan is longer than the duration of the process creating the object. This property by which an object continues to exist even after its creator ceases to exist is known as persistence. In the system analysis or object-oriented analysis phase of software development, the system requirements are determined, the classes are identified and the relationships among classes are identified. The three analysis techniques that are used in conjunction with each other for object-oriented analysis are object modelling, dynamic modelling, and functional modelling. Object modelling develops the static structure of the software system in terms of objects. It identifies the objects, the classes into which the objects can be grouped into and the relationships between the objects. It also identifies the main attributes and operations that characterize each class. The process of object modelling can be visualized in the following steps βˆ’ Identify objects and group into classes Identify the relationships among classes Create user object model diagram Define user object attributes Define the operations that should be performed on the classes Review glossary After the static behavior of the system is analyzed, its behavior with respect to time and external changes needs to be examined. This is the purpose of dynamic modelling. Dynamic Modelling can be defined as β€œa way of describing how an individual object responds to events, either internal events triggered by other objects, or external events triggered by the outside world”. The process of dynamic modelling can be visualized in the following steps βˆ’ Identify states of each object Identify events and analyze the applicability of actions Construct dynamic model diagram, comprising of state transition diagrams Express each state in terms of object attributes Validate the state–transition diagrams drawn Functional Modelling is the final component of object-oriented analysis. The functional model shows the processes that are performed within an object and how the data changes as it moves between methods. It specifies the meaning of the operations of object modelling and the actions of dynamic modelling. The functional model corresponds to the data flow diagram of traditional structured analysis. The process of functional modelling can be visualized in the following steps βˆ’ Identify all the inputs and outputs Construct data flow diagrams showing functional dependencies State the purpose of each function Identify constraints Specify optimization criteria The Structured Analysis/Structured Design (SASD) approach is the traditional approach of software development based upon the waterfall model. The phases of development of a system using SASD are βˆ’ Feasibility Study Requirement Analysis and Specification System Design Implementation Post-implementation Review Now, we will look at the relative advantages and disadvantages of structured analysis approach and object-oriented analysis approach. The dynamic model represents the time–dependent aspects of a system. It is concerned with the temporal changes in the states of the objects in a system. The main concepts are βˆ’ State, which is the situation at a particular condition during the lifetime of an object. State, which is the situation at a particular condition during the lifetime of an object. Transition, a change in the state Transition, a change in the state Event, an occurrence that triggers transitions Event, an occurrence that triggers transitions Action, an uninterrupted and atomic computation that occurs due to some event, and Action, an uninterrupted and atomic computation that occurs due to some event, and Concurrency of transitions. Concurrency of transitions. A state machine models the behavior of an object as it passes through a number of states in its lifetime due to some events as well as the actions occurring due to the events. A state machine is graphically represented through a state transition diagram. The state is an abstraction given by the values of the attributes that the object has at a particular time period. It is a situation occurring for a finite time period in the lifetime of an object, in which it fulfils certain conditions, performs certain activities, or waits for certain events to occur. In state transition diagrams, a state is represented by rounded rectangles. Name βˆ’ A string differentiates one state from another. A state may not have any name. Name βˆ’ A string differentiates one state from another. A state may not have any name. Entry/Exit Actions βˆ’ It denotes the activities performed on entering and on exiting the state. Entry/Exit Actions βˆ’ It denotes the activities performed on entering and on exiting the state. Internal Transitions βˆ’ The changes within a state that do not cause a change in the state. Internal Transitions βˆ’ The changes within a state that do not cause a change in the state. Sub–states βˆ’ States within states. Sub–states βˆ’ States within states. The default starting state of an object is called its initial state. The final state indicates the completion of execution of the state machine. The initial and the final states are pseudo-states, and may not have the parts of a regular state except name. In state transition diagrams, the initial state is represented by a filled black circle. The final state is represented by a filled black circle encircled within another unfilled black circle. A transition denotes a change in the state of an object. If an object is in a certain state when an event occurs, the object may perform certain activities subject to specified conditions and change the state. In this case, a stateβˆ’transition is said to have occurred. The transition gives the relationship between the first state and the new state. A transition is graphically represented by a solid directed arc from the source state to the destination state. The five parts of a transition are βˆ’ Source State βˆ’ The state affected by the transition. Source State βˆ’ The state affected by the transition. Event Trigger βˆ’ The occurrence due to which an object in the source state undergoes a transition if the guard condition is satisfied. Event Trigger βˆ’ The occurrence due to which an object in the source state undergoes a transition if the guard condition is satisfied. Guard Condition βˆ’ A Boolean expression which if True, causes a transition on receiving the event trigger. Guard Condition βˆ’ A Boolean expression which if True, causes a transition on receiving the event trigger. Action βˆ’ An un-interruptible and atomic computation that occurs on the source object due to some event. Action βˆ’ An un-interruptible and atomic computation that occurs on the source object due to some event. Target State βˆ’ The destination state after completion of transition. Target State βˆ’ The destination state after completion of transition. Example Suppose a person is taking a taxi from place X to place Y. The states of the person may be: Waiting (waiting for taxi), Riding (he has got a taxi and is travelling in it), and Reached (he has reached the destination). The following figure depicts the state transition. Events are some occurrences that can trigger state transition of an object or a group of objects. Events have a location in time and space but do not have a time period associated with it. Events are generally associated with some actions. Examples of events are mouse click, key press, an interrupt, stack overflow, etc. Events that trigger transitions are written alongside the arc of transition in state diagrams. Example Considering the example shown in the above figure, the transition from Waiting state to Riding state takes place when the person gets a taxi. Likewise, the final state is reached, when he reaches the destination. These two occurrences can be termed as events Get_Taxi and Reach_Destination. The following figure shows the events in a state machine. External events are those events that pass from a user of the system to the objects within the system. For example, mouse click or keyβˆ’press by the user are external events. Internal events are those that pass from one object to another object within a system. For example, stack overflow, a divide error, etc. Deferred events are those which are not immediately handled by the object in the current state but are lined up in a queue so that they can be handled by the object in some other state at a later time. Event class indicates a group of events with common structure and behavior. As with classes of objects, event classes may also be organized in a hierarchical structure. Event classes may have attributes associated with them, time being an implicit attribute. For example, we can consider the events of departure of a flight of an airline, which we can group into the following class βˆ’ Flight_Departs (Flight_No, From_City, To_City, Route) Activity is an operation upon the states of an object that requires some time period. They are the ongoing executions within a system that can be interrupted. Activities are shown in activity diagrams that portray the flow from one activity to another. An action is an atomic operation that executes as a result of certain events. By atomic, it is meant that actions are un-interruptible, i.e., if an action starts executing, it runs into completion without being interrupted by any event. An action may operate upon an object on which an event has been triggered or on other objects that are visible to this object. A set of actions comprise an activity. Entry action is the action that is executed on entering a state, irrespective of the transition that led into it. Likewise, the action that is executed while leaving a state, irrespective of the transition that led out of it, is called an exit action. Scenario is a description of a specified sequence of actions. It depicts the behavior of objects undergoing a specific action series. The primary scenarios depict the essential sequences and the secondary scenarios depict the alternative sequences. There are two primary diagrams that are used for dynamic modelling βˆ’ Interaction diagrams describe the dynamic behavior among different objects. It comprises of a set of objects, their relationships, and the message that the objects send and receive. Thus, an interaction models the behavior of a group of interrelated objects. The two types of interaction diagrams are βˆ’ Sequence Diagram βˆ’ It represents the temporal ordering of messages in a tabular manner. Sequence Diagram βˆ’ It represents the temporal ordering of messages in a tabular manner. Collaboration Diagram βˆ’ It represents the structural organization of objects that send and receive messages through vertices and arcs. Collaboration Diagram βˆ’ It represents the structural organization of objects that send and receive messages through vertices and arcs. State transition diagrams or state machines describe the dynamic behavior of a single object. It illustrates the sequences of states that an object goes through in its lifetime, the transitions of the states, the events and conditions causing the transition and the responses due to the events. In a system, two types of concurrency may exist. They are βˆ’ Here, concurrency is modelled in the system level. The overall system is modelled as the aggregation of state machines, where each state machine executes concurrently with others. Here, an object can issue concurrent events. An object may have states that are composed of sub-states, and concurrent events may occur in each of the sub-states. Concepts related to concurrency within an object are as follows βˆ’ A simple state has no sub-structure. A state that has simpler states nested inside it is called a composite state. A sub-state is a state that is nested inside another state. It is generally used to reduce the complexity of a state machine. Sub-states can be nested to any number of levels. Composite states may have either sequential sub-states or concurrent sub-states. In sequential sub-states, the control of execution passes from one sub-state to another sub-state one after another in a sequential manner. There is at most one initial state and one final state in these state machines. The following figure illustrates the concept of sequential sub-states. In concurrent sub-states, the sub-states execute in parallel, or in other words, each state has concurrently executing state machines within it. Each of the state machines has its own initial and final states. If one concurrent sub-state reaches its final state before the other, control waits at its final state. When all the nested state machines reach their final states, the sub-states join back to a single flow. The following figure shows the concept of concurrent sub-states. Functional Modelling gives the process perspective of the object-oriented analysis model and an overview of what the system is supposed to do. It defines the function of the internal processes in the system with the aid of Data Flow Diagrams (DFDs). It depicts the functional derivation of the data values without indicating how they are derived when they are computed, or why they need to be computed. Functional Modelling is represented through a hierarchy of DFDs. The DFD is a graphical representation of a system that shows the inputs to the system, the processing upon the inputs, the outputs of the system as well as the internal data stores. DFDs illustrate the series of transformations or computations performed on the objects or the system, and the external controls and objects that affect the transformation. Rumbaugh et al. have defined DFD as, β€œA data flow diagram is a graph which shows the flow of data values from their sources in objects through processes that transform them to their destinations on other objects.” The four main parts of a DFD are βˆ’ Processes, Data Flows, Actors, and Data Stores. The other parts of a DFD are βˆ’ Constraints, and Control Flows. Processes are the computational activities that transform data values. A whole system can be visualized as a high-level process. A process may be further divided into smaller components. The lowest-level process may be a simple function. Representation in DFD βˆ’ A process is represented as an ellipse with its name written inside it and contains a fixed number of input and output data values. Example βˆ’ The following figure shows a process Compute_HCF_LCM that accepts two integers as inputs and outputs their HCF (highest common factor) and LCM (least common multiple). Data flow represents the flow of data between two processes. It could be between an actor and a process, or between a data store and a process. A data flow denotes the value of a data item at some point of the computation. This value is not changed by the data flow. Representation in DFD βˆ’ A data flow is represented by a directed arc or an arrow, labelled with the name of the data item that it carries. In the above figure, Integer_a and Integer_b represent the input data flows to the process, while L.C.M. and H.C.F. are the output data flows. A data flow may be forked in the following cases βˆ’ The output value is sent to several places as shown in the following figure. Here, the output arrows are unlabelled as they denote the same value. The output value is sent to several places as shown in the following figure. Here, the output arrows are unlabelled as they denote the same value. The data flow contains an aggregate value, and each of the components is sent to different places as shown in the following figure. Here, each of the forked components is labelled. The data flow contains an aggregate value, and each of the components is sent to different places as shown in the following figure. Here, each of the forked components is labelled. Actors are the active objects that interact with the system by either producing data and inputting them to the system, or consuming data produced by the system. In other words, actors serve as the sources and the sinks of data. Representation in DFD βˆ’ An actor is represented by a rectangle. Actors are connected to the inputs and outputs and lie on the boundary of the DFD. Example βˆ’ The following figure shows the actors, namely, Customer and Sales_Clerk in a counter sales system. Data stores are the passive objects that act as a repository of data. Unlike actors, they cannot perform any operations. They are used to store data and retrieve the stored data. They represent a data structure, a disk file, or a table in a database. Representation in DFD βˆ’ A data store is represented by two parallel lines containing the name of the data store. Each data store is connected to at least one process. Input arrows contain information to modify the contents of the data store, while output arrows contain information retrieved from the data store. When a part of the information is to be retrieved, the output arrow is labelled. An unlabelled arrow denotes full data retrieval. A two-way arrow implies both retrieval and update. Example βˆ’ The following figure shows a data store, Sales_Record, that stores the details of all sales. Input to the data store comprises of details of sales such as item, billing amount, date, etc. To find the average sales, the process retrieves the sales records and computes the average. Constraints specify the conditions or restrictions that need to be satisfied over time. They allow adding new rules or modifying existing ones. Constraints can appear in all the three models of object-oriented analysis. In Object Modelling, the constraints define the relationship between objects. They may also define the relationship between the different values that an object may take at different times. In Object Modelling, the constraints define the relationship between objects. They may also define the relationship between the different values that an object may take at different times. In Dynamic Modelling, the constraints define the relationship between the states and events of different objects. In Dynamic Modelling, the constraints define the relationship between the states and events of different objects. In Functional Modelling, the constraints define the restrictions on the transformations and computations. In Functional Modelling, the constraints define the restrictions on the transformations and computations. Representation βˆ’ A constraint is rendered as a string within braces. Example βˆ’ The following figure shows a portion of DFD for computing the salary of employees of a company that has decided to give incentives to all employees of the sales department and increment the salary of all employees of the HR department. It can be seen that the constraint {Dept:Sales} causes incentive to be calculated only if the department is sales and the constraint {Dept:HR} causes increment to be computed only if the department is HR. A process may be associated with a certain Boolean value and is evaluated only if the value is true, though it is not a direct input to the process. These Boolean values are called the control flows. Representation in DFD βˆ’ Control flows are represented by a dotted arc from the process producing the Boolean value to the process controlled by them. Example βˆ’ The following figure represents a DFD for arithmetic division. The Divisor is tested for non-zero. If it is not zero, the control flow OK has a value True and subsequently the Divide process computes the Quotient and the Remainder. In order to develop the DFD model of a system, a hierarchy of DFDs are constructed. The top-level DFD comprises of a single process and the actors interacting with it. At each successive lower level, further details are gradually included. A process is decomposed into sub-processes, the data flows among the sub-processes are identified, the control flows are determined, and the data stores are defined. While decomposing a process, the data flow into or out of the process should match the data flow at the next level of DFD. Example βˆ’ Let us consider a software system, Wholesaler Software, that automates the transactions of a wholesale shop. The shop sells in bulks and has a clientele comprising of merchants and retail shop owners. Each customer is asked to register with his/her particulars and is given a unique customer code, C_Code. Once a sale is done, the shop registers its details and sends the goods for dispatch. Each year, the shop distributes Christmas gifts to its customers, which comprise of a silver coin or a gold coin depending upon the total sales and the decision of the proprietor. The functional model for the Wholesale Software is given below. The figure below shows the top-level DFD. It shows the software as a single process and the actors that interact with it. The actors in the system are βˆ’ Customers Salesperson Proprietor In the next level DFD, as shown in the following figure, the major processes of the system are identified, the data stores are defined and the interaction of the processes with the actors, and the data stores are established. In the system, three processes can be identified, which are βˆ’ Register Customers Process Sales Ascertain Gifts The data stores that will be required are βˆ’ Customer Details Sales Details Gift Details The following figure shows the details of the process Register Customer. There are three processes in it, Verify Details, Generate C_Code, and Update Customer Details. When the details of the customer are entered, they are verified. If the data is correct, C_Code is generated and the data store Customer Details is updated. The following figure shows the expansion of the process Ascertain Gifts. It has two processes in it, Find Total Sales and Decide Type of Gift Coin. The Find Total Sales process computes the yearly total sales corresponding to each customer and records the data. Taking this record and the decision of the proprietor as inputs, the gift coins are allotted through Decide Type of Gift Coin process. The Object Model, the Dynamic Model, and the Functional Model are complementary to each other for a complete Object-Oriented Analysis. Object modelling develops the static structure of the software system in terms of objects. Thus it shows the β€œdoers” of a system. Object modelling develops the static structure of the software system in terms of objects. Thus it shows the β€œdoers” of a system. Dynamic Modelling develops the temporal behavior of the objects in response to external events. It shows the sequences of operations performed on the objects. Dynamic Modelling develops the temporal behavior of the objects in response to external events. It shows the sequences of operations performed on the objects. Functional model gives an overview of what the system should do. Functional model gives an overview of what the system should do. The four main parts of a Functional Model in terms of object model are βˆ’ Process βˆ’ Processes imply the methods of the objects that need to be implemented. Process βˆ’ Processes imply the methods of the objects that need to be implemented. Actors βˆ’ Actors are the objects in the object model. Actors βˆ’ Actors are the objects in the object model. Data Stores βˆ’ These are either objects in the object model or attributes of objects. Data Stores βˆ’ These are either objects in the object model or attributes of objects. Data Flows βˆ’ Data flows to or from actors represent operations on or by objects. Data flows to or from data stores represent queries or updates. Data Flows βˆ’ Data flows to or from actors represent operations on or by objects. Data flows to or from data stores represent queries or updates. The dynamic model states when the operations are performed, while the functional model states how they are performed and which arguments are needed. As actors are active objects, the dynamic model has to specify when it acts. The data stores are passive objects and they only respond to updates and queries; therefore the dynamic model need not specify when they act. The dynamic model shows the status of the objects and the operations performed on the occurrences of events and the subsequent changes in states. The state of the object as a result of the changes is shown in the object model. The Unified Modeling Language (UML) is a graphical language for OOAD that gives a standard way to write a software system’s blueprint. It helps to visualize, specify, construct, and document the artifacts of an object-oriented system. It is used to depict the structures and the relationships in a complex system. It was developed in 1990s as an amalgamation of several techniques, prominently OOAD technique by Grady Booch, OMT (Object Modeling Technique) by James Rumbaugh, and OOSE (Object Oriented Software Engineering) by Ivar Jacobson. UML attempted to standardize semantic models, syntactic notations, and diagrams of OOAD. System βˆ’ A set of elements organized to achieve certain objectives form a system. Systems are often divided into subsystems and described by a set of models. Model βˆ’ Model is a simplified, complete, and consistent abstraction of a system, created for better understanding of the system. View βˆ’ A view is a projection of a system’s model from a specific perspective. The Conceptual Model of UML encompasses three major elements βˆ’ Basic building blocks Rules Common mechanisms The three building blocks of UML are βˆ’ Things Relationships Diagrams There are four kinds of things in UML, namely βˆ’ Structural Things βˆ’ These are the nouns of the UML models representing the static elements that may be either physical or conceptual. The structural things are class, interface, collaboration, use case, active class, components, and nodes. Structural Things βˆ’ These are the nouns of the UML models representing the static elements that may be either physical or conceptual. The structural things are class, interface, collaboration, use case, active class, components, and nodes. Behavioral Things βˆ’ These are the verbs of the UML models representing the dynamic behavior over time and space. The two types of behavioral things are interaction and state machine. Behavioral Things βˆ’ These are the verbs of the UML models representing the dynamic behavior over time and space. The two types of behavioral things are interaction and state machine. Grouping Things βˆ’ They comprise the organizational parts of the UML models. There is only one kind of grouping thing, i.e., package. Grouping Things βˆ’ They comprise the organizational parts of the UML models. There is only one kind of grouping thing, i.e., package. Annotational Things βˆ’ These are the explanations in the UML models representing the comments applied to describe elements. Annotational Things βˆ’ These are the explanations in the UML models representing the comments applied to describe elements. Relationships are the connection between things. The four types of relationships that can be represented in UML are βˆ’ Dependency βˆ’ This is a semantic relationship between two things such that a change in one thing brings a change in the other. The former is the independent thing, while the latter is the dependent thing. Dependency βˆ’ This is a semantic relationship between two things such that a change in one thing brings a change in the other. The former is the independent thing, while the latter is the dependent thing. Association βˆ’ This is a structural relationship that represents a group of links having common structure and common behavior. Association βˆ’ This is a structural relationship that represents a group of links having common structure and common behavior. Generalization βˆ’ This represents a generalization/specialization relationship in which subclasses inherit structure and behavior from super-classes. Generalization βˆ’ This represents a generalization/specialization relationship in which subclasses inherit structure and behavior from super-classes. Realization βˆ’ This is a semantic relationship between two or more classifiers such that one classifier lays down a contract that the other classifiers ensure to abide by. Realization βˆ’ This is a semantic relationship between two or more classifiers such that one classifier lays down a contract that the other classifiers ensure to abide by. A diagram is a graphical representation of a system. It comprises of a group of elements generally in the form of a graph. UML includes nine diagrams in all, namely βˆ’ Class Diagram Object Diagram Use Case Diagram Sequence Diagram Collaboration Diagram State Chart Diagram Activity Diagram Component Diagram Deployment Diagram UML has a number of rules so that the models are semantically self-consistent and related to other models in the system harmoniously. UML has semantic rules for the following βˆ’ Names Scope Visibility Integrity Execution UML has four common mechanisms βˆ’ Specifications Adornments Common Divisions Extensibility Mechanisms In UML, behind each graphical notation, there is a textual statement denoting the syntax and semantics. These are the specifications. The specifications provide a semantic backplane that contains all the parts of a system and the relationship among the different paths. Each element in UML has a unique graphical notation. Besides, there are notations to represent the important aspects of an element like name, scope, visibility, etc. Object-oriented systems can be divided in many ways. The two common ways of division are βˆ’ Division of classes and objects βˆ’ A class is an abstraction of a group of similar objects. An object is the concrete instance that has actual existence in the system. Division of classes and objects βˆ’ A class is an abstraction of a group of similar objects. An object is the concrete instance that has actual existence in the system. Division of Interface and Implementation βˆ’ An interface defines the rules for interaction. Implementation is the concrete realization of the rules defined in the interface. Division of Interface and Implementation βˆ’ An interface defines the rules for interaction. Implementation is the concrete realization of the rules defined in the interface. UML is an open-ended language. It is possible to extend the capabilities of UML in a controlled manner to suit the requirements of a system. The extensibility mechanisms are βˆ’ Stereotypes βˆ’ It extends the vocabulary of the UML, through which new building blocks can be created out of existing ones. Stereotypes βˆ’ It extends the vocabulary of the UML, through which new building blocks can be created out of existing ones. Tagged Values βˆ’ It extends the properties of UML building blocks. Tagged Values βˆ’ It extends the properties of UML building blocks. Constraints βˆ’ It extends the semantics of UML building blocks. Constraints βˆ’ It extends the semantics of UML building blocks. UML defines specific notations for each of the building blocks. A class is represented by a rectangle having three sections βˆ’ the top section containing the name of the class the middle section containing class attributes the bottom section representing operations of the class The visibility of the attributes and operations can be represented in the following ways βˆ’ Public βˆ’ A public member is visible from anywhere in the system. In class diagram, it is prefixed by the symbol β€˜+’. Public βˆ’ A public member is visible from anywhere in the system. In class diagram, it is prefixed by the symbol β€˜+’. Private βˆ’ A private member is visible only from within the class. It cannot be accessed from outside the class. A private member is prefixed by the symbol β€˜βˆ’β€™. Private βˆ’ A private member is visible only from within the class. It cannot be accessed from outside the class. A private member is prefixed by the symbol β€˜βˆ’β€™. Protected βˆ’ A protected member is visible from within the class and from the subclasses inherited from this class, but not from outside. It is prefixed by the symbol β€˜#’. Protected βˆ’ A protected member is visible from within the class and from the subclasses inherited from this class, but not from outside. It is prefixed by the symbol β€˜#’. An abstract class has the class name written in italics. Example βˆ’ Let us consider the Circle class introduced earlier. The attributes of Circle are x-coord, y-coord, and radius. The operations are findArea(), findCircumference(), and scale(). Let us assume that x-coord and y-coord are private data members, radius is a protected data member, and the member functions are public. The following figure gives the diagrammatic representation of the class. An object is represented as a rectangle with two sections βˆ’ The top section contains the name of the object with the name of the class or package of which it is an instance of. The name takes the following forms βˆ’ object-name βˆ’ class-name object-name βˆ’ class-name :: package-name class-name βˆ’ in case of anonymous objects The top section contains the name of the object with the name of the class or package of which it is an instance of. The name takes the following forms βˆ’ object-name βˆ’ class-name object-name βˆ’ class-name object-name βˆ’ class-name :: package-name object-name βˆ’ class-name :: package-name class-name βˆ’ in case of anonymous objects class-name βˆ’ in case of anonymous objects The bottom section represents the values of the attributes. It takes the form attribute-name = value. The bottom section represents the values of the attributes. It takes the form attribute-name = value. Sometimes objects are represented using rounded rectangles. Sometimes objects are represented using rounded rectangles. Example βˆ’ Let us consider an object of the class Circle named c1. We assume that the center of c1 is at (2, 3) and the radius of c1 is 5. The following figure depicts the object. A component is a physical and replaceable part of the system that conforms to and provides the realization of a set of interfaces. It represents the physical packaging of elements like classes and interfaces. Notation βˆ’ In UML diagrams, a component is represented by a rectangle with tabs as shown in the figure below. Interface is a collection of methods of a class or component. It specifies the set of services that may be provided by the class or component. Notation βˆ’ Generally, an interface is drawn as a circle together with its name. An interface is almost always attached to the class or component that realizes it. The following figure gives the notation of an interface. A package is an organized group of elements. A package may contain structural things like classes, components, and other packages in it. Notation βˆ’ Graphically, a package is represented by a tabbed folder. A package is generally drawn with only its name. However it may have additional details about the contents of the package. See the following figures. The notations for the different types of relationships are as follows βˆ’ Usually, elements in a relationship play specific roles in the relationship. A role name signifies the behavior of an element participating in a certain context. Example βˆ’ The following figures show examples of different relationships between classes. The first figure shows an association between two classes, Department and Employee, wherein a department may have a number of employees working in it. Worker is the role name. The β€˜1’ alongside Department and β€˜*’ alongside Employee depict that the cardinality ratio is one–to–many. The second figure portrays the aggregation relationship, a University is the β€œwhole–of” many Departments. UML structural diagrams are categorized as follows: class diagram, object diagram, component diagram, and deployment diagram. A class diagram models the static view of a system. It comprises of the classes, interfaces, and collaborations of a system; and the relationships between them. Let us consider a simplified Banking System. A bank has many branches. In each zone, one branch is designated as the zonal head office that supervises the other branches in that zone. Each branch can have multiple accounts and loans. An account may be either a savings account or a current account. A customer may open both a savings account and a current account. However, a customer must not have more than one savings account or current account. A customer may also procure loans from the bank. The following figure shows the corresponding class diagram. Bank, Branch, Account, Savings Account, Current Account, Loan, and Customer. A Bank β€œhas–a” number of Branches βˆ’ composition, one–to–many A Bank β€œhas–a” number of Branches βˆ’ composition, one–to–many A Branch with role Zonal Head Office supervises other Branches βˆ’ unary association, one–to-many A Branch with role Zonal Head Office supervises other Branches βˆ’ unary association, one–to-many A Branch β€œhas–a” number of accounts βˆ’ aggregation, one–to–many A Branch β€œhas–a” number of accounts βˆ’ aggregation, one–to–many From the class Account, two classes have inherited, namely, Savings Account and Current Account. A Customer can have one Current Account βˆ’ association, one–to–one A Customer can have one Current Account βˆ’ association, one–to–one A Customer can have one Savings Account βˆ’ association, one–to–one A Customer can have one Savings Account βˆ’ association, one–to–one A Branch β€œhas–a” number of Loans βˆ’ aggregation, one–to–many A Branch β€œhas–a” number of Loans βˆ’ aggregation, one–to–many A Customer can take many loans βˆ’ association, one–to–many A Customer can take many loans βˆ’ association, one–to–many An object diagram models a group of objects and their links at a point of time. It shows the instances of the things in a class diagram. Object diagram is the static part of an interaction diagram. Example βˆ’ The following figure shows an object diagram of a portion of the class diagram of the Banking System. Component diagrams show the organization and dependencies among a group of components. Component diagrams comprise of βˆ’ Components Interfaces Relationships Packages and Subsystems (optional) Component diagrams are used for βˆ’ constructing systems through forward and reverse engineering. constructing systems through forward and reverse engineering. modeling configuration management of source code files while developing a system using an object-oriented programming language. modeling configuration management of source code files while developing a system using an object-oriented programming language. representing schemas in modeling databases. representing schemas in modeling databases. modeling behaviors of dynamic systems. modeling behaviors of dynamic systems. Example The following figure shows a component diagram to model a system’s source code that is developed using C++. It shows four source code files, namely, myheader.h, otherheader.h, priority.cpp, and other.cpp. Two versions of myheader.h are shown, tracing from the recent version to its ancestor. The file priority.cpp has compilation dependency on other.cpp. The file other.cpp has compilation dependency on otherheader.h. A deployment diagram puts emphasis on the configuration of runtime processing nodes and their components that live on them. They are commonly comprised of nodes and dependencies, or associations between the nodes. Deployment diagrams are used to βˆ’ model devices in embedded systems that typically comprise of software-intensive collection of hardware. model devices in embedded systems that typically comprise of software-intensive collection of hardware. represent the topologies of client/server systems. represent the topologies of client/server systems. model fully distributed systems. model fully distributed systems. Example The following figure shows the topology of a computer system that follows client/server architecture. The figure illustrates a node stereotyped as server that comprises of processors. The figure indicates that four or more servers are deployed at the system. Connected to the server are the client nodes, where each node represents a terminal device such as workstation, laptop, scanner, or printer. The nodes are represented using icons that clearly depict the real-world equivalent. UML behavioral diagrams visualize, specify, construct, and document the dynamic aspects of a system. The behavioral diagrams are categorized as follows: use case diagrams, interaction diagrams, state–chart diagrams, and activity diagrams. A use case describes the sequence of actions a system performs yielding visible results. It shows the interaction of things outside the system with the system itself. Use cases may be applied to the whole system as well as a part of the system. An actor represents the roles that the users of the use cases play. An actor may be a person (e.g. student, customer), a device (e.g. workstation), or another system (e.g. bank, institution). The following figure shows the notations of an actor named Student and a use case called Generate Performance Report. Use case diagrams present an outside view of the manner the elements in a system behave and how they can be used in the context. Use case diagrams comprise of βˆ’ Use cases Actors Relationships like dependency, generalization, and association Use case diagrams are used βˆ’ To model the context of a system by enclosing all the activities of a system within a rectangle and focusing on the actors outside the system by interacting with it. To model the context of a system by enclosing all the activities of a system within a rectangle and focusing on the actors outside the system by interacting with it. To model the requirements of a system from the outside point of view. To model the requirements of a system from the outside point of view. Example Let us consider an Automated Trading House System. We assume the following features of the system βˆ’ The trading house has transactions with two types of customers, individual customers and corporate customers. The trading house has transactions with two types of customers, individual customers and corporate customers. Once the customer places an order, it is processed by the sales department and the customer is given the bill. Once the customer places an order, it is processed by the sales department and the customer is given the bill. The system allows the manager to manage customer accounts and answer any queries posted by the customer. The system allows the manager to manage customer accounts and answer any queries posted by the customer. Interaction diagrams depict interactions of objects and their relationships. They also include the messages passed between them. There are two types of interaction diagrams βˆ’ Sequence Diagrams Collaboration Diagrams the control flow by time ordering using sequence diagrams. the control flow by time ordering using sequence diagrams. the control flow of organization using collaboration diagrams. the control flow of organization using collaboration diagrams. Sequence diagrams are interaction diagrams that illustrate the ordering of messages according to time. Notations βˆ’ These diagrams are in the form of two-dimensional charts. The objects that initiate the interaction are placed on the x–axis. The messages that these objects send and receive are placed along the y–axis, in the order of increasing time from top to bottom. Example βˆ’ A sequence diagram for the Automated Trading House System is shown in the following figure. Collaboration diagrams are interaction diagrams that illustrate the structure of the objects that send and receive messages. Notations βˆ’ In these diagrams, the objects that participate in the interaction are shown using vertices. The links that connect the objects are used to send and receive messages. The message is shown as a labeled arrow. Example βˆ’ Collaboration diagram for the Automated Trading House System is illustrated in the figure below. A state–chart diagram shows a state machine that depicts the control flow of an object from one state to another. A state machine portrays the sequences of states which an object undergoes due to events and their responses to events. State–Chart Diagrams comprise of βˆ’ States: Simple or Composite Transitions between states Events causing transitions Actions due to the events State-chart diagrams are used for modeling objects which are reactive in nature. Example In the Automated Trading House System, let us model Order as an object and trace its sequence. The following figure shows the corresponding state–chart diagram. An activity diagram depicts the flow of activities which are ongoing non-atomic operations in a state machine. Activities result in actions which are atomic operations. Activity diagrams comprise of βˆ’ Activity states and action states Transitions Objects Activity diagrams are used for modeling βˆ’ workflows as viewed by actors, interacting with the system. details of operations or computations using flowcharts. Example The following figure shows an activity diagram of a portion of the Automated Trading House System. After the analysis phase, the conceptual model is developed further into an object-oriented model using object-oriented design (OOD). In OOD, the technology-independent concepts in the analysis model are mapped onto implementing classes, constraints are identified, and interfaces are designed, resulting in a model for the solution domain. In a nutshell, a detailed description is constructed specifying how the system is to be built on concrete technologies The stages for object–oriented design can be identified as βˆ’ Definition of the context of the system Designing system architecture Identification of the objects in the system Construction of design models Specification of object interfaces Object-oriented system design involves defining the context of a system followed by designing the architecture of the system. Context βˆ’ The context of a system has a static and a dynamic part. The static context of the system is designed using a simple block diagram of the whole system which is expanded into a hierarchy of subsystems. The subsystem model is represented by UML packages. The dynamic context describes how the system interacts with its environment. It is modelled using use case diagrams. Context βˆ’ The context of a system has a static and a dynamic part. The static context of the system is designed using a simple block diagram of the whole system which is expanded into a hierarchy of subsystems. The subsystem model is represented by UML packages. The dynamic context describes how the system interacts with its environment. It is modelled using use case diagrams. System Architecture βˆ’ The system architecture is designed on the basis of the context of the system in accordance with the principles of architectural design as well as domain knowledge. Typically, a system is partitioned into layers and each layer is decomposed to form the subsystems. System Architecture βˆ’ The system architecture is designed on the basis of the context of the system in accordance with the principles of architectural design as well as domain knowledge. Typically, a system is partitioned into layers and each layer is decomposed to form the subsystems. Decomposition means dividing a large complex system into a hierarchy of smaller components with lesser complexities, on the principles of divide–and–conquer. Each major component of the system is called a subsystem. Object-oriented decomposition identifies individual autonomous objects in a system and the communication among these objects. The advantages of decomposition are βˆ’ The individual components are of lesser complexity, and so more understandable and manageable. The individual components are of lesser complexity, and so more understandable and manageable. It enables division of workforce having specialized skills. It enables division of workforce having specialized skills. It allows subsystems to be replaced or modified without affecting other subsystems. It allows subsystems to be replaced or modified without affecting other subsystems. Concurrency allows more than one objects to receive events at the same time and more than one activity to be executed simultaneously. Concurrency is identified and represented in the dynamic model. To enable concurrency, each concurrent element is assigned a separate thread of control. If the concurrency is at object level, then two concurrent objects are assigned two different threads of control. If two operations of a single object are concurrent in nature, then that object is split among different threads. Concurrency is associated with the problems of data integrity, deadlock, and starvation. So a clear strategy needs to be made whenever concurrency is required. Besides, concurrency requires to be identified at the design stage itself, and cannot be left for implementation stage. While designing applications, some commonly accepted solutions are adopted for some categories of problems. These are the patterns of design. A pattern can be defined as a documented set of building blocks that can be used in certain types of application development problems. Some commonly used design patterns are βˆ’ FacΜ§ade pattern Model view separation pattern Observer pattern Model view controller pattern Publish subscribe pattern Proxy pattern During system design, the events that may occur in the objects of the system need to be identified and appropriately dealt with. An event is a specification of a significant occurrence that has a location in time and space. There are four types of events that can be modelled, namely βˆ’ Signal Event βˆ’ A named object thrown by one object and caught by another object. Signal Event βˆ’ A named object thrown by one object and caught by another object. Call Event βˆ’ A synchronous event representing dispatch of an operation. Call Event βˆ’ A synchronous event representing dispatch of an operation. Time Event βˆ’ An event representing passage of time. Time Event βˆ’ An event representing passage of time. Change Event βˆ’ An event representing change in state. Change Event βˆ’ An event representing change in state. The system design phase needs to address the initialization and the termination of the system as a whole as well as each subsystem. The different aspects that are documented are as follows βˆ’ The start–up of the system, i.e., the transition of the system from non-initialized state to steady state. The start–up of the system, i.e., the transition of the system from non-initialized state to steady state. The termination of the system, i.e., the closing of all running threads, cleaning up of resources, and the messages to be sent. The termination of the system, i.e., the closing of all running threads, cleaning up of resources, and the messages to be sent. The initial configuration of the system and the reconfiguration of the system when needed. The initial configuration of the system and the reconfiguration of the system when needed. Foreseeing failures or undesired termination of the system. Foreseeing failures or undesired termination of the system. Boundary conditions are modelled using boundary use cases. After the hierarchy of subsystems has been developed, the objects in the system are identified and their details are designed. Here, the designer details out the strategy chosen during the system design. The emphasis shifts from application domain concepts toward computer concepts. The objects identified during analysis are etched out for implementation with an aim to minimize execution time, memory consumption, and overall cost. Object design includes the following phases βˆ’ Object identification Object representation, i.e., construction of design models Classification of operations Algorithm design Design of relationships Implementation of control for external interactions Package classes and associations into modules The first step of object design is object identification. The objects identified in the object–oriented analysis phases are grouped into classes and refined so that they are suitable for actual implementation. The functions of this stage are βˆ’ Identifying and refining the classes in each subsystem or package Identifying and refining the classes in each subsystem or package Defining the links and associations between the classes Defining the links and associations between the classes Designing the hierarchical associations among the classes, i.e., the generalization/specialization and inheritances Designing the hierarchical associations among the classes, i.e., the generalization/specialization and inheritances Designing aggregations Designing aggregations Once the classes are identified, they need to be represented using object modelling techniques. This stage essentially involves constructing UML diagrams. There are two types of design models that need to be produced βˆ’ Static Models βˆ’ To describe the static structure of a system using class diagrams and object diagrams. Static Models βˆ’ To describe the static structure of a system using class diagrams and object diagrams. Dynamic Models βˆ’ To describe the dynamic structure of a system and show the interaction between classes using interaction diagrams and state–chart diagrams. Dynamic Models βˆ’ To describe the dynamic structure of a system and show the interaction between classes using interaction diagrams and state–chart diagrams. In this step, the operation to be performed on objects are defined by combining the three models developed in the OOA phase, namely, object model, dynamic model, and functional model. An operation specifies what is to be done and not how it should be done. The following tasks are performed regarding operations βˆ’ The state transition diagram of each object in the system is developed. The state transition diagram of each object in the system is developed. Operations are defined for the events received by the objects. Operations are defined for the events received by the objects. Cases in which one event triggers other events in same or different objects are identified. Cases in which one event triggers other events in same or different objects are identified. The sub–operations within the actions are identified. The sub–operations within the actions are identified. The main actions are expanded to data flow diagrams. The main actions are expanded to data flow diagrams. The operations in the objects are defined using algorithms. An algorithm is a stepwise procedure that solves the problem laid down in an operation. Algorithms focus on how it is to be done. There may be more than one algorithm corresponding to a given operation. Once the alternative algorithms are identified, the optimal algorithm is selected for the given problem domain. The metrics for choosing the optimal algorithm are βˆ’ Computational Complexity βˆ’ Complexity determines the efficiency of an algorithm in terms of computation time and memory requirements. Computational Complexity βˆ’ Complexity determines the efficiency of an algorithm in terms of computation time and memory requirements. Flexibility βˆ’ Flexibility determines whether the chosen algorithm can be implemented suitably, without loss of appropriateness in various environments. Flexibility βˆ’ Flexibility determines whether the chosen algorithm can be implemented suitably, without loss of appropriateness in various environments. Understandability βˆ’ This determines whether the chosen algorithm is easy to understand and implement. Understandability βˆ’ This determines whether the chosen algorithm is easy to understand and implement. The strategy to implement the relationships needs to be chalked out during the object design phase. The main relationships that are addressed comprise of associations, aggregations, and inheritances. The designer should do the following regarding associations βˆ’ Identify whether an association is unidirectional or bidirectional. Identify whether an association is unidirectional or bidirectional. Analyze the path of associations and update them if necessary. Analyze the path of associations and update them if necessary. Implement the associations as a distinct object, in case of many–to-many relationships; or as a link to other object in case of one–to-one or one–to-many relationships. Implement the associations as a distinct object, in case of many–to-many relationships; or as a link to other object in case of one–to-one or one–to-many relationships. Regarding inheritances, the designer should do the following βˆ’ Adjust the classes and their associations. Adjust the classes and their associations. Identify abstract classes. Identify abstract classes. Make provisions so that behaviors are shared when needed. Make provisions so that behaviors are shared when needed. The object designer may incorporate refinements in the strategy of the state–chart model. In system design, a basic strategy for realizing the dynamic model is made. During object design, this strategy is aptly embellished for appropriate implementation. The approaches for implementation of the dynamic model are βˆ’ Represent State as a Location within a Program βˆ’ This is the traditional procedure-driven approach whereby the location of control defines the program state. A finite state machine can be implemented as a program. A transition forms an input statement, the main control path forms the sequence of instructions, the branches form the conditions, and the backward paths form the loops or iterations. Represent State as a Location within a Program βˆ’ This is the traditional procedure-driven approach whereby the location of control defines the program state. A finite state machine can be implemented as a program. A transition forms an input statement, the main control path forms the sequence of instructions, the branches form the conditions, and the backward paths form the loops or iterations. State Machine Engine βˆ’ This approach directly represents a state machine through a state machine engine class. This class executes the state machine through a set of transitions and actions provided by the application. State Machine Engine βˆ’ This approach directly represents a state machine through a state machine engine class. This class executes the state machine through a set of transitions and actions provided by the application. Control as Concurrent Tasks βˆ’ In this approach, an object is implemented as a task in the programming language or the operating system. Here, an event is implemented as an inter-task call. It preserves inherent concurrency of real objects. Control as Concurrent Tasks βˆ’ In this approach, an object is implemented as a task in the programming language or the operating system. Here, an event is implemented as an inter-task call. It preserves inherent concurrency of real objects. In any large project, meticulous partitioning of an implementation into modules or packages is important. During object design, classes and objects are grouped into packages to enable multiple groups to work cooperatively on a project. The different aspects of packaging are βˆ’ Hiding Internal Information from Outside View βˆ’ It allows a class to be viewed as a β€œblack box” and permits class implementation to be changed without requiring any clients of the class to modify code. Hiding Internal Information from Outside View βˆ’ It allows a class to be viewed as a β€œblack box” and permits class implementation to be changed without requiring any clients of the class to modify code. Coherence of Elements βˆ’ An element, such as a class, an operation, or a module, is coherent if it is organized on a consistent plan and all its parts are intrinsically related so that they serve a common goal. Coherence of Elements βˆ’ An element, such as a class, an operation, or a module, is coherent if it is organized on a consistent plan and all its parts are intrinsically related so that they serve a common goal. Construction of Physical Modules βˆ’ The following guidelines help while constructing physical modules βˆ’ Classes in a module should represent similar things or components in the same composite object. Closely connected classes should be in the same module. Unconnected or weakly connected classes should be placed in separate modules. Modules should have good cohesion, i.e., high cooperation among its components. A module should have low coupling with other modules, i.e., interaction or interdependence between modules should be minimum. Construction of Physical Modules βˆ’ The following guidelines help while constructing physical modules βˆ’ Classes in a module should represent similar things or components in the same composite object. Classes in a module should represent similar things or components in the same composite object. Closely connected classes should be in the same module. Closely connected classes should be in the same module. Unconnected or weakly connected classes should be placed in separate modules. Unconnected or weakly connected classes should be placed in separate modules. Modules should have good cohesion, i.e., high cooperation among its components. Modules should have good cohesion, i.e., high cooperation among its components. A module should have low coupling with other modules, i.e., interaction or interdependence between modules should be minimum. A module should have low coupling with other modules, i.e., interaction or interdependence between modules should be minimum. The analysis model captures the logical information about the system, while the design model adds details to support efficient information access. Before a design is implemented, it should be optimized so as to make the implementation more efficient. The aim of optimization is to minimize the cost in terms of time, space, and other metrics. However, design optimization should not be excess, as ease of implementation, maintainability, and extensibility are also important concerns. It is often seen that a perfectly optimized design is more efficient but less readable and reusable. So the designer must strike a balance between the two. The various things that may be done for design optimization are βˆ’ Add redundant associations Omit non-usable associations Optimization of algorithms Save derived attributes to avoid re-computation of complex expressions During design optimization, it is checked if deriving new associations can reduce access costs. Though these redundant associations may not add any information, they may increase the efficiency of the overall model. Presence of too many associations may render a system indecipherable and hence reduce the overall efficiency of the system. So, during optimization, all non-usable associations are removed. In object-oriented systems, optimization of data structure and algorithms are done in a collaborative manner. Once the class design is in place, the operations and the algorithms need to be optimized. Optimization of algorithms is obtained by βˆ’ Rearrangement of the order of computational tasks Reversal of execution order of loops from that laid down in the functional model Removal of dead paths within the algorithm Derived attributes are those attributes whose values are computed as a function of other attributes (base attributes). Re-computation of the values of derived attributes every time they are needed is a time–consuming procedure. To avoid this, the values can be computed and stored in their computed forms. However, this may pose update anomalies, i.e., a change in the values of base attributes with no corresponding change in the values of the derived attributes. To avoid this, the following steps are taken βˆ’ With each update of the base attribute value, the derived attribute is also re-computed. With each update of the base attribute value, the derived attribute is also re-computed. All the derived attributes are re-computed and updated periodically in a group rather than after each update. All the derived attributes are re-computed and updated periodically in a group rather than after each update. Documentation is an essential part of any software development process that records the procedure of making the software. The design decisions need to be documented for any non–trivial software system for transmitting the design to others. Though a secondary product, a good documentation is indispensable, particularly in the following areas βˆ’ In designing software that is being developed by a number of developers In iterative software development strategies In developing subsequent versions of a software project For evaluating a software For finding conditions and areas of testing For maintenance of the software. A beneficial documentation should essentially include the following contents βˆ’ High–level system architecture βˆ’ Process diagrams and module diagrams High–level system architecture βˆ’ Process diagrams and module diagrams Key abstractions and mechanisms βˆ’ Class diagrams and object diagrams. Key abstractions and mechanisms βˆ’ Class diagrams and object diagrams. Scenarios that illustrate the behavior of the main aspects βˆ’ Behavioural diagrams Scenarios that illustrate the behavior of the main aspects βˆ’ Behavioural diagrams The features of a good documentation are βˆ’ Concise and at the same time, unambiguous, consistent, and complete Concise and at the same time, unambiguous, consistent, and complete Traceable to the system’s requirement specifications Traceable to the system’s requirement specifications Well-structured Well-structured Diagrammatic instead of descriptive Diagrammatic instead of descriptive Implementing an object-oriented design generally involves using a standard object oriented programming language (OOPL) or mapping object designs to databases. In most cases, it involves both. Usually, the task of transforming an object design into code is a straightforward process. Any object-oriented programming language like C++, Java, Smalltalk, C# and Python, includes provision for representing classes. In this chapter, we exemplify the concept using C++. The following figure shows the representation of the class Circle using C++. Most programming languages do not provide constructs to implement associations directly. So the task of implementing associations needs considerable thought. Associations may be either unidirectional or bidirectional. Besides, each association may be either one–to–one, one–to–many, or many–to–many. For implementing unidirectional associations, care should be taken so that unidirectionality is maintained. The implementations for different multiplicity are as follows βˆ’ Optional Associations βˆ’ Here, a link may or may not exist between the participating objects. For example, in the association between Customer and Current Account in the figure below, a customer may or may not have a current account. Optional Associations βˆ’ Here, a link may or may not exist between the participating objects. For example, in the association between Customer and Current Account in the figure below, a customer may or may not have a current account. For implementation, an object of Current Account is included as an attribute in Customer that may be NULL. Implementation using C++ βˆ’ class Customer { private: // attributes Current_Account c; //an object of Current_Account as attribute public: Customer() { c = NULL; } // assign c as NULL Current_Account getCurrAc() { return c; } void setCurrAc( Current_Account myacc) { c = myacc; } void removeAcc() { c = NULL; } }; One–to–one Associations βˆ’ Here, one instance of a class is related to exactly one instance of the associated class. For example, Department and Manager have one–to–one association as shown in the figure below. One–to–one Associations βˆ’ Here, one instance of a class is related to exactly one instance of the associated class. For example, Department and Manager have one–to–one association as shown in the figure below. This is implemented by including in Department, an object of Manager that should not be NULL. Implementation using C++ βˆ’ class Department { private: // attributes Manager mgr; //an object of Manager as attribute public: Department (/*parameters*/, Manager m) { //m is not NULL // assign parameters to variables mgr = m; } Manager getMgr() { return mgr; } }; One–to–many Associations βˆ’ Here, one instance of a class is related to more than one instances of the associated class. For example, consider the association between Employee and Dependent in the following figure. One–to–many Associations βˆ’ Here, one instance of a class is related to more than one instances of the associated class. For example, consider the association between Employee and Dependent in the following figure. This is implemented by including a list of Dependents in class Employee. Implementation using C++ STL list container βˆ’ class Employee { private: char * deptName; list <Dependent> dep; //a list of Dependents as attribute public: void addDependent ( Dependent d) { dep.push_back(d); } // adds an employee to the department void removeDeoendent( Dependent d) { int index = find ( d, dep ); // find() function returns the index of d in list dep dep.erase(index); } }; To implement bi-directional association, links in both directions require to be maintained. Optional or one–to–one Associations βˆ’ Consider the relationship between Project and Project Manager having one–to–one bidirectional association as shown in the figure below. Optional or one–to–one Associations βˆ’ Consider the relationship between Project and Project Manager having one–to–one bidirectional association as shown in the figure below. Implementation using C++ βˆ’ Class Project { private: // attributes Project_Manager pmgr; public: void setManager ( Project_Manager pm); Project_Manager changeManager(); }; class Project_Manager { private: // attributes Project pj; public: void setProject(Project p); Project removeProject(); }; One–to–many Associations βˆ’ Consider the relationship between Department and Employee having one–to–many association as shown in the figure below. One–to–many Associations βˆ’ Consider the relationship between Department and Employee having one–to–many association as shown in the figure below. class Department { private: char * deptName; list <Employee> emp; //a list of Employees as attribute public: void addEmployee ( Employee e) { emp.push_back(e); } // adds an employee to the department void removeEmployee( Employee e) { int index = find ( e, emp ); // find function returns the index of e in list emp emp.erase(index); } }; class Employee { private: //attributes Department d; public: void addDept(); void removeDept(); }; If an association has some attributes associated, it should be implemented using a separate class. For example, consider the one–to–one association between Employee and Project as shown in the figure below. class WorksOn { private: Employee e; Project p; Hours h; char * date; public: // class methods }; Constraints in classes restrict the range and type of values that the attributes may take. In order to implement constraints, a valid default value is assigned to the attribute when an object is instantiated from the class. Whenever the value is changed at runtime, it is checked whether the value is valid or not. An invalid value may be handled by an exception handling routine or other methods. Example Consider an Employee class where age is an attribute that may have values in the range of 18 to 60. The following C++ code incorporates it βˆ’ class Employee { private: char * name; int age; // other attributes public: Employee() { // default constructor strcpy(name, ""); age = 18; // default value } class AgeError {}; // Exception class void changeAge( int a) { // method that changes age if ( a < 18 || a > 60 ) // check for invalid condition throw AgeError(); // throw exception age = a; } }; There are two alternative implementation strategies to implement states in state chart diagrams. In this approach, the states are represented by different values of a data member (or set of data members). The values are explicitly defined by an enumeration within the class. The transitions are represented by member functions that change the value of the concerned data member. In this approach, the states are arranged in a generalization hierarchy in a manner that they can be referred by a common pointer variable. The following figure shows a transformation from state chart diagram to a generalization hierarchy. An important aspect of developing object-oriented systems is persistency of data. Through persistency, objects have longer lifespan than the program that created it. Persistent data is saved on secondary storage medium from where it can be reloaded when required. A database is an ordered collection of related data. A database management system (DBMS) is a collection of software that facilitates the processes of defining, creating, storing, manipulating, retrieving, sharing, and removing data in databases. In relational database management systems (RDBMS), data is stored as relations or tables, where each column or field represents an attribute and each row or tuple represents a record of an instance. Each row is uniquely identified by a chosen set of minimal attributes called primary key. A foreign key is an attribute that is the primary key of a related table. To map a class to a database table, each attribute is represented as a field in the table. Either an existing attribute(s) is assigned as a primary key or a separate ID field is added as a primary key. The class may be partitioned horizontally or vertically as per requirement. For example, the Circle class can be converted to table as shown in the figure below. Schema for Circle Table: CIRCLE(CID, X_COORD, Y_COORD, RADIUS, COLOR) Creating a Table Circle using SQL command: CREATE TABLE CIRCLE ( CID VARCHAR2(4) PRIMARY KEY, X_COORD INTEGER NOT NULL, Y_COORD INTEGER NOT NULL, Z_COORD INTEGER NOT NULL, COLOR ); To implement 1:1 associations, the primary key of any one table is assigned as the foreign key of the other table. For example, consider the association between Department and Manager βˆ’ CREATE TABLE DEPARTMENT ( DEPT_ID INTEGER PRIMARY KEY, DNAME VARCHAR2(30) NOT NULL, LOCATION VARCHAR2(20), EMPID INTEGER REFERENCES MANAGER ); CREATE TABLE MANAGER ( EMPID INTEGER PRIMARY KEY, ENAME VARCHAR2(50) NOT NULL, ADDRESS VARCHAR2(70), ); To implement 1:N associations, the primary key of the table in the 1-side of the association is assigned as the foreign key of the table at the N-side of the association. For example, consider the association between Department and Employee βˆ’ CREATE TABLE DEPARTMENT ( DEPT_ID INTEGER PRIMARY KEY, DNAME VARCHAR2(30) NOT NULL, LOCATION VARCHAR2(20), ); CREATE TABLE EMPLOYEE ( EMPID INTEGER PRIMARY KEY, ENAME VARCHAR2(50) NOT NULL, ADDRESS VARCHAR2(70), D_ID INTEGER REFERENCES DEPARTMENT ); To implement M:N associations, a new relation is created that represents the association. For example, consider the following association between Employee and Project βˆ’ Schema for Works_On Table βˆ’ WORKS_ON (EMPID, PID, HOURS, START_DATE) SQL command to create Works_On association βˆ’ CREATE TABLE WORKS_ON ( EMPID INTEGER, PID INTEGER, HOURS INTEGER, START_DATE DATE, PRIMARY KEY (EMPID, PID), FOREIGN KEY (EMPID) REFERENCES EMPLOYEE, FOREIGN KEY (PID) REFERENCES PROJECT ); To map inheritance, the primary key of the base table(s) is assigned as the primary key as well as the foreign key in the derived table(s). Example Once a program code is written, it must be tested to detect and subsequently handle all errors in it. A number of schemes are used for testing purposes. Another important aspect is the fitness of purpose of a program that ascertains whether the program serves the purpose which it aims for. The fitness defines the software quality. Testing is a continuous activity during software development. In object-oriented systems, testing encompasses three levels, namely, unit testing, subsystem testing, and system testing. In unit testing, the individual classes are tested. It is seen whether the class attributes are implemented as per design and whether the methods and the interfaces are error-free. Unit testing is the responsibility of the application engineer who implements the structure. This involves testing a particular module or a subsystem and is the responsibility of the subsystem lead. It involves testing the associations within the subsystem as well as the interaction of the subsystem with the outside. Subsystem tests can be used as regression tests for each newly released version of the subsystem. System testing involves testing the system as a whole and is the responsibility of the quality-assurance team. The team often uses system tests as regression tests when assembling new releases. The different types of test cases that can be designed for testing object-oriented programs are called grey box test cases. Some of the important types of grey box testing are βˆ’ State model based testing βˆ’ This encompasses state coverage, state transition coverage, and state transition path coverage. State model based testing βˆ’ This encompasses state coverage, state transition coverage, and state transition path coverage. Use case based testing βˆ’ Each scenario in each use case is tested. Use case based testing βˆ’ Each scenario in each use case is tested. Class diagram based testing βˆ’ Each class, derived class, associations, and aggregations are tested. Class diagram based testing βˆ’ Each class, derived class, associations, and aggregations are tested. Sequence diagram based testing βˆ’ The methods in the messages in the sequence diagrams are tested. Sequence diagram based testing βˆ’ The methods in the messages in the sequence diagrams are tested. The two main approaches of subsystem testing are βˆ’ Thread based testing βˆ’ All classes that are needed to realize a single use case in a subsystem are integrated and tested. Thread based testing βˆ’ All classes that are needed to realize a single use case in a subsystem are integrated and tested. Use based testing βˆ’ The interfaces and services of the modules at each level of hierarchy are tested. Testing starts from the individual classes to the small modules comprising of classes, gradually to larger modules, and finally all the major subsystems. Use based testing βˆ’ The interfaces and services of the modules at each level of hierarchy are tested. Testing starts from the individual classes to the small modules comprising of classes, gradually to larger modules, and finally all the major subsystems. Alpha testing βˆ’ This is carried out by the testing team within the organization that develops software. Alpha testing βˆ’ This is carried out by the testing team within the organization that develops software. Beta testing βˆ’ This is carried out by select group of co-operating customers. Beta testing βˆ’ This is carried out by select group of co-operating customers. Acceptance testing βˆ’ This is carried out by the customer before accepting the deliverables. Acceptance testing βˆ’ This is carried out by the customer before accepting the deliverables. Schulmeyer and McManus have defined software quality as β€œthe fitness for use of the total software product”. A good quality software does exactly what it is supposed to do and is interpreted in terms of satisfaction of the requirement specification laid down by the user. Software quality assurance is a methodology that determines the extent to which a software product is fit for use. The activities that are included for determining software quality are βˆ’ Auditing Development of standards and guidelines Production of reports Review of quality system Correctness βˆ’ Correctness determines whether the software requirements are appropriately met. Correctness βˆ’ Correctness determines whether the software requirements are appropriately met. Usability βˆ’ Usability determines whether the software can be used by different categories of users (beginners, non-technical, and experts). Usability βˆ’ Usability determines whether the software can be used by different categories of users (beginners, non-technical, and experts). Portability βˆ’ Portability determines whether the software can operate in different platforms with different hardware devices. Portability βˆ’ Portability determines whether the software can operate in different platforms with different hardware devices. Maintainability βˆ’ Maintainability determines the ease at which errors can be corrected and modules can be updated. Maintainability βˆ’ Maintainability determines the ease at which errors can be corrected and modules can be updated. Reusability βˆ’ Reusability determines whether the modules and classes can be reused for developing other software products. Reusability βˆ’ Reusability determines whether the modules and classes can be reused for developing other software products. Metrics can be broadly classified into three categories: project metrics, product metrics, and process metrics. Project Metrics enable a software project manager to assess the status and performance of an ongoing project. The following metrics are appropriate for object-oriented software projects βˆ’ Number of scenario scripts Number of key classes Number of support classes Number of subsystems Product metrics measure the characteristics of the software product that has been developed. The product metrics suitable for object-oriented systems are βˆ’ Methods per Class βˆ’ It determines the complexity of a class. If all the methods of a class are assumed to be equally complex, then a class with more methods is more complex and thus more susceptible to errors. Methods per Class βˆ’ It determines the complexity of a class. If all the methods of a class are assumed to be equally complex, then a class with more methods is more complex and thus more susceptible to errors. Inheritance Structure βˆ’ Systems with several small inheritance lattices are more well–structured than systems with a single large inheritance lattice. As a thumb rule, an inheritance tree should not have more than 7 (Β± 2) number of levels and the tree should be balanced. Inheritance Structure βˆ’ Systems with several small inheritance lattices are more well–structured than systems with a single large inheritance lattice. As a thumb rule, an inheritance tree should not have more than 7 (Β± 2) number of levels and the tree should be balanced. Coupling and Cohesion βˆ’ Modules having low coupling and high cohesion are considered to be better designed, as they permit greater reusability and maintainability. Coupling and Cohesion βˆ’ Modules having low coupling and high cohesion are considered to be better designed, as they permit greater reusability and maintainability. Response for a Class βˆ’ It measures the efficiency of the methods that are called by the instances of the class. Response for a Class βˆ’ It measures the efficiency of the methods that are called by the instances of the class. Process metrics help in measuring how a process is performing. They are collected over all projects over long periods of time. They are used as indicators for long-term software process improvements. Some process metrics are βˆ’ Number of KLOC (Kilo Lines of Code) Defect removal efficiency Average number of failures detected during testing Number of latent defects per KLOC 14 Lectures 1.5 hours Harshit Srivastava 60 Lectures 8 hours DigiFisk (Programming Is Fun) 11 Lectures 35 mins Sandip Bhattacharya 21 Lectures 2 hours Pranjal Srivastava 6 Lectures 43 mins Frahaan Hussain 49 Lectures 4.5 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2154, "s": 1987, "text": "The object-oriented paradigm took its shape from the initial concept of a new programming approach, while the interest in design and analysis methods came much later." }, { "code": null, "e": 2306, "s": 2154, "text": "The first object–oriented language was Simula (Simulation of real systems) that was developed in 1960 by researchers at the Norwegian Computing Center." }, { "code": null, "e": 2458, "s": 2306, "text": "The first object–oriented language was Simula (Simulation of real systems) that was developed in 1960 by researchers at the Norwegian Computing Center." }, { "code": null, "e": 2662, "s": 2458, "text": "In 1970, Alan Kay and his research group at Xerox PARK created a personal computer named Dynabook and the first pure object-oriented programming language (OOPL) - Smalltalk, for programming the Dynabook." }, { "code": null, "e": 2866, "s": 2662, "text": "In 1970, Alan Kay and his research group at Xerox PARK created a personal computer named Dynabook and the first pure object-oriented programming language (OOPL) - Smalltalk, for programming the Dynabook." }, { "code": null, "e": 3098, "s": 2866, "text": "In the 1980s, Grady Booch published a paper titled Object Oriented Design that mainly presented a design for the programming language, Ada. In the ensuing editions, he extended his ideas to a complete object–oriented design method." }, { "code": null, "e": 3330, "s": 3098, "text": "In the 1980s, Grady Booch published a paper titled Object Oriented Design that mainly presented a design for the programming language, Ada. In the ensuing editions, he extended his ideas to a complete object–oriented design method." }, { "code": null, "e": 3407, "s": 3330, "text": "In the 1990s, Coad incorporated behavioral ideas to object-oriented methods." }, { "code": null, "e": 3484, "s": 3407, "text": "In the 1990s, Coad incorporated behavioral ideas to object-oriented methods." }, { "code": null, "e": 3641, "s": 3484, "text": "The other significant innovations were Object Modelling Techniques (OMT) by James Rumbaugh and Object-Oriented Software Engineering (OOSE) by Ivar Jacobson." }, { "code": null, "e": 3863, "s": 3641, "text": "Object–Oriented Analysis (OOA) is the procedure of identifying software engineering requirements and developing software specifications in terms of a software system’s object model, which comprises of interacting objects." }, { "code": null, "e": 4245, "s": 3863, "text": "The main difference between object-oriented analysis and other forms of analysis is that in object-oriented approach, requirements are organized around objects, which integrate both data and functions. They are modelled after real-world objects that the system interacts with. In traditional analysis methodologies, the two aspects - functions and data - are considered separately." }, { "code": null, "e": 4450, "s": 4245, "text": "Grady Booch has defined OOA as, β€œObject-oriented analysis is a method of analysis that examines requirements from the perspective of the classes and objects found in the vocabulary of the problem domain”." }, { "code": null, "e": 4508, "s": 4450, "text": "The primary tasks in object-oriented analysis (OOA) are βˆ’" }, { "code": null, "e": 4528, "s": 4508, "text": "Identifying objects" }, { "code": null, "e": 4584, "s": 4528, "text": "Organizing the objects by creating object model diagram" }, { "code": null, "e": 4644, "s": 4584, "text": "Defining the internals of the objects, or object attributes" }, { "code": null, "e": 4703, "s": 4644, "text": "Defining the behavior of the objects, i.e., object actions" }, { "code": null, "e": 4739, "s": 4703, "text": "Describing how the objects interact" }, { "code": null, "e": 4802, "s": 4739, "text": "The common models used in OOA are use cases and object models." }, { "code": null, "e": 5223, "s": 4802, "text": "Object–Oriented Design (OOD) involves implementation of the conceptual model produced during object-oriented analysis. In OOD, concepts in the analysis model, which are technologyβˆ’independent, are mapped onto implementing classes, constraints are identified and interfaces are designed, resulting in a model for the solution domain, i.e., a detailed description of how the system is to be built on concrete technologies." }, { "code": null, "e": 5270, "s": 5223, "text": "The implementation details generally include βˆ’" }, { "code": null, "e": 5315, "s": 5270, "text": "Restructuring the class data (if necessary)," }, { "code": null, "e": 5389, "s": 5315, "text": "Implementation of methods, i.e., internal data structures and algorithms," }, { "code": null, "e": 5420, "s": 5389, "text": "Implementation of control, and" }, { "code": null, "e": 5452, "s": 5420, "text": "Implementation of associations." }, { "code": null, "e": 5701, "s": 5452, "text": "Grady Booch has defined object-oriented design as β€œa method of design encompassing the process of object-oriented decomposition and a notation for depicting both logical and physical as well as static and dynamic models of the system under design”." }, { "code": null, "e": 6015, "s": 5701, "text": "Object-oriented programming (OOP) is a programming paradigm based upon objects (having both data and methods) that aims to incorporate the advantages of modularity and reusability. Objects, which are usually instances of classes, are used to interact with one another to design applications and computer programs." }, { "code": null, "e": 6075, "s": 6015, "text": "The important features of object–oriented programming are βˆ’" }, { "code": null, "e": 6112, "s": 6075, "text": "Bottom–up approach in program design" }, { "code": null, "e": 6166, "s": 6112, "text": "Programs organized around objects, grouped in classes" }, { "code": null, "e": 6223, "s": 6166, "text": "Focus on data with methods to operate upon object’s data" }, { "code": null, "e": 6269, "s": 6223, "text": "Interaction between objects through functions" }, { "code": null, "e": 6362, "s": 6269, "text": "Reusability of design through creation of new classes by adding features to existing classes" }, { "code": null, "e": 6484, "s": 6362, "text": "Some examples of object-oriented programming languages are C++, Java, Smalltalk, Delphi, C#, Perl, Python, Ruby, and PHP." }, { "code": null, "e": 6789, "s": 6484, "text": "Grady Booch has defined object–oriented programming as β€œa method of implementation in which programs are organized as cooperative collections of objects, each of which represents an instance of some class, and whose classes are all members of a hierarchy of classes united via inheritance relationships”." }, { "code": null, "e": 6977, "s": 6789, "text": "The object model visualizes the elements in a software application in terms of objects. In this chapter, we will look into the basic concepts and terminologies of object–oriented systems." }, { "code": null, "e": 7107, "s": 6977, "text": "The concepts of objects and classes are intrinsically linked with each other and form the foundation of object–oriented paradigm." }, { "code": null, "e": 7245, "s": 7107, "text": "An object is a real-world element in an object–oriented environment that may have a physical or a conceptual existence. Each object has βˆ’" }, { "code": null, "e": 7310, "s": 7245, "text": "Identity that distinguishes it from other objects in the system." }, { "code": null, "e": 7375, "s": 7310, "text": "Identity that distinguishes it from other objects in the system." }, { "code": null, "e": 7503, "s": 7375, "text": "State that determines the characteristic properties of an object as well as the values of the properties that the object holds." }, { "code": null, "e": 7631, "s": 7503, "text": "State that determines the characteristic properties of an object as well as the values of the properties that the object holds." }, { "code": null, "e": 7743, "s": 7631, "text": "Behavior that represents externally visible activities performed by an object in terms of changes in its state." }, { "code": null, "e": 7855, "s": 7743, "text": "Behavior that represents externally visible activities performed by an object in terms of changes in its state." }, { "code": null, "e": 8064, "s": 7855, "text": "Objects can be modelled according to the needs of the application. An object may have a physical existence, like a customer, a car, etc.; or an intangible conceptual existence, like a project, a process, etc." }, { "code": null, "e": 8367, "s": 8064, "text": "A class represents a collection of objects having same characteristic properties that exhibit common behavior. It gives the blueprint or description of the objects that can be created from it. Creation of an object as a member of a class is called instantiation. Thus, object is an instance of a class." }, { "code": null, "e": 8401, "s": 8367, "text": "The constituents of a class are βˆ’" }, { "code": null, "e": 8620, "s": 8401, "text": "A set of attributes for the objects that are to be instantiated from the class. Generally, different objects of a class have some difference in the values of the attributes. Attributes are often referred as class data." }, { "code": null, "e": 8839, "s": 8620, "text": "A set of attributes for the objects that are to be instantiated from the class. Generally, different objects of a class have some difference in the values of the attributes. Attributes are often referred as class data." }, { "code": null, "e": 8968, "s": 8839, "text": "A set of operations that portray the behavior of the objects of the class. Operations are also referred as functions or methods." }, { "code": null, "e": 9097, "s": 8968, "text": "A set of operations that portray the behavior of the objects of the class. Operations are also referred as functions or methods." }, { "code": null, "e": 9105, "s": 9097, "text": "Example" }, { "code": null, "e": 9279, "s": 9105, "text": "Let us consider a simple class, Circle, that represents the geometrical figure circle in a two–dimensional space. The attributes of this class can be identified as follows βˆ’" }, { "code": null, "e": 9325, "s": 9279, "text": "x–coord, to denote x–coordinate of the center" }, { "code": null, "e": 9371, "s": 9325, "text": "y–coord, to denote y–coordinate of the center" }, { "code": null, "e": 9409, "s": 9371, "text": "a, to denote the radius of the circle" }, { "code": null, "e": 9460, "s": 9409, "text": "Some of its operations can be defined as follows βˆ’" }, { "code": null, "e": 9497, "s": 9460, "text": "findArea(), method to calculate area" }, { "code": null, "e": 9552, "s": 9497, "text": "findCircumference(), method to calculate circumference" }, { "code": null, "e": 9603, "s": 9552, "text": "scale(), method to increase or decrease the radius" }, { "code": null, "e": 10033, "s": 9603, "text": "During instantiation, values are assigned for at least some of the attributes. If we create an object my_circle, we can assign values like x-coord : 2, y-coord : 3, and a : 4 to depict its state. Now, if the operation scale() is performed on my_circle with a scaling factor of 2, the value of the variable a will become 8. This operation brings a change in the state of my_circle, i.e., the object has exhibited certain behavior." }, { "code": null, "e": 10324, "s": 10033, "text": "Encapsulation is the process of binding both attributes and methods together within a class. Through encapsulation, the internal details of a class can be hidden from outside. It permits the elements of the class to be accessed from outside only through the interface provided by the class." }, { "code": null, "e": 10560, "s": 10324, "text": "Typically, a class is designed such that its data (attributes) can be accessed only by its class methods and insulated from direct outside access. This process of insulating an object’s data is called data hiding or information hiding." }, { "code": null, "e": 10568, "s": 10560, "text": "Example" }, { "code": null, "e": 10751, "s": 10568, "text": "In the class Circle, data hiding can be incorporated by making attributes invisible from outside the class and adding two more methods to the class for accessing class data, namely βˆ’" }, { "code": null, "e": 10815, "s": 10751, "text": "setValues(), method to assign values to x-coord, y-coord, and a" }, { "code": null, "e": 10881, "s": 10815, "text": "getValues(), method to retrieve values of x-coord, y-coord, and a" }, { "code": null, "e": 11098, "s": 10881, "text": "Here the private data of the object my_circle cannot be accessed directly by any method that is not encapsulated within the class Circle. It should instead be accessed through the methods setValues() and getValues()." }, { "code": null, "e": 11401, "s": 11098, "text": "Any application requires a number of objects interacting in a harmonious manner. Objects in a system may communicate with each other using message passing. Suppose a system has two objects: obj1 and obj2. The object obj1 sends a message to object obj2, if obj1 wants obj2 to execute one of its methods." }, { "code": null, "e": 11439, "s": 11401, "text": "The features of message passing are βˆ’" }, { "code": null, "e": 11504, "s": 11439, "text": "Message passing between two objects is generally unidirectional." }, { "code": null, "e": 11562, "s": 11504, "text": "Message passing enables all interactions between objects." }, { "code": null, "e": 11623, "s": 11562, "text": "Message passing essentially involves invoking class methods." }, { "code": null, "e": 11690, "s": 11623, "text": "Objects in different processes can be involved in message passing." }, { "code": null, "e": 12262, "s": 11690, "text": "Inheritance is the mechanism that permits new classes to be created out of existing classes by extending and refining its capabilities. The existing classes are called the base classes/parent classes/super-classes, and the new classes are called the derived classes/child classes/subclasses. The subclass can inherit or derive the attributes and methods of the super-class(es) provided that the super-class allows so. Besides, the subclass may add its own attributes and methods and may modify any of the super-class methods. Inheritance defines an β€œis – a” relationship." }, { "code": null, "e": 12270, "s": 12262, "text": "Example" }, { "code": null, "e": 12541, "s": 12270, "text": "From a class Mammal, a number of classes can be derived such as Human, Cat, Dog, Cow, etc. Humans, cats, dogs, and cows all have the distinct characteristics of mammals. In addition, each has its own particular characteristics. It can be said that a cow β€œis – a” mammal." }, { "code": null, "e": 12608, "s": 12541, "text": "Single Inheritance βˆ’ A subclass derives from a single super-class." }, { "code": null, "e": 12675, "s": 12608, "text": "Single Inheritance βˆ’ A subclass derives from a single super-class." }, { "code": null, "e": 12751, "s": 12675, "text": "Multiple Inheritance βˆ’ A subclass derives from more than one super-classes." }, { "code": null, "e": 12827, "s": 12751, "text": "Multiple Inheritance βˆ’ A subclass derives from more than one super-classes." }, { "code": null, "e": 12945, "s": 12827, "text": "Multilevel Inheritance βˆ’ A subclass derives from a super-class which in turn is derived from another class and so on." }, { "code": null, "e": 13063, "s": 12945, "text": "Multilevel Inheritance βˆ’ A subclass derives from a super-class which in turn is derived from another class and so on." }, { "code": null, "e": 13238, "s": 13063, "text": "Hierarchical Inheritance βˆ’ A class has a number of subclasses each of which may have subsequent subclasses, continuing for a number of levels, so as to form a tree structure." }, { "code": null, "e": 13413, "s": 13238, "text": "Hierarchical Inheritance βˆ’ A class has a number of subclasses each of which may have subsequent subclasses, continuing for a number of levels, so as to form a tree structure." }, { "code": null, "e": 13522, "s": 13413, "text": "Hybrid Inheritance βˆ’ A combination of multiple and multilevel inheritance so as to form a lattice structure." }, { "code": null, "e": 13631, "s": 13522, "text": "Hybrid Inheritance βˆ’ A combination of multiple and multilevel inheritance so as to form a lattice structure." }, { "code": null, "e": 13708, "s": 13631, "text": "The following figure depicts the examples of different types of inheritance." }, { "code": null, "e": 14105, "s": 13708, "text": "Polymorphism is originally a Greek word that means the ability to take multiple forms. In object-oriented paradigm, polymorphism implies using operations in different ways, depending upon the instance they are operating upon. Polymorphism allows objects with different internal structures to have a common external interface. Polymorphism is particularly effective while implementing inheritance." }, { "code": null, "e": 14113, "s": 14105, "text": "Example" }, { "code": null, "e": 14532, "s": 14113, "text": "Let us consider two classes, Circle and Square, each with a method findArea(). Though the name and purpose of the methods in the classes are same, the internal implementation, i.e., the procedure of calculating area is different for each class. When an object of class Circle invokes its findArea() method, the operation finds the area of the circle without any conflict with the findArea() method of the Square class." }, { "code": null, "e": 14667, "s": 14532, "text": "Generalization and specialization represent a hierarchy of relationships between classes, where subclasses inherit from super-classes." }, { "code": null, "e": 14998, "s": 14667, "text": "In the generalization process, the common characteristics of classes are combined to form a class in a higher level of hierarchy, i.e., subclasses are combined to form a generalized super-class. It represents an β€œis – a – kind – of” relationship. For example, β€œcar is a kind of land vehicle”, or β€œship is a kind of water vehicle”." }, { "code": null, "e": 15254, "s": 14998, "text": "Specialization is the reverse process of generalization. Here, the distinguishing features of groups of objects are used to form specialized classes from existing classes. It can be said that the subclasses are the specialized versions of the super-class." }, { "code": null, "e": 15330, "s": 15254, "text": "The following figure shows an example of generalization and specialization." }, { "code": null, "e": 15647, "s": 15330, "text": "A link represents a connection through which an object collaborates with other objects. Rumbaugh has defined it as β€œa physical or conceptual connection between objects”. Through a link, one object may invoke the methods or navigate through another object. A link depicts the relationship between two or more objects." }, { "code": null, "e": 15857, "s": 15647, "text": "Association is a group of links having common structure and common behavior. Association depicts the relationship between objects of one or more classes. A link can be defined as an instance of an association." }, { "code": null, "e": 15979, "s": 15857, "text": "Degree of an association denotes the number of classes involved in a connection. Degree may be unary, binary, or ternary." }, { "code": null, "e": 16037, "s": 15979, "text": " A unary relationship connects objects of the same class." }, { "code": null, "e": 16095, "s": 16037, "text": " A unary relationship connects objects of the same class." }, { "code": null, "e": 16151, "s": 16095, "text": " A binary relationship connects objects of two classes." }, { "code": null, "e": 16207, "s": 16151, "text": " A binary relationship connects objects of two classes." }, { "code": null, "e": 16274, "s": 16207, "text": " A ternary relationship connects objects of three or more classes." }, { "code": null, "e": 16341, "s": 16274, "text": " A ternary relationship connects objects of three or more classes." }, { "code": null, "e": 16496, "s": 16341, "text": "Cardinality of a binary association denotes the number of instances participating in an association. There are three types of cardinality ratios, namely βˆ’" }, { "code": null, "e": 16583, "s": 16496, "text": "One–to–One βˆ’ A single object of class A is associated with a single object of class B." }, { "code": null, "e": 16670, "s": 16583, "text": "One–to–One βˆ’ A single object of class A is associated with a single object of class B." }, { "code": null, "e": 16755, "s": 16670, "text": "One–to–Many βˆ’ A single object of class A is associated with many objects of class B." }, { "code": null, "e": 16840, "s": 16755, "text": "One–to–Many βˆ’ A single object of class A is associated with many objects of class B." }, { "code": null, "e": 17007, "s": 16840, "text": "Many–to–Many βˆ’ An object of class A may be associated with many objects of class B and conversely an object of class B may be associated with many objects of class A." }, { "code": null, "e": 17174, "s": 17007, "text": "Many–to–Many βˆ’ An object of class A may be associated with many objects of class B and conversely an object of class B may be associated with many objects of class A." }, { "code": null, "e": 17589, "s": 17174, "text": "Aggregation or composition is a relationship among classes by which a class can be made up of any combination of objects of other classes. It allows objects to be placed directly within the body of other classes. Aggregation is referred as a β€œpart–of” or β€œhas–a” relationship, with the ability to navigate from the whole to its parts. An aggregate object is an object that is composed of one or more other objects." }, { "code": null, "e": 17597, "s": 17589, "text": "Example" }, { "code": null, "e": 17744, "s": 17597, "text": "In the relationship, β€œa car has–a motor”, car is the whole object or the aggregate, and the motor is a β€œpart–of” the car. Aggregation may denote βˆ’" }, { "code": null, "e": 17844, "s": 17744, "text": "Physical containment βˆ’ Example, a computer is composed of monitor, CPU, mouse, keyboard, and so on." }, { "code": null, "e": 17944, "s": 17844, "text": "Physical containment βˆ’ Example, a computer is composed of monitor, CPU, mouse, keyboard, and so on." }, { "code": null, "e": 18003, "s": 17944, "text": "Conceptual containment βˆ’ Example, shareholder has–a share." }, { "code": null, "e": 18062, "s": 18003, "text": "Conceptual containment βˆ’ Example, shareholder has–a share." }, { "code": null, "e": 18220, "s": 18062, "text": "Now that we have gone through the core concepts pertaining to object orientation, it would be worthwhile to note the advantages that this model has to offer." }, { "code": null, "e": 18265, "s": 18220, "text": "The benefits of using the object model are βˆ’" }, { "code": null, "e": 18309, "s": 18265, "text": "It helps in faster development of software." }, { "code": null, "e": 18353, "s": 18309, "text": "It helps in faster development of software." }, { "code": null, "e": 18527, "s": 18353, "text": "It is easy to maintain. Suppose a module develops an error, then a programmer can fix that particular module, while the other parts of the software are still up and running." }, { "code": null, "e": 18701, "s": 18527, "text": "It is easy to maintain. Suppose a module develops an error, then a programmer can fix that particular module, while the other parts of the software are still up and running." }, { "code": null, "e": 18746, "s": 18701, "text": "It supports relatively hassle-free upgrades." }, { "code": null, "e": 18791, "s": 18746, "text": "It supports relatively hassle-free upgrades." }, { "code": null, "e": 18844, "s": 18791, "text": "It enables reuse of objects, designs, and functions." }, { "code": null, "e": 18897, "s": 18844, "text": "It enables reuse of objects, designs, and functions." }, { "code": null, "e": 18975, "s": 18897, "text": "It reduces development risks, particularly in integration of complex systems." }, { "code": null, "e": 19053, "s": 18975, "text": "It reduces development risks, particularly in integration of complex systems." }, { "code": null, "e": 19260, "s": 19053, "text": "We know that the Object-Oriented Modelling (OOM) technique visualizes things in an application by using models organized around objects. Any software development approach goes through the following stages βˆ’" }, { "code": null, "e": 19270, "s": 19260, "text": "Analysis," }, { "code": null, "e": 19282, "s": 19270, "text": "Design, and" }, { "code": null, "e": 19298, "s": 19282, "text": "Implementation." }, { "code": null, "e": 19533, "s": 19298, "text": "In object-oriented software engineering, the software developer identifies and organizes the application in terms of object-oriented concepts, prior to their final representation in any specific programming language or software tools." }, { "code": null, "e": 19698, "s": 19533, "text": "The major phases of software development using object–oriented methodology are object-oriented analysis, object-oriented design, and object-oriented implementation." }, { "code": null, "e": 20068, "s": 19698, "text": "In this stage, the problem is formulated, user requirements are identified, and then a model is built based upon real–world objects. The analysis produces models on how the desired system should function and how it must be developed. The models do not include any implementation details so that it can be understood and examined by any non–technical application expert." }, { "code": null, "e": 20158, "s": 20068, "text": "Object-oriented design includes two main stages, namely, system design and object design." }, { "code": null, "e": 20172, "s": 20158, "text": "System Design" }, { "code": null, "e": 20597, "s": 20172, "text": "In this stage, the complete architecture of the desired system is designed. The system is conceived as a set of interacting subsystems that in turn is composed of a hierarchy of interacting objects, grouped into classes. System design is done according to both the system analysis model and the proposed system architecture. Here, the emphasis is on the objects comprising the system rather than the processes in the system." }, { "code": null, "e": 20611, "s": 20597, "text": "Object Design" }, { "code": null, "e": 20848, "s": 20611, "text": "In this phase, a design model is developed based on both the models developed in the system analysis phase and the architecture designed in the system design phase. All the classes required are identified. The designer decides whether βˆ’" }, { "code": null, "e": 20892, "s": 20848, "text": "new classes are to be created from scratch," }, { "code": null, "e": 20953, "s": 20892, "text": "any existing classes can be used in their original form, or " }, { "code": null, "e": 21013, "s": 20953, "text": "new classes should be inherited from the existing classes. " }, { "code": null, "e": 21298, "s": 21013, "text": "The associations between the identified classes are established and the hierarchies of classes are identified. Besides, the developer designs the internal details of the classes and their associations, i.e., the data structure for each attribute and the algorithms for the operations." }, { "code": null, "e": 21640, "s": 21298, "text": "In this stage, the design model developed in the object design is translated into code in an appropriate programming language or software tool. The databases are created and the specific hardware requirements are ascertained. Once the code is in shape, it is tested using specialized techniques to identify and remove the errors in the code." }, { "code": null, "e": 21792, "s": 21640, "text": "The conceptual framework of object–oriented systems is based upon the object model. There are two categories of elements in an object-oriented system βˆ’" }, { "code": null, "e": 21951, "s": 21792, "text": "Major Elements βˆ’ By major, it is meant that if a model does not have any one of these elements, it ceases to be object oriented. The four major elements are βˆ’" }, { "code": null, "e": 21963, "s": 21951, "text": "Abstraction" }, { "code": null, "e": 21977, "s": 21963, "text": "Encapsulation" }, { "code": null, "e": 21988, "s": 21977, "text": "Modularity" }, { "code": null, "e": 21998, "s": 21988, "text": "Hierarchy" }, { "code": null, "e": 22148, "s": 21998, "text": "Minor Elements βˆ’ By minor, it is meant that these elements are useful, but not indispensable part of the object model. The three minor elements are βˆ’" }, { "code": null, "e": 22155, "s": 22148, "text": "Typing" }, { "code": null, "e": 22167, "s": 22155, "text": "Concurrency" }, { "code": null, "e": 22179, "s": 22167, "text": "Persistence" }, { "code": null, "e": 22400, "s": 22179, "text": "Abstraction means to focus on the essential features of an element or object in OOP, ignoring its extraneous or accidental properties. The essential features are relative to the context in which the object is being used." }, { "code": null, "e": 22449, "s": 22400, "text": "Grady Booch has defined abstraction as follows βˆ’" }, { "code": null, "e": 22668, "s": 22449, "text": "β€œAn abstraction denotes the essential characteristics of an object that distinguish it from all other kinds of objects and thus provide crisply defined conceptual boundaries, relative to the perspective of the viewer.”" }, { "code": null, "e": 22932, "s": 22668, "text": "Example βˆ’ When a class Student is designed, the attributes enrolment_number, name, course, and address are included while characteristics like pulse_rate and size_of_shoe are eliminated, since they are irrelevant in the perspective of the educational institution." }, { "code": null, "e": 23216, "s": 22932, "text": "Encapsulation is the process of binding both attributes and methods together within a class. Through encapsulation, the internal details of a class can be hidden from outside. The class has methods that provide user interfaces by which the services provided by the class may be used." }, { "code": null, "e": 23388, "s": 23216, "text": "Modularity is the process of decomposing a problem (program) into a set of modules so as to reduce the overall complexity of the problem. Booch has defined modularity as βˆ’" }, { "code": null, "e": 23506, "s": 23388, "text": "β€œModularity is the property of a system that has been decomposed into a set of cohesive and loosely coupled modules.”" }, { "code": null, "e": 23759, "s": 23506, "text": "Modularity is intrinsically linked with encapsulation. Modularity can be visualized as a way of mapping encapsulated abstractions into real, physical modules having high cohesion within the modules and their inter–module interaction or coupling is low." }, { "code": null, "e": 24086, "s": 23759, "text": "In Grady Booch’s words, β€œHierarchy is the ranking or ordering of abstraction”. Through hierarchy, a system can be made up of interrelated subsystems, which can have their own subsystems and so on until the smallest level components are reached. It uses the principle of β€œdivide and conquer”. Hierarchy allows code reusability." }, { "code": null, "e": 24128, "s": 24086, "text": "The two types of hierarchies in OOA are βˆ’" }, { "code": null, "e": 24411, "s": 24128, "text": "β€œIS–A” hierarchy βˆ’ It defines the hierarchical relationship in inheritance, whereby from a super-class, a number of subclasses may be derived which may again have subclasses and so on. For example, if we derive a class Rose from a class Flower, we can say that a rose β€œis–a” flower." }, { "code": null, "e": 24694, "s": 24411, "text": "β€œIS–A” hierarchy βˆ’ It defines the hierarchical relationship in inheritance, whereby from a super-class, a number of subclasses may be derived which may again have subclasses and so on. For example, if we derive a class Rose from a class Flower, we can say that a rose β€œis–a” flower." }, { "code": null, "e": 24948, "s": 24694, "text": "β€œPART–OF” hierarchy βˆ’ It defines the hierarchical relationship in aggregation by which a class may be composed of other classes. For example, a flower is composed of sepals, petals, stamens, and carpel. It can be said that a petal is a β€œpart–of” flower." }, { "code": null, "e": 25202, "s": 24948, "text": "β€œPART–OF” hierarchy βˆ’ It defines the hierarchical relationship in aggregation by which a class may be composed of other classes. For example, a flower is composed of sepals, petals, stamens, and carpel. It can be said that a petal is a β€œpart–of” flower." }, { "code": null, "e": 25662, "s": 25202, "text": "According to the theories of abstract data type, a type is a characterization of a set of elements. In OOP, a class is visualized as a type having properties distinct from any other types. Typing is the enforcement of the notion that an object is an instance of a single class or type. It also enforces that objects of different types may not be generally interchanged; and can be interchanged only in a very restricted manner if absolutely required to do so." }, { "code": null, "e": 25692, "s": 25662, "text": "The two types of typing are βˆ’" }, { "code": null, "e": 25819, "s": 25692, "text": "Strong Typing βˆ’ Here, the operation on an object is checked at the time of compilation, as in the programming language Eiffel." }, { "code": null, "e": 25946, "s": 25819, "text": "Strong Typing βˆ’ Here, the operation on an object is checked at the time of compilation, as in the programming language Eiffel." }, { "code": null, "e": 26099, "s": 25946, "text": "Weak Typing βˆ’ Here, messages may be sent to any class. The operation is checked only at the time of execution, as in the programming language Smalltalk." }, { "code": null, "e": 26252, "s": 26099, "text": "Weak Typing βˆ’ Here, messages may be sent to any class. The operation is checked only at the time of execution, as in the programming language Smalltalk." }, { "code": null, "e": 26769, "s": 26252, "text": "Concurrency in operating systems allows performing multiple tasks or processes simultaneously. When a single process exists in a system, it is said that there is a single thread of control. However, most systems have multiple threads, some active, some waiting for CPU, some suspended, and some terminated. Systems with multiple CPUs inherently permit concurrent threads of control; but systems running on a single CPU use appropriate algorithms to give equitable CPU time to the threads so as to enable concurrency." }, { "code": null, "e": 27050, "s": 26769, "text": "In an object-oriented environment, there are active and inactive objects. The active objects have independent threads of control that can execute concurrently with threads of other objects. The active objects synchronize with one another as well as with purely sequential objects." }, { "code": null, "e": 27481, "s": 27050, "text": "An object occupies a memory space and exists for a particular period of time. In traditional programming, the lifespan of an object was typically the lifespan of the execution of the program that created it. In files or databases, the object lifespan is longer than the duration of the process creating the object. This property by which an object continues to exist even after its creator ceases to exist is known as persistence." }, { "code": null, "e": 27682, "s": 27481, "text": "In the system analysis or object-oriented analysis phase of software development, the system requirements are determined, the classes are identified and the relationships among classes are identified." }, { "code": null, "e": 27853, "s": 27682, "text": "The three analysis techniques that are used in conjunction with each other for object-oriented analysis are object modelling, dynamic modelling, and functional modelling." }, { "code": null, "e": 28153, "s": 27853, "text": "Object modelling develops the static structure of the software system in terms of objects. It identifies the objects, the classes into which the objects can be grouped into and the relationships between the objects. It also identifies the main attributes and operations that characterize each class." }, { "code": null, "e": 28228, "s": 28153, "text": "The process of object modelling can be visualized in the following steps βˆ’" }, { "code": null, "e": 28268, "s": 28228, "text": "Identify objects and group into classes" }, { "code": null, "e": 28309, "s": 28268, "text": "Identify the relationships among classes" }, { "code": null, "e": 28342, "s": 28309, "text": "Create user object model diagram" }, { "code": null, "e": 28372, "s": 28342, "text": "Define user object attributes" }, { "code": null, "e": 28434, "s": 28372, "text": "Define the operations that should be performed on the classes" }, { "code": null, "e": 28450, "s": 28434, "text": "Review glossary" }, { "code": null, "e": 28622, "s": 28450, "text": "After the static behavior of the system is analyzed, its behavior with respect to time and external changes needs to be examined. This is the purpose of dynamic modelling." }, { "code": null, "e": 28827, "s": 28622, "text": "Dynamic Modelling can be defined as β€œa way of describing how an individual object responds to events, either internal events triggered by other objects, or external events triggered by the outside world”." }, { "code": null, "e": 28903, "s": 28827, "text": "The process of dynamic modelling can be visualized in the following steps βˆ’" }, { "code": null, "e": 28934, "s": 28903, "text": "Identify states of each object" }, { "code": null, "e": 28991, "s": 28934, "text": "Identify events and analyze the applicability of actions" }, { "code": null, "e": 29064, "s": 28991, "text": "Construct dynamic model diagram, comprising of state transition diagrams" }, { "code": null, "e": 29113, "s": 29064, "text": "Express each state in terms of object attributes" }, { "code": null, "e": 29158, "s": 29113, "text": "Validate the state–transition diagrams drawn" }, { "code": null, "e": 29557, "s": 29158, "text": "Functional Modelling is the final component of object-oriented analysis. The functional model shows the processes that are performed within an object and how the data changes as it moves between methods. It specifies the meaning of the operations of object modelling and the actions of dynamic modelling. The functional model corresponds to the data flow diagram of traditional structured analysis." }, { "code": null, "e": 29636, "s": 29557, "text": "The process of functional modelling can be visualized in the following steps βˆ’" }, { "code": null, "e": 29672, "s": 29636, "text": "Identify all the inputs and outputs" }, { "code": null, "e": 29733, "s": 29672, "text": "Construct data flow diagrams showing functional dependencies" }, { "code": null, "e": 29768, "s": 29733, "text": "State the purpose of each function" }, { "code": null, "e": 29789, "s": 29768, "text": "Identify constraints" }, { "code": null, "e": 29819, "s": 29789, "text": "Specify optimization criteria" }, { "code": null, "e": 30016, "s": 29819, "text": "The Structured Analysis/Structured Design (SASD) approach is the traditional approach of software development based upon the waterfall model. The phases of development of a system using SASD are βˆ’" }, { "code": null, "e": 30034, "s": 30016, "text": "Feasibility Study" }, { "code": null, "e": 30073, "s": 30034, "text": "Requirement Analysis and Specification" }, { "code": null, "e": 30087, "s": 30073, "text": "System Design" }, { "code": null, "e": 30102, "s": 30087, "text": "Implementation" }, { "code": null, "e": 30129, "s": 30102, "text": "Post-implementation Review" }, { "code": null, "e": 30263, "s": 30129, "text": "Now, we will look at the relative advantages and disadvantages of structured analysis approach and object-oriented analysis approach." }, { "code": null, "e": 30440, "s": 30263, "text": "The dynamic model represents the time–dependent aspects of a system. It is concerned with the temporal changes in the states of the objects in a system. The main concepts are βˆ’" }, { "code": null, "e": 30530, "s": 30440, "text": "State, which is the situation at a particular condition during the lifetime of an object." }, { "code": null, "e": 30620, "s": 30530, "text": "State, which is the situation at a particular condition during the lifetime of an object." }, { "code": null, "e": 30654, "s": 30620, "text": "Transition, a change in the state" }, { "code": null, "e": 30688, "s": 30654, "text": "Transition, a change in the state" }, { "code": null, "e": 30735, "s": 30688, "text": "Event, an occurrence that triggers transitions" }, { "code": null, "e": 30782, "s": 30735, "text": "Event, an occurrence that triggers transitions" }, { "code": null, "e": 30865, "s": 30782, "text": "Action, an uninterrupted and atomic computation that occurs due to some event, and" }, { "code": null, "e": 30948, "s": 30865, "text": "Action, an uninterrupted and atomic computation that occurs due to some event, and" }, { "code": null, "e": 30976, "s": 30948, "text": "Concurrency of transitions." }, { "code": null, "e": 31004, "s": 30976, "text": "Concurrency of transitions." }, { "code": null, "e": 31259, "s": 31004, "text": "A state machine models the behavior of an object as it passes through a number of states in its lifetime due to some events as well as the actions occurring due to the events. A state machine is graphically represented through a state transition diagram." }, { "code": null, "e": 31640, "s": 31259, "text": "The state is an abstraction given by the values of the attributes that the object has at a particular time period. It is a situation occurring for a finite time period in the lifetime of an object, in which it fulfils certain conditions, performs certain activities, or waits for certain events to occur. In state transition diagrams, a state is represented by rounded rectangles." }, { "code": null, "e": 31726, "s": 31640, "text": "Name βˆ’ A string differentiates one state from another. A state may not have any name." }, { "code": null, "e": 31812, "s": 31726, "text": "Name βˆ’ A string differentiates one state from another. A state may not have any name." }, { "code": null, "e": 31907, "s": 31812, "text": "Entry/Exit Actions βˆ’ It denotes the activities performed on entering and on exiting the state." }, { "code": null, "e": 32002, "s": 31907, "text": "Entry/Exit Actions βˆ’ It denotes the activities performed on entering and on exiting the state." }, { "code": null, "e": 32093, "s": 32002, "text": "Internal Transitions βˆ’ The changes within a state that do not cause a change in the state." }, { "code": null, "e": 32184, "s": 32093, "text": "Internal Transitions βˆ’ The changes within a state that do not cause a change in the state." }, { "code": null, "e": 32219, "s": 32184, "text": "Sub–states βˆ’ States within states." }, { "code": null, "e": 32254, "s": 32219, "text": "Sub–states βˆ’ States within states." }, { "code": null, "e": 32703, "s": 32254, "text": "The default starting state of an object is called its initial state. The final state indicates the completion of execution of the state machine. The initial and the final states are pseudo-states, and may not have the parts of a regular state except name. In state transition diagrams, the initial state is represented by a filled black circle. The final state is represented by a filled black circle encircled within another unfilled black circle." }, { "code": null, "e": 33165, "s": 32703, "text": "A transition denotes a change in the state of an object. If an object is in a certain state when an event occurs, the object may perform certain activities subject to specified conditions and change the state. In this case, a stateβˆ’transition is said to have occurred. The transition gives the relationship between the first state and the new state. A transition is graphically represented by a solid directed arc from the source state to the destination state." }, { "code": null, "e": 33202, "s": 33165, "text": "The five parts of a transition are βˆ’" }, { "code": null, "e": 33255, "s": 33202, "text": "Source State βˆ’ The state affected by the transition." }, { "code": null, "e": 33308, "s": 33255, "text": "Source State βˆ’ The state affected by the transition." }, { "code": null, "e": 33442, "s": 33308, "text": "Event Trigger βˆ’ The occurrence due to which an object in the source state undergoes a transition if the guard condition is satisfied." }, { "code": null, "e": 33576, "s": 33442, "text": "Event Trigger βˆ’ The occurrence due to which an object in the source state undergoes a transition if the guard condition is satisfied." }, { "code": null, "e": 33682, "s": 33576, "text": "Guard Condition βˆ’ A Boolean expression which if True, causes a transition on receiving the event trigger." }, { "code": null, "e": 33788, "s": 33682, "text": "Guard Condition βˆ’ A Boolean expression which if True, causes a transition on receiving the event trigger." }, { "code": null, "e": 33892, "s": 33788, "text": "Action βˆ’ An un-interruptible and atomic computation that occurs on the source object due to some event." }, { "code": null, "e": 33996, "s": 33892, "text": "Action βˆ’ An un-interruptible and atomic computation that occurs on the source object due to some event." }, { "code": null, "e": 34065, "s": 33996, "text": "Target State βˆ’ The destination state after completion of transition." }, { "code": null, "e": 34134, "s": 34065, "text": "Target State βˆ’ The destination state after completion of transition." }, { "code": null, "e": 34142, "s": 34134, "text": "Example" }, { "code": null, "e": 34411, "s": 34142, "text": "Suppose a person is taking a taxi from place X to place Y. The states of the person may be: Waiting (waiting for taxi), Riding (he has got a taxi and is travelling in it), and Reached (he has reached the destination). The following figure depicts the state transition." }, { "code": null, "e": 34651, "s": 34411, "text": "Events are some occurrences that can trigger state transition of an object or a group of objects. Events have a location in time and space but do not have a time period associated with it. Events are generally associated with some actions." }, { "code": null, "e": 34733, "s": 34651, "text": "Examples of events are mouse click, key press, an interrupt, stack overflow, etc." }, { "code": null, "e": 34828, "s": 34733, "text": "Events that trigger transitions are written alongside the arc of transition in state diagrams." }, { "code": null, "e": 34836, "s": 34828, "text": "Example" }, { "code": null, "e": 35185, "s": 34836, "text": "Considering the example shown in the above figure, the transition from Waiting state to Riding state takes place when the person gets a taxi. Likewise, the final state is reached, when he reaches the destination. These two occurrences can be termed as events Get_Taxi and Reach_Destination. The following figure shows the events in a state machine." }, { "code": null, "e": 35359, "s": 35185, "text": "External events are those events that pass from a user of the system to the objects within the system. For example, mouse click or keyβˆ’press by the user are external events." }, { "code": null, "e": 35496, "s": 35359, "text": "Internal events are those that pass from one object to another object within a system. For example, stack overflow, a divide error, etc." }, { "code": null, "e": 35698, "s": 35496, "text": "Deferred events are those which are not immediately handled by the object in the current state but are lined up in a queue so that they can be handled by the object in some other state at a later time." }, { "code": null, "e": 36083, "s": 35698, "text": "Event class indicates a group of events with common structure and behavior. As with classes of objects, event classes may also be organized in a hierarchical structure. Event classes may have attributes associated with them, time being an implicit attribute. For example, we can consider the events of departure of a flight of an airline, which we can group into the following class βˆ’" }, { "code": null, "e": 36137, "s": 36083, "text": "Flight_Departs (Flight_No, From_City, To_City, Route)" }, { "code": null, "e": 36390, "s": 36137, "text": "Activity is an operation upon the states of an object that requires some time period. They are the ongoing executions within a system that can be interrupted. Activities are shown in activity diagrams that portray the flow from one activity to another." }, { "code": null, "e": 36793, "s": 36390, "text": "An action is an atomic operation that executes as a result of certain events. By atomic, it is meant that actions are un-interruptible, i.e., if an action starts executing, it runs into completion without being interrupted by any event. An action may operate upon an object on which an event has been triggered or on other objects that are visible to this object. A set of actions comprise an activity." }, { "code": null, "e": 36907, "s": 36793, "text": "Entry action is the action that is executed on entering a state, irrespective of the transition that led into it." }, { "code": null, "e": 37045, "s": 36907, "text": "Likewise, the action that is executed while leaving a state, irrespective of the transition that led out of it, is called an exit action." }, { "code": null, "e": 37294, "s": 37045, "text": "Scenario is a description of a specified sequence of actions. It depicts the behavior of objects undergoing a specific action series. The primary scenarios depict the essential sequences and the secondary scenarios depict the alternative sequences." }, { "code": null, "e": 37363, "s": 37294, "text": "There are two primary diagrams that are used for dynamic modelling βˆ’" }, { "code": null, "e": 37666, "s": 37363, "text": "Interaction diagrams describe the dynamic behavior among different objects. It comprises of a set of objects, their relationships, and the message that the objects send and receive. Thus, an interaction models the behavior of a group of interrelated objects. The two types of interaction diagrams are βˆ’" }, { "code": null, "e": 37754, "s": 37666, "text": "Sequence Diagram βˆ’ It represents the temporal ordering of messages in a tabular manner." }, { "code": null, "e": 37842, "s": 37754, "text": "Sequence Diagram βˆ’ It represents the temporal ordering of messages in a tabular manner." }, { "code": null, "e": 37977, "s": 37842, "text": "Collaboration Diagram βˆ’ It represents the structural organization of objects that send and receive messages through vertices and arcs." }, { "code": null, "e": 38112, "s": 37977, "text": "Collaboration Diagram βˆ’ It represents the structural organization of objects that send and receive messages through vertices and arcs." }, { "code": null, "e": 38407, "s": 38112, "text": "State transition diagrams or state machines describe the dynamic behavior of a single object. It illustrates the sequences of states that an object goes through in its lifetime, the transitions of the states, the events and conditions causing the transition and the responses due to the events." }, { "code": null, "e": 38467, "s": 38407, "text": "In a system, two types of concurrency may exist. They are βˆ’" }, { "code": null, "e": 38647, "s": 38467, "text": "Here, concurrency is modelled in the system level. The overall system is modelled as the aggregation of state machines, where each state machine executes concurrently with others." }, { "code": null, "e": 38810, "s": 38647, "text": "Here, an object can issue concurrent events. An object may have states that are composed of sub-states, and concurrent events may occur in each of the sub-states." }, { "code": null, "e": 38876, "s": 38810, "text": "Concepts related to concurrency within an object are as follows βˆ’" }, { "code": null, "e": 39167, "s": 38876, "text": "A simple state has no sub-structure. A state that has simpler states nested inside it is called a composite state. A sub-state is a state that is nested inside another state. It is generally used to reduce the complexity of a state machine. Sub-states can be nested to any number of levels." }, { "code": null, "e": 39248, "s": 39167, "text": "Composite states may have either sequential sub-states or concurrent sub-states." }, { "code": null, "e": 39468, "s": 39248, "text": "In sequential sub-states, the control of execution passes from one sub-state to another sub-state one after another in a sequential manner. There is at most one initial state and one final state in these state machines." }, { "code": null, "e": 39539, "s": 39468, "text": "The following figure illustrates the concept of sequential sub-states." }, { "code": null, "e": 39957, "s": 39539, "text": "In concurrent sub-states, the sub-states execute in parallel, or in other words, each state has concurrently executing state machines within it. Each of the state machines has its own initial and final states. If one concurrent sub-state reaches its final state before the other, control waits at its final state. When all the nested state machines reach their final states, the sub-states join back to a single flow." }, { "code": null, "e": 40022, "s": 39957, "text": "The following figure shows the concept of concurrent sub-states." }, { "code": null, "e": 40425, "s": 40022, "text": "Functional Modelling gives the process perspective of the object-oriented analysis model and an overview of what the system is supposed to do. It defines the function of the internal processes in the system with the aid of Data Flow Diagrams (DFDs). It depicts the functional derivation of the data values without indicating how they are derived when they are computed, or why they need to be computed." }, { "code": null, "e": 40844, "s": 40425, "text": "Functional Modelling is represented through a hierarchy of DFDs. The DFD is a graphical representation of a system that shows the inputs to the system, the processing upon the inputs, the outputs of the system as well as the internal data stores. DFDs illustrate the series of transformations or computations performed on the objects or the system, and the external controls and objects that affect the transformation." }, { "code": null, "e": 41058, "s": 40844, "text": "Rumbaugh et al. have defined DFD as, β€œA data flow diagram is a graph which shows the flow of data values from their sources in objects through processes that transform them to their destinations on other objects.”" }, { "code": null, "e": 41093, "s": 41058, "text": "The four main parts of a DFD are βˆ’" }, { "code": null, "e": 41104, "s": 41093, "text": "Processes," }, { "code": null, "e": 41116, "s": 41104, "text": "Data Flows," }, { "code": null, "e": 41128, "s": 41116, "text": "Actors, and" }, { "code": null, "e": 41141, "s": 41128, "text": "Data Stores." }, { "code": null, "e": 41172, "s": 41141, "text": "The other parts of a DFD are βˆ’" }, { "code": null, "e": 41189, "s": 41172, "text": "Constraints, and" }, { "code": null, "e": 41204, "s": 41189, "text": "Control Flows." }, { "code": null, "e": 41442, "s": 41204, "text": "Processes are the computational activities that transform data values. A whole system can be visualized as a high-level process. A process may be further divided into smaller components. The lowest-level process may be a simple function." }, { "code": null, "e": 41598, "s": 41442, "text": "Representation in DFD βˆ’ A process is represented as an ellipse with its name written inside it and contains a fixed number of input and output data values." }, { "code": null, "e": 41776, "s": 41598, "text": "Example βˆ’ The following figure shows a process Compute_HCF_LCM that accepts two integers as inputs and outputs their HCF (highest common factor) and LCM (least common multiple)." }, { "code": null, "e": 42043, "s": 41776, "text": "Data flow represents the flow of data between two processes. It could be between an actor and a process, or between a data store and a process. A data flow denotes the value of a data item at some point of the computation. This value is not changed by the data flow." }, { "code": null, "e": 42182, "s": 42043, "text": "Representation in DFD βˆ’ A data flow is represented by a directed arc or an arrow, labelled with the name of the data item that it carries." }, { "code": null, "e": 42325, "s": 42182, "text": "In the above figure, Integer_a and Integer_b represent the input data flows to the process, while L.C.M. and H.C.F. are the output data flows." }, { "code": null, "e": 42376, "s": 42325, "text": "A data flow may be forked in the following cases βˆ’" }, { "code": null, "e": 42523, "s": 42376, "text": "The output value is sent to several places as shown in the following figure. Here, the output arrows are unlabelled as they denote the same value." }, { "code": null, "e": 42670, "s": 42523, "text": "The output value is sent to several places as shown in the following figure. Here, the output arrows are unlabelled as they denote the same value." }, { "code": null, "e": 42851, "s": 42670, "text": "The data flow contains an aggregate value, and each of the components is sent to different places as shown in the following figure. Here, each of the forked components is labelled." }, { "code": null, "e": 43032, "s": 42851, "text": "The data flow contains an aggregate value, and each of the components is sent to different places as shown in the following figure. Here, each of the forked components is labelled." }, { "code": null, "e": 43260, "s": 43032, "text": "Actors are the active objects that interact with the system by either producing data and inputting them to the system, or consuming data produced by the system. In other words, actors serve as the sources and the sinks of data." }, { "code": null, "e": 43407, "s": 43260, "text": "Representation in DFD βˆ’ An actor is represented by a rectangle. Actors are connected to the inputs and outputs and lie on the boundary of the DFD." }, { "code": null, "e": 43516, "s": 43407, "text": "Example βˆ’ The following figure shows the actors, namely, Customer and Sales_Clerk in a counter sales system." }, { "code": null, "e": 43767, "s": 43516, "text": "Data stores are the passive objects that act as a repository of data. Unlike actors, they cannot perform any operations. They are used to store data and retrieve the stored data. They represent a data structure, a disk file, or a table in a database." }, { "code": null, "e": 44261, "s": 43767, "text": "Representation in DFD βˆ’ A data store is represented by two parallel lines containing the name of the data store. Each data store is connected to at least one process. Input arrows contain information to modify the contents of the data store, while output arrows contain information retrieved from the data store. When a part of the information is to be retrieved, the output arrow is labelled. An unlabelled arrow denotes full data retrieval. A two-way arrow implies both retrieval and update." }, { "code": null, "e": 44552, "s": 44261, "text": "Example βˆ’ The following figure shows a data store, Sales_Record, that stores the details of all sales. Input to the data store comprises of details of sales such as item, billing amount, date, etc. To find the average sales, the process retrieves the sales records and computes the average." }, { "code": null, "e": 44772, "s": 44552, "text": "Constraints specify the conditions or restrictions that need to be satisfied over time. They allow adding new rules or modifying existing ones. Constraints can appear in all the three models of object-oriented analysis." }, { "code": null, "e": 44961, "s": 44772, "text": "In Object Modelling, the constraints define the relationship between objects. They may also define the relationship between the different values that an object may take at different times." }, { "code": null, "e": 45150, "s": 44961, "text": "In Object Modelling, the constraints define the relationship between objects. They may also define the relationship between the different values that an object may take at different times." }, { "code": null, "e": 45264, "s": 45150, "text": "In Dynamic Modelling, the constraints define the relationship between the states and events of different objects." }, { "code": null, "e": 45378, "s": 45264, "text": "In Dynamic Modelling, the constraints define the relationship between the states and events of different objects." }, { "code": null, "e": 45484, "s": 45378, "text": "In Functional Modelling, the constraints define the restrictions on the transformations and computations." }, { "code": null, "e": 45590, "s": 45484, "text": "In Functional Modelling, the constraints define the restrictions on the transformations and computations." }, { "code": null, "e": 45659, "s": 45590, "text": "Representation βˆ’ A constraint is rendered as a string within braces." }, { "code": null, "e": 46110, "s": 45659, "text": "Example βˆ’ The following figure shows a portion of DFD for computing the salary of employees of a company that has decided to give incentives to all employees of the sales department and increment the salary of all employees of the HR department. It can be seen that the constraint {Dept:Sales} causes incentive to be calculated only if the department is sales and the constraint {Dept:HR} causes increment to be computed only if the department is HR." }, { "code": null, "e": 46310, "s": 46110, "text": "A process may be associated with a certain Boolean value and is evaluated only if the value is true, though it is not a direct input to the process. These Boolean values are called the control flows." }, { "code": null, "e": 46460, "s": 46310, "text": "Representation in DFD βˆ’ Control flows are represented by a dotted arc from the process producing the Boolean value to the process controlled by them." }, { "code": null, "e": 46702, "s": 46460, "text": "Example βˆ’ The following figure represents a DFD for arithmetic division. The Divisor is tested for non-zero. If it is not zero, the control flow OK has a value True and subsequently the Divide process computes the Quotient and the Remainder." }, { "code": null, "e": 46870, "s": 46702, "text": "In order to develop the DFD model of a system, a hierarchy of DFDs are constructed. The top-level DFD comprises of a single process and the actors interacting with it." }, { "code": null, "e": 47231, "s": 46870, "text": "At each successive lower level, further details are gradually included. A process is decomposed into sub-processes, the data flows among the sub-processes are identified, the control flows are determined, and the data stores are defined. While decomposing a process, the data flow into or out of the process should match the data flow at the next level of DFD." }, { "code": null, "e": 47813, "s": 47231, "text": "Example βˆ’ Let us consider a software system, Wholesaler Software, that automates the transactions of a wholesale shop. The shop sells in bulks and has a clientele comprising of merchants and retail shop owners. Each customer is asked to register with his/her particulars and is given a unique customer code, C_Code. Once a sale is done, the shop registers its details and sends the goods for dispatch. Each year, the shop distributes Christmas gifts to its customers, which comprise of a silver coin or a gold coin depending upon the total sales and the decision of the proprietor." }, { "code": null, "e": 47999, "s": 47813, "text": "The functional model for the Wholesale Software is given below. The figure below shows the top-level DFD. It shows the software as a single process and the actors that interact with it." }, { "code": null, "e": 48030, "s": 47999, "text": "The actors in the system are βˆ’" }, { "code": null, "e": 48040, "s": 48030, "text": "Customers" }, { "code": null, "e": 48052, "s": 48040, "text": "Salesperson" }, { "code": null, "e": 48063, "s": 48052, "text": "Proprietor" }, { "code": null, "e": 48289, "s": 48063, "text": "In the next level DFD, as shown in the following figure, the major processes of the system are identified, the data stores are defined and the interaction of the processes with the actors, and the data stores are established." }, { "code": null, "e": 48351, "s": 48289, "text": "In the system, three processes can be identified, which are βˆ’" }, { "code": null, "e": 48370, "s": 48351, "text": "Register Customers" }, { "code": null, "e": 48384, "s": 48370, "text": "Process Sales" }, { "code": null, "e": 48400, "s": 48384, "text": "Ascertain Gifts" }, { "code": null, "e": 48444, "s": 48400, "text": "The data stores that will be required are βˆ’" }, { "code": null, "e": 48461, "s": 48444, "text": "Customer Details" }, { "code": null, "e": 48475, "s": 48461, "text": "Sales Details" }, { "code": null, "e": 48488, "s": 48475, "text": "Gift Details" }, { "code": null, "e": 48813, "s": 48488, "text": "The following figure shows the details of the process Register Customer. There are three processes in it, Verify Details, Generate C_Code, and Update Customer Details. When the details of the customer are entered, they are verified. If the data is correct, C_Code is generated and the data store Customer Details is updated." }, { "code": null, "e": 49210, "s": 48813, "text": "The following figure shows the expansion of the process Ascertain Gifts. It has two processes in it, Find Total Sales and Decide Type of Gift Coin. The Find Total Sales process computes the yearly total sales corresponding to each customer and records the data. Taking this record and the decision of the proprietor as inputs, the gift coins are allotted through Decide Type of Gift Coin process." }, { "code": null, "e": 49345, "s": 49210, "text": "The Object Model, the Dynamic Model, and the Functional Model are complementary to each other for a complete Object-Oriented Analysis." }, { "code": null, "e": 49475, "s": 49345, "text": "Object modelling develops the static structure of the software system in terms of objects. Thus it shows the β€œdoers” of a system." }, { "code": null, "e": 49605, "s": 49475, "text": "Object modelling develops the static structure of the software system in terms of objects. Thus it shows the β€œdoers” of a system." }, { "code": null, "e": 49764, "s": 49605, "text": "Dynamic Modelling develops the temporal behavior of the objects in response to external events. It shows the sequences of operations performed on the objects." }, { "code": null, "e": 49923, "s": 49764, "text": "Dynamic Modelling develops the temporal behavior of the objects in response to external events. It shows the sequences of operations performed on the objects." }, { "code": null, "e": 49988, "s": 49923, "text": "Functional model gives an overview of what the system should do." }, { "code": null, "e": 50053, "s": 49988, "text": "Functional model gives an overview of what the system should do." }, { "code": null, "e": 50126, "s": 50053, "text": "The four main parts of a Functional Model in terms of object model are βˆ’" }, { "code": null, "e": 50208, "s": 50126, "text": "Process βˆ’ Processes imply the methods of the objects that need to be implemented." }, { "code": null, "e": 50290, "s": 50208, "text": "Process βˆ’ Processes imply the methods of the objects that need to be implemented." }, { "code": null, "e": 50343, "s": 50290, "text": "Actors βˆ’ Actors are the objects in the object model." }, { "code": null, "e": 50396, "s": 50343, "text": "Actors βˆ’ Actors are the objects in the object model." }, { "code": null, "e": 50481, "s": 50396, "text": "Data Stores βˆ’ These are either objects in the object model or attributes of objects." }, { "code": null, "e": 50566, "s": 50481, "text": "Data Stores βˆ’ These are either objects in the object model or attributes of objects." }, { "code": null, "e": 50711, "s": 50566, "text": "Data Flows βˆ’ Data flows to or from actors represent operations on or by objects. Data flows to or from data stores represent queries or updates." }, { "code": null, "e": 50856, "s": 50711, "text": "Data Flows βˆ’ Data flows to or from actors represent operations on or by objects. Data flows to or from data stores represent queries or updates." }, { "code": null, "e": 51224, "s": 50856, "text": "The dynamic model states when the operations are performed, while the functional model states how they are performed and which arguments are needed. As actors are active objects, the dynamic model has to specify when it acts. The data stores are passive objects and they only respond to updates and queries; therefore the dynamic model need not specify when they act." }, { "code": null, "e": 51451, "s": 51224, "text": "The dynamic model shows the status of the objects and the operations performed on the occurrences of events and the subsequent changes in states. The state of the object as a result of the changes is shown in the object model." }, { "code": null, "e": 51765, "s": 51451, "text": "The Unified Modeling Language (UML) is a graphical language for OOAD that gives a standard way to write a software system’s blueprint. It helps to visualize, specify, construct, and document the artifacts of an object-oriented system. It is used to depict the structures and the relationships in a complex system." }, { "code": null, "e": 52082, "s": 51765, "text": "It was developed in 1990s as an amalgamation of several techniques, prominently OOAD technique by Grady Booch, OMT (Object Modeling Technique) by James Rumbaugh, and OOSE (Object Oriented Software Engineering) by Ivar Jacobson. UML attempted to standardize semantic models, syntactic notations, and diagrams of OOAD." }, { "code": null, "e": 52240, "s": 52082, "text": "System βˆ’ A set of elements organized to achieve certain objectives form a system. Systems are often divided into subsystems and described by a set of models." }, { "code": null, "e": 52369, "s": 52240, "text": "Model βˆ’ Model is a simplified, complete, and consistent abstraction of a system, created for better understanding of the system." }, { "code": null, "e": 52448, "s": 52369, "text": "View βˆ’ A view is a projection of a system’s model from a specific perspective." }, { "code": null, "e": 52511, "s": 52448, "text": "The Conceptual Model of UML encompasses three major elements βˆ’" }, { "code": null, "e": 52533, "s": 52511, "text": "Basic building blocks" }, { "code": null, "e": 52539, "s": 52533, "text": "Rules" }, { "code": null, "e": 52557, "s": 52539, "text": "Common mechanisms" }, { "code": null, "e": 52596, "s": 52557, "text": "The three building blocks of UML are βˆ’" }, { "code": null, "e": 52603, "s": 52596, "text": "Things" }, { "code": null, "e": 52617, "s": 52603, "text": "Relationships" }, { "code": null, "e": 52626, "s": 52617, "text": "Diagrams" }, { "code": null, "e": 52674, "s": 52626, "text": "There are four kinds of things in UML, namely βˆ’" }, { "code": null, "e": 52914, "s": 52674, "text": "Structural Things βˆ’ These are the nouns of the UML models representing the static elements that may be either physical or conceptual. The structural things are class, interface, collaboration, use case, active class, components, and nodes." }, { "code": null, "e": 53154, "s": 52914, "text": "Structural Things βˆ’ These are the nouns of the UML models representing the static elements that may be either physical or conceptual. The structural things are class, interface, collaboration, use case, active class, components, and nodes." }, { "code": null, "e": 53337, "s": 53154, "text": "Behavioral Things βˆ’ These are the verbs of the UML models representing the dynamic behavior over time and space. The two types of behavioral things are interaction and state machine." }, { "code": null, "e": 53520, "s": 53337, "text": "Behavioral Things βˆ’ These are the verbs of the UML models representing the dynamic behavior over time and space. The two types of behavioral things are interaction and state machine." }, { "code": null, "e": 53653, "s": 53520, "text": "Grouping Things βˆ’ They comprise the organizational parts of the UML models. There is only one kind of grouping thing, i.e., package." }, { "code": null, "e": 53786, "s": 53653, "text": "Grouping Things βˆ’ They comprise the organizational parts of the UML models. There is only one kind of grouping thing, i.e., package." }, { "code": null, "e": 53909, "s": 53786, "text": "Annotational Things βˆ’ These are the explanations in the UML models representing the comments applied to describe elements." }, { "code": null, "e": 54032, "s": 53909, "text": "Annotational Things βˆ’ These are the explanations in the UML models representing the comments applied to describe elements." }, { "code": null, "e": 54150, "s": 54032, "text": "Relationships are the connection between things. The four types of relationships that can be represented in UML are βˆ’" }, { "code": null, "e": 54354, "s": 54150, "text": "Dependency βˆ’ This is a semantic relationship between two things such that a change in one thing brings a change in the other. The former is the independent thing, while the latter is the dependent thing." }, { "code": null, "e": 54558, "s": 54354, "text": "Dependency βˆ’ This is a semantic relationship between two things such that a change in one thing brings a change in the other. The former is the independent thing, while the latter is the dependent thing." }, { "code": null, "e": 54684, "s": 54558, "text": "Association βˆ’ This is a structural relationship that represents a group of links having common structure and common behavior." }, { "code": null, "e": 54810, "s": 54684, "text": "Association βˆ’ This is a structural relationship that represents a group of links having common structure and common behavior." }, { "code": null, "e": 54959, "s": 54810, "text": "Generalization βˆ’ This represents a generalization/specialization relationship in which subclasses inherit structure and behavior from super-classes." }, { "code": null, "e": 55108, "s": 54959, "text": "Generalization βˆ’ This represents a generalization/specialization relationship in which subclasses inherit structure and behavior from super-classes." }, { "code": null, "e": 55279, "s": 55108, "text": "Realization βˆ’ This is a semantic relationship between two or more classifiers such that one classifier lays down a contract that the other classifiers ensure to abide by." }, { "code": null, "e": 55450, "s": 55279, "text": "Realization βˆ’ This is a semantic relationship between two or more classifiers such that one classifier lays down a contract that the other classifiers ensure to abide by." }, { "code": null, "e": 55617, "s": 55450, "text": "A diagram is a graphical representation of a system. It comprises of a group of elements generally in the form of a graph. UML includes nine diagrams in all, namely βˆ’" }, { "code": null, "e": 55631, "s": 55617, "text": "Class Diagram" }, { "code": null, "e": 55646, "s": 55631, "text": "Object Diagram" }, { "code": null, "e": 55663, "s": 55646, "text": "Use Case Diagram" }, { "code": null, "e": 55680, "s": 55663, "text": "Sequence Diagram" }, { "code": null, "e": 55702, "s": 55680, "text": "Collaboration Diagram" }, { "code": null, "e": 55722, "s": 55702, "text": "State Chart Diagram" }, { "code": null, "e": 55739, "s": 55722, "text": "Activity Diagram" }, { "code": null, "e": 55757, "s": 55739, "text": "Component Diagram" }, { "code": null, "e": 55776, "s": 55757, "text": "Deployment Diagram" }, { "code": null, "e": 55953, "s": 55776, "text": "UML has a number of rules so that the models are semantically self-consistent and related to other models in the system harmoniously. UML has semantic rules for the following βˆ’" }, { "code": null, "e": 55959, "s": 55953, "text": "Names" }, { "code": null, "e": 55965, "s": 55959, "text": "Scope" }, { "code": null, "e": 55976, "s": 55965, "text": "Visibility" }, { "code": null, "e": 55986, "s": 55976, "text": "Integrity" }, { "code": null, "e": 55996, "s": 55986, "text": "Execution" }, { "code": null, "e": 56029, "s": 55996, "text": "UML has four common mechanisms βˆ’" }, { "code": null, "e": 56044, "s": 56029, "text": "Specifications" }, { "code": null, "e": 56055, "s": 56044, "text": "Adornments" }, { "code": null, "e": 56072, "s": 56055, "text": "Common Divisions" }, { "code": null, "e": 56097, "s": 56072, "text": "Extensibility Mechanisms" }, { "code": null, "e": 56367, "s": 56097, "text": "In UML, behind each graphical notation, there is a textual statement denoting the syntax and semantics. These are the specifications. The specifications provide a semantic backplane that contains all the parts of a system and the relationship among the different paths." }, { "code": null, "e": 56533, "s": 56367, "text": "Each element in UML has a unique graphical notation. Besides, there are notations to represent the important aspects of an element like name, scope, visibility, etc." }, { "code": null, "e": 56624, "s": 56533, "text": "Object-oriented systems can be divided in many ways. The two common ways of division are βˆ’" }, { "code": null, "e": 56791, "s": 56624, "text": "Division of classes and objects βˆ’ A class is an abstraction of a group of similar objects. An object is the concrete instance that has actual existence in the system." }, { "code": null, "e": 56958, "s": 56791, "text": "Division of classes and objects βˆ’ A class is an abstraction of a group of similar objects. An object is the concrete instance that has actual existence in the system." }, { "code": null, "e": 57131, "s": 56958, "text": "Division of Interface and Implementation βˆ’ An interface defines the rules for interaction. Implementation is the concrete realization of the rules defined in the interface." }, { "code": null, "e": 57304, "s": 57131, "text": "Division of Interface and Implementation βˆ’ An interface defines the rules for interaction. Implementation is the concrete realization of the rules defined in the interface." }, { "code": null, "e": 57480, "s": 57304, "text": "UML is an open-ended language. It is possible to extend the capabilities of UML in a controlled manner to suit the requirements of a system. The extensibility mechanisms are βˆ’" }, { "code": null, "e": 57603, "s": 57480, "text": "Stereotypes βˆ’ It extends the vocabulary of the UML, through which new building blocks can be created out of existing ones." }, { "code": null, "e": 57726, "s": 57603, "text": "Stereotypes βˆ’ It extends the vocabulary of the UML, through which new building blocks can be created out of existing ones." }, { "code": null, "e": 57792, "s": 57726, "text": "Tagged Values βˆ’ It extends the properties of UML building blocks." }, { "code": null, "e": 57858, "s": 57792, "text": "Tagged Values βˆ’ It extends the properties of UML building blocks." }, { "code": null, "e": 57921, "s": 57858, "text": "Constraints βˆ’ It extends the semantics of UML building blocks." }, { "code": null, "e": 57984, "s": 57921, "text": "Constraints βˆ’ It extends the semantics of UML building blocks." }, { "code": null, "e": 58048, "s": 57984, "text": "UML defines specific notations for each of the building blocks." }, { "code": null, "e": 58110, "s": 58048, "text": "A class is represented by a rectangle having three sections βˆ’" }, { "code": null, "e": 58159, "s": 58110, "text": "the top section containing the name of the class" }, { "code": null, "e": 58206, "s": 58159, "text": "the middle section containing class attributes" }, { "code": null, "e": 58262, "s": 58206, "text": "the bottom section representing operations of the class" }, { "code": null, "e": 58353, "s": 58262, "text": "The visibility of the attributes and operations can be represented in the following ways βˆ’" }, { "code": null, "e": 58470, "s": 58353, "text": "Public βˆ’ A public member is visible from anywhere in the system. In class diagram, it is prefixed by the symbol β€˜+’." }, { "code": null, "e": 58587, "s": 58470, "text": "Public βˆ’ A public member is visible from anywhere in the system. In class diagram, it is prefixed by the symbol β€˜+’." }, { "code": null, "e": 58747, "s": 58587, "text": "Private βˆ’ A private member is visible only from within the class. It cannot be accessed from outside the class. A private member is prefixed by the symbol β€˜βˆ’β€™." }, { "code": null, "e": 58907, "s": 58747, "text": "Private βˆ’ A private member is visible only from within the class. It cannot be accessed from outside the class. A private member is prefixed by the symbol β€˜βˆ’β€™." }, { "code": null, "e": 59078, "s": 58907, "text": "Protected βˆ’ A protected member is visible from within the class and from the subclasses inherited from this class, but not from outside. It is prefixed by the symbol β€˜#’." }, { "code": null, "e": 59249, "s": 59078, "text": "Protected βˆ’ A protected member is visible from within the class and from the subclasses inherited from this class, but not from outside. It is prefixed by the symbol β€˜#’." }, { "code": null, "e": 59306, "s": 59249, "text": "An abstract class has the class name written in italics." }, { "code": null, "e": 59703, "s": 59306, "text": "Example βˆ’ Let us consider the Circle class introduced earlier. The attributes of Circle are x-coord, y-coord, and radius. The operations are findArea(), findCircumference(), and scale(). Let us assume that x-coord and y-coord are private data members, radius is a protected data member, and the member functions are public. The following figure gives the diagrammatic representation of the class." }, { "code": null, "e": 59763, "s": 59703, "text": "An object is represented as a rectangle with two sections βˆ’" }, { "code": null, "e": 60028, "s": 59763, "text": "The top section contains the name of the object with the name of the class or package of which it is an instance of. The name takes the following forms βˆ’\n\nobject-name βˆ’ class-name\nobject-name βˆ’ class-name :: package-name\nclass-name βˆ’ in case of anonymous objects\n\n" }, { "code": null, "e": 60182, "s": 60028, "text": "The top section contains the name of the object with the name of the class or package of which it is an instance of. The name takes the following forms βˆ’" }, { "code": null, "e": 60207, "s": 60182, "text": "object-name βˆ’ class-name" }, { "code": null, "e": 60232, "s": 60207, "text": "object-name βˆ’ class-name" }, { "code": null, "e": 60273, "s": 60232, "text": "object-name βˆ’ class-name :: package-name" }, { "code": null, "e": 60314, "s": 60273, "text": "object-name βˆ’ class-name :: package-name" }, { "code": null, "e": 60356, "s": 60314, "text": "class-name βˆ’ in case of anonymous objects" }, { "code": null, "e": 60398, "s": 60356, "text": "class-name βˆ’ in case of anonymous objects" }, { "code": null, "e": 60500, "s": 60398, "text": "The bottom section represents the values of the attributes. It takes the form attribute-name = value." }, { "code": null, "e": 60602, "s": 60500, "text": "The bottom section represents the values of the attributes. It takes the form attribute-name = value." }, { "code": null, "e": 60662, "s": 60602, "text": "Sometimes objects are represented using rounded rectangles." }, { "code": null, "e": 60722, "s": 60662, "text": "Sometimes objects are represented using rounded rectangles." }, { "code": null, "e": 60901, "s": 60722, "text": "Example βˆ’ Let us consider an object of the class Circle named c1. We assume that the center of c1 is at (2, 3) and the radius of c1 is 5. The following figure depicts the object." }, { "code": null, "e": 61110, "s": 60901, "text": "A component is a physical and replaceable part of the system that conforms to and provides the realization of a set of interfaces. It represents the physical packaging of elements like classes and interfaces." }, { "code": null, "e": 61220, "s": 61110, "text": "Notation βˆ’ In UML diagrams, a component is represented by a rectangle with tabs as shown in the figure below." }, { "code": null, "e": 61363, "s": 61220, "text": "Interface is a collection of methods of a class or component. It specifies the set of services that may be provided by the class or component." }, { "code": null, "e": 61583, "s": 61363, "text": "Notation βˆ’ Generally, an interface is drawn as a circle together with its name. An interface is almost always attached to the class or component that realizes it. The following figure gives the notation of an interface." }, { "code": null, "e": 61720, "s": 61583, "text": "A package is an organized group of elements. A package may contain structural things like classes, components, and other packages in it." }, { "code": null, "e": 61939, "s": 61720, "text": "Notation βˆ’ Graphically, a package is represented by a tabbed folder. A package is generally drawn with only its name. However it may have additional details about the contents of the package. See the following figures." }, { "code": null, "e": 62011, "s": 61939, "text": "The notations for the different types of relationships are as follows βˆ’" }, { "code": null, "e": 62173, "s": 62011, "text": "Usually, elements in a relationship play specific roles in the relationship. A role name signifies the behavior of an element participating in a certain context." }, { "code": null, "e": 62651, "s": 62173, "text": "Example βˆ’ The following figures show examples of different relationships between classes. The first figure shows an association between two classes, Department and Employee, wherein a department may have a number of employees working in it. Worker is the role name. The β€˜1’ alongside Department and β€˜*’ alongside Employee depict that the cardinality ratio is one–to–many. The second figure portrays the aggregation relationship, a University is the β€œwhole–of” many Departments." }, { "code": null, "e": 62777, "s": 62651, "text": "UML structural diagrams are categorized as follows: class diagram, object diagram, component diagram, and deployment diagram." }, { "code": null, "e": 62938, "s": 62777, "text": "A class diagram models the static view of a system. It comprises of the classes, interfaces, and collaborations of a system; and the relationships between them." }, { "code": null, "e": 62983, "s": 62938, "text": "Let us consider a simplified Banking System." }, { "code": null, "e": 63436, "s": 62983, "text": "A bank has many branches. In each zone, one branch is designated as the zonal head office that supervises the other branches in that zone. Each branch can have multiple accounts and loans. An account may be either a savings account or a current account. A customer may open both a savings account and a current account. However, a customer must not have more than one savings account or current account. A customer may also procure loans from the bank." }, { "code": null, "e": 63496, "s": 63436, "text": "The following figure shows the corresponding class diagram." }, { "code": null, "e": 63573, "s": 63496, "text": "Bank, Branch, Account, Savings Account, Current Account, Loan, and Customer." }, { "code": null, "e": 63634, "s": 63573, "text": "A Bank β€œhas–a” number of Branches βˆ’ composition, one–to–many" }, { "code": null, "e": 63695, "s": 63634, "text": "A Bank β€œhas–a” number of Branches βˆ’ composition, one–to–many" }, { "code": null, "e": 63791, "s": 63695, "text": "A Branch with role Zonal Head Office supervises other Branches βˆ’ unary association, one–to-many" }, { "code": null, "e": 63887, "s": 63791, "text": "A Branch with role Zonal Head Office supervises other Branches βˆ’ unary association, one–to-many" }, { "code": null, "e": 63950, "s": 63887, "text": "A Branch β€œhas–a” number of accounts βˆ’ aggregation, one–to–many" }, { "code": null, "e": 64013, "s": 63950, "text": "A Branch β€œhas–a” number of accounts βˆ’ aggregation, one–to–many" }, { "code": null, "e": 64110, "s": 64013, "text": "From the class Account, two classes have inherited, namely, Savings Account and Current Account." }, { "code": null, "e": 64176, "s": 64110, "text": "A Customer can have one Current Account βˆ’ association, one–to–one" }, { "code": null, "e": 64242, "s": 64176, "text": "A Customer can have one Current Account βˆ’ association, one–to–one" }, { "code": null, "e": 64308, "s": 64242, "text": "A Customer can have one Savings Account βˆ’ association, one–to–one" }, { "code": null, "e": 64374, "s": 64308, "text": "A Customer can have one Savings Account βˆ’ association, one–to–one" }, { "code": null, "e": 64434, "s": 64374, "text": "A Branch β€œhas–a” number of Loans βˆ’ aggregation, one–to–many" }, { "code": null, "e": 64494, "s": 64434, "text": "A Branch β€œhas–a” number of Loans βˆ’ aggregation, one–to–many" }, { "code": null, "e": 64552, "s": 64494, "text": "A Customer can take many loans βˆ’ association, one–to–many" }, { "code": null, "e": 64610, "s": 64552, "text": "A Customer can take many loans βˆ’ association, one–to–many" }, { "code": null, "e": 64808, "s": 64610, "text": "An object diagram models a group of objects and their links at a point of time. It shows the instances of the things in a class diagram. Object diagram is the static part of an interaction diagram." }, { "code": null, "e": 64920, "s": 64808, "text": "Example βˆ’ The following figure shows an object diagram of a portion of the class diagram of the Banking System." }, { "code": null, "e": 65007, "s": 64920, "text": "Component diagrams show the organization and dependencies among a group of components." }, { "code": null, "e": 65040, "s": 65007, "text": "Component diagrams comprise of βˆ’" }, { "code": null, "e": 65051, "s": 65040, "text": "Components" }, { "code": null, "e": 65062, "s": 65051, "text": "Interfaces" }, { "code": null, "e": 65076, "s": 65062, "text": "Relationships" }, { "code": null, "e": 65111, "s": 65076, "text": "Packages and Subsystems (optional)" }, { "code": null, "e": 65145, "s": 65111, "text": "Component diagrams are used for βˆ’" }, { "code": null, "e": 65207, "s": 65145, "text": "constructing systems through forward and reverse engineering." }, { "code": null, "e": 65269, "s": 65207, "text": "constructing systems through forward and reverse engineering." }, { "code": null, "e": 65397, "s": 65269, "text": "modeling configuration management of source code files while developing a system using an object-oriented programming language." }, { "code": null, "e": 65525, "s": 65397, "text": "modeling configuration management of source code files while developing a system using an object-oriented programming language." }, { "code": null, "e": 65569, "s": 65525, "text": "representing schemas in modeling databases." }, { "code": null, "e": 65613, "s": 65569, "text": "representing schemas in modeling databases." }, { "code": null, "e": 65652, "s": 65613, "text": "modeling behaviors of dynamic systems." }, { "code": null, "e": 65691, "s": 65652, "text": "modeling behaviors of dynamic systems." }, { "code": null, "e": 65699, "s": 65691, "text": "Example" }, { "code": null, "e": 66118, "s": 65699, "text": "The following figure shows a component diagram to model a system’s source code that is developed using C++. It shows four source code files, namely, myheader.h, otherheader.h, priority.cpp, and other.cpp. Two versions of myheader.h are shown, tracing from the recent version to its ancestor. The file priority.cpp has compilation dependency on other.cpp. The file other.cpp has compilation dependency on otherheader.h." }, { "code": null, "e": 66332, "s": 66118, "text": "A deployment diagram puts emphasis on the configuration of runtime processing nodes and their components that live on them. They are commonly comprised of nodes and dependencies, or associations between the nodes." }, { "code": null, "e": 66366, "s": 66332, "text": "Deployment diagrams are used to βˆ’" }, { "code": null, "e": 66470, "s": 66366, "text": "model devices in embedded systems that typically comprise of software-intensive collection of hardware." }, { "code": null, "e": 66574, "s": 66470, "text": "model devices in embedded systems that typically comprise of software-intensive collection of hardware." }, { "code": null, "e": 66625, "s": 66574, "text": "represent the topologies of client/server systems." }, { "code": null, "e": 66676, "s": 66625, "text": "represent the topologies of client/server systems." }, { "code": null, "e": 66709, "s": 66676, "text": "model fully distributed systems." }, { "code": null, "e": 66742, "s": 66709, "text": "model fully distributed systems." }, { "code": null, "e": 66750, "s": 66742, "text": "Example" }, { "code": null, "e": 67235, "s": 66750, "text": "The following figure shows the topology of a computer system that follows client/server architecture. The figure illustrates a node stereotyped as server that comprises of processors. The figure indicates that four or more servers are deployed at the system. Connected to the server are the client nodes, where each node represents a terminal device such as workstation, laptop, scanner, or printer. The nodes are represented using icons that clearly depict the real-world equivalent." }, { "code": null, "e": 67474, "s": 67235, "text": "UML behavioral diagrams visualize, specify, construct, and document the dynamic aspects of a system. The behavioral diagrams are categorized as follows: use case diagrams, interaction diagrams, state–chart diagrams, and activity diagrams." }, { "code": null, "e": 67719, "s": 67474, "text": "A use case describes the sequence of actions a system performs yielding visible results. It shows the interaction of things outside the system with the system itself. Use cases may be applied to the whole system as well as a part of the system." }, { "code": null, "e": 67911, "s": 67719, "text": "An actor represents the roles that the users of the use cases play. An actor may be a person (e.g. student, customer), a device (e.g. workstation), or another system (e.g. bank, institution)." }, { "code": null, "e": 68029, "s": 67911, "text": "The following figure shows the notations of an actor named Student and a use case called Generate Performance Report." }, { "code": null, "e": 68158, "s": 68029, "text": "Use case diagrams present an outside view of the manner the elements in a system behave and how they can be used in the context." }, { "code": null, "e": 68190, "s": 68158, "text": "Use case diagrams comprise of βˆ’" }, { "code": null, "e": 68200, "s": 68190, "text": "Use cases" }, { "code": null, "e": 68207, "s": 68200, "text": "Actors" }, { "code": null, "e": 68270, "s": 68207, "text": "Relationships like dependency, generalization, and association" }, { "code": null, "e": 68299, "s": 68270, "text": "Use case diagrams are used βˆ’" }, { "code": null, "e": 68465, "s": 68299, "text": "To model the context of a system by enclosing all the activities of a system within a rectangle and focusing on the actors outside the system by interacting with it." }, { "code": null, "e": 68631, "s": 68465, "text": "To model the context of a system by enclosing all the activities of a system within a rectangle and focusing on the actors outside the system by interacting with it." }, { "code": null, "e": 68701, "s": 68631, "text": "To model the requirements of a system from the outside point of view." }, { "code": null, "e": 68771, "s": 68701, "text": "To model the requirements of a system from the outside point of view." }, { "code": null, "e": 68779, "s": 68771, "text": "Example" }, { "code": null, "e": 68879, "s": 68779, "text": "Let us consider an Automated Trading House System. We assume the following features of the system βˆ’" }, { "code": null, "e": 68989, "s": 68879, "text": "The trading house has transactions with two types of customers, individual customers and corporate customers." }, { "code": null, "e": 69099, "s": 68989, "text": "The trading house has transactions with two types of customers, individual customers and corporate customers." }, { "code": null, "e": 69210, "s": 69099, "text": "Once the customer places an order, it is processed by the sales department and the customer is given the bill." }, { "code": null, "e": 69321, "s": 69210, "text": "Once the customer places an order, it is processed by the sales department and the customer is given the bill." }, { "code": null, "e": 69426, "s": 69321, "text": "The system allows the manager to manage customer accounts and answer any queries posted by the customer." }, { "code": null, "e": 69531, "s": 69426, "text": "The system allows the manager to manage customer accounts and answer any queries posted by the customer." }, { "code": null, "e": 69706, "s": 69531, "text": "Interaction diagrams depict interactions of objects and their relationships. They also include the messages passed between them. There are two types of interaction diagrams βˆ’" }, { "code": null, "e": 69724, "s": 69706, "text": "Sequence Diagrams" }, { "code": null, "e": 69747, "s": 69724, "text": "Collaboration Diagrams" }, { "code": null, "e": 69806, "s": 69747, "text": "the control flow by time ordering using sequence diagrams." }, { "code": null, "e": 69865, "s": 69806, "text": "the control flow by time ordering using sequence diagrams." }, { "code": null, "e": 69928, "s": 69865, "text": "the control flow of organization using collaboration diagrams." }, { "code": null, "e": 69991, "s": 69928, "text": "the control flow of organization using collaboration diagrams." }, { "code": null, "e": 70094, "s": 69991, "text": "Sequence diagrams are interaction diagrams that illustrate the ordering of messages according to time." }, { "code": null, "e": 70362, "s": 70094, "text": "Notations βˆ’ These diagrams are in the form of two-dimensional charts. The objects that initiate the interaction are placed on the x–axis. The messages that these objects send and receive are placed along the y–axis, in the order of increasing time from top to bottom." }, { "code": null, "e": 70464, "s": 70362, "text": "Example βˆ’ A sequence diagram for the Automated Trading House System is shown in the following figure." }, { "code": null, "e": 70589, "s": 70464, "text": "Collaboration diagrams are interaction diagrams that illustrate the structure of the objects that send and receive messages." }, { "code": null, "e": 70809, "s": 70589, "text": "Notations βˆ’ In these diagrams, the objects that participate in the interaction are shown using vertices. The links that connect the objects are used to send and receive messages. The message is shown as a labeled arrow." }, { "code": null, "e": 70916, "s": 70809, "text": "Example βˆ’ Collaboration diagram for the Automated Trading House System is illustrated in the figure below." }, { "code": null, "e": 71150, "s": 70916, "text": "A state–chart diagram shows a state machine that depicts the control flow of an object from one state to another. A state machine portrays the sequences of states which an object undergoes due to events and their responses to events." }, { "code": null, "e": 71185, "s": 71150, "text": "State–Chart Diagrams comprise of βˆ’" }, { "code": null, "e": 71213, "s": 71185, "text": "States: Simple or Composite" }, { "code": null, "e": 71240, "s": 71213, "text": "Transitions between states" }, { "code": null, "e": 71267, "s": 71240, "text": "Events causing transitions" }, { "code": null, "e": 71293, "s": 71267, "text": "Actions due to the events" }, { "code": null, "e": 71374, "s": 71293, "text": "State-chart diagrams are used for modeling objects which are reactive in nature." }, { "code": null, "e": 71382, "s": 71374, "text": "Example" }, { "code": null, "e": 71543, "s": 71382, "text": "In the Automated Trading House System, let us model Order as an object and trace its sequence. The following figure shows the corresponding state–chart diagram." }, { "code": null, "e": 71712, "s": 71543, "text": "An activity diagram depicts the flow of activities which are ongoing non-atomic operations in a state machine. Activities result in actions which are atomic operations." }, { "code": null, "e": 71744, "s": 71712, "text": "Activity diagrams comprise of βˆ’" }, { "code": null, "e": 71778, "s": 71744, "text": "Activity states and action states" }, { "code": null, "e": 71790, "s": 71778, "text": "Transitions" }, { "code": null, "e": 71798, "s": 71790, "text": "Objects" }, { "code": null, "e": 71840, "s": 71798, "text": "Activity diagrams are used for modeling βˆ’" }, { "code": null, "e": 71900, "s": 71840, "text": "workflows as viewed by actors, interacting with the system." }, { "code": null, "e": 71956, "s": 71900, "text": "details of operations or computations using flowcharts." }, { "code": null, "e": 71964, "s": 71956, "text": "Example" }, { "code": null, "e": 72063, "s": 71964, "text": "The following figure shows an activity diagram of a portion of the Automated Trading House System." }, { "code": null, "e": 72523, "s": 72063, "text": "After the analysis phase, the conceptual model is developed further into an object-oriented model using object-oriented design (OOD). In OOD, the technology-independent concepts in the analysis model are mapped onto implementing classes, constraints are identified, and interfaces are designed, resulting in a model for the solution domain. In a nutshell, a detailed description is constructed specifying how the system is to be built on concrete technologies" }, { "code": null, "e": 72584, "s": 72523, "text": "The stages for object–oriented design can be identified as βˆ’" }, { "code": null, "e": 72624, "s": 72584, "text": "Definition of the context of the system" }, { "code": null, "e": 72654, "s": 72624, "text": "Designing system architecture" }, { "code": null, "e": 72698, "s": 72654, "text": "Identification of the objects in the system" }, { "code": null, "e": 72728, "s": 72698, "text": "Construction of design models" }, { "code": null, "e": 72763, "s": 72728, "text": "Specification of object interfaces" }, { "code": null, "e": 72889, "s": 72763, "text": "Object-oriented system design involves defining the context of a system followed by designing the architecture of the system." }, { "code": null, "e": 73269, "s": 72889, "text": "Context βˆ’ The context of a system has a static and a dynamic part. The static context of the system is designed using a simple block diagram of the whole system which is expanded into a hierarchy of subsystems. The subsystem model is represented by UML packages. The dynamic context describes how the system interacts with its environment. It is modelled using use case diagrams." }, { "code": null, "e": 73649, "s": 73269, "text": "Context βˆ’ The context of a system has a static and a dynamic part. The static context of the system is designed using a simple block diagram of the whole system which is expanded into a hierarchy of subsystems. The subsystem model is represented by UML packages. The dynamic context describes how the system interacts with its environment. It is modelled using use case diagrams." }, { "code": null, "e": 73936, "s": 73649, "text": "System Architecture βˆ’ The system architecture is designed on the basis of the context of the system in accordance with the principles of architectural design as well as domain knowledge. Typically, a system is partitioned into layers and each layer is decomposed to form the subsystems." }, { "code": null, "e": 74223, "s": 73936, "text": "System Architecture βˆ’ The system architecture is designed on the basis of the context of the system in accordance with the principles of architectural design as well as domain knowledge. Typically, a system is partitioned into layers and each layer is decomposed to form the subsystems." }, { "code": null, "e": 74565, "s": 74223, "text": "Decomposition means dividing a large complex system into a hierarchy of smaller components with lesser complexities, on the principles of divide–and–conquer. Each major component of the system is called a subsystem. Object-oriented decomposition identifies individual autonomous objects in a system and the communication among these objects." }, { "code": null, "e": 74603, "s": 74565, "text": "The advantages of decomposition are βˆ’" }, { "code": null, "e": 74698, "s": 74603, "text": "The individual components are of lesser complexity, and so more understandable and manageable." }, { "code": null, "e": 74793, "s": 74698, "text": "The individual components are of lesser complexity, and so more understandable and manageable." }, { "code": null, "e": 74853, "s": 74793, "text": "It enables division of workforce having specialized skills." }, { "code": null, "e": 74913, "s": 74853, "text": "It enables division of workforce having specialized skills." }, { "code": null, "e": 74997, "s": 74913, "text": "It allows subsystems to be replaced or modified without affecting other subsystems." }, { "code": null, "e": 75081, "s": 74997, "text": "It allows subsystems to be replaced or modified without affecting other subsystems." }, { "code": null, "e": 75279, "s": 75081, "text": "Concurrency allows more than one objects to receive events at the same time and more than one activity to be executed simultaneously. Concurrency is identified and represented in the dynamic model." }, { "code": null, "e": 75596, "s": 75279, "text": "To enable concurrency, each concurrent element is assigned a separate thread of control. If the concurrency is at object level, then two concurrent objects are assigned two different threads of control. If two operations of a single object are concurrent in nature, then that object is split among different threads." }, { "code": null, "e": 75876, "s": 75596, "text": "Concurrency is associated with the problems of data integrity, deadlock, and starvation. So a clear strategy needs to be made whenever concurrency is required. Besides, concurrency requires to be identified at the design stage itself, and cannot be left for implementation stage." }, { "code": null, "e": 76153, "s": 75876, "text": "While designing applications, some commonly accepted solutions are adopted for some categories of problems. These are the patterns of design. A pattern can be defined as a documented set of building blocks that can be used in certain types of application development problems." }, { "code": null, "e": 76194, "s": 76153, "text": "Some commonly used design patterns are βˆ’" }, { "code": null, "e": 76210, "s": 76194, "text": "FacΜ§ade pattern" }, { "code": null, "e": 76240, "s": 76210, "text": "Model view separation pattern" }, { "code": null, "e": 76257, "s": 76240, "text": "Observer pattern" }, { "code": null, "e": 76287, "s": 76257, "text": "Model view controller pattern" }, { "code": null, "e": 76313, "s": 76287, "text": "Publish subscribe pattern" }, { "code": null, "e": 76327, "s": 76313, "text": "Proxy pattern" }, { "code": null, "e": 76456, "s": 76327, "text": "During system design, the events that may occur in the objects of the system need to be identified and appropriately dealt with." }, { "code": null, "e": 76551, "s": 76456, "text": "An event is a specification of a significant occurrence that has a location in time and space." }, { "code": null, "e": 76613, "s": 76551, "text": "There are four types of events that can be modelled, namely βˆ’" }, { "code": null, "e": 76694, "s": 76613, "text": "Signal Event βˆ’ A named object thrown by one object and caught by another object." }, { "code": null, "e": 76775, "s": 76694, "text": "Signal Event βˆ’ A named object thrown by one object and caught by another object." }, { "code": null, "e": 76847, "s": 76775, "text": "Call Event βˆ’ A synchronous event representing dispatch of an operation." }, { "code": null, "e": 76919, "s": 76847, "text": "Call Event βˆ’ A synchronous event representing dispatch of an operation." }, { "code": null, "e": 76971, "s": 76919, "text": "Time Event βˆ’ An event representing passage of time." }, { "code": null, "e": 77023, "s": 76971, "text": "Time Event βˆ’ An event representing passage of time." }, { "code": null, "e": 77077, "s": 77023, "text": "Change Event βˆ’ An event representing change in state." }, { "code": null, "e": 77131, "s": 77077, "text": "Change Event βˆ’ An event representing change in state." }, { "code": null, "e": 77322, "s": 77131, "text": "The system design phase needs to address the initialization and the termination of the system as a whole as well as each subsystem. The different aspects that are documented are as follows βˆ’" }, { "code": null, "e": 77429, "s": 77322, "text": "The start–up of the system, i.e., the transition of the system from non-initialized state to steady state." }, { "code": null, "e": 77536, "s": 77429, "text": "The start–up of the system, i.e., the transition of the system from non-initialized state to steady state." }, { "code": null, "e": 77664, "s": 77536, "text": "The termination of the system, i.e., the closing of all running threads, cleaning up of resources, and the messages to be sent." }, { "code": null, "e": 77792, "s": 77664, "text": "The termination of the system, i.e., the closing of all running threads, cleaning up of resources, and the messages to be sent." }, { "code": null, "e": 77883, "s": 77792, "text": "The initial configuration of the system and the reconfiguration of the system when needed." }, { "code": null, "e": 77974, "s": 77883, "text": "The initial configuration of the system and the reconfiguration of the system when needed." }, { "code": null, "e": 78034, "s": 77974, "text": "Foreseeing failures or undesired termination of the system." }, { "code": null, "e": 78094, "s": 78034, "text": "Foreseeing failures or undesired termination of the system." }, { "code": null, "e": 78153, "s": 78094, "text": "Boundary conditions are modelled using boundary use cases." }, { "code": null, "e": 78587, "s": 78153, "text": "After the hierarchy of subsystems has been developed, the objects in the system are identified and their details are designed. Here, the designer details out the strategy chosen during the system design. The emphasis shifts from application domain concepts toward computer concepts. The objects identified during analysis are etched out for implementation with an aim to minimize execution time, memory consumption, and overall cost." }, { "code": null, "e": 78633, "s": 78587, "text": "Object design includes the following phases βˆ’" }, { "code": null, "e": 78655, "s": 78633, "text": "Object identification" }, { "code": null, "e": 78714, "s": 78655, "text": "Object representation, i.e., construction of design models" }, { "code": null, "e": 78743, "s": 78714, "text": "Classification of operations" }, { "code": null, "e": 78760, "s": 78743, "text": "Algorithm design" }, { "code": null, "e": 78784, "s": 78760, "text": "Design of relationships" }, { "code": null, "e": 78836, "s": 78784, "text": "Implementation of control for external interactions" }, { "code": null, "e": 78882, "s": 78836, "text": "Package classes and associations into modules" }, { "code": null, "e": 79092, "s": 78882, "text": "The first step of object design is object identification. The objects identified in the object–oriented analysis phases are grouped into classes and refined so that they are suitable for actual implementation." }, { "code": null, "e": 79126, "s": 79092, "text": "The functions of this stage are βˆ’" }, { "code": null, "e": 79192, "s": 79126, "text": "Identifying and refining the classes in each subsystem or package" }, { "code": null, "e": 79258, "s": 79192, "text": "Identifying and refining the classes in each subsystem or package" }, { "code": null, "e": 79314, "s": 79258, "text": "Defining the links and associations between the classes" }, { "code": null, "e": 79370, "s": 79314, "text": "Defining the links and associations between the classes" }, { "code": null, "e": 79486, "s": 79370, "text": "Designing the hierarchical associations among the classes, i.e., the generalization/specialization and inheritances" }, { "code": null, "e": 79602, "s": 79486, "text": "Designing the hierarchical associations among the classes, i.e., the generalization/specialization and inheritances" }, { "code": null, "e": 79625, "s": 79602, "text": "Designing aggregations" }, { "code": null, "e": 79648, "s": 79625, "text": "Designing aggregations" }, { "code": null, "e": 79803, "s": 79648, "text": "Once the classes are identified, they need to be represented using object modelling techniques. This stage essentially involves constructing UML diagrams." }, { "code": null, "e": 79867, "s": 79803, "text": "There are two types of design models that need to be produced βˆ’" }, { "code": null, "e": 79970, "s": 79867, "text": "Static Models βˆ’ To describe the static structure of a system using class diagrams and object diagrams." }, { "code": null, "e": 80073, "s": 79970, "text": "Static Models βˆ’ To describe the static structure of a system using class diagrams and object diagrams." }, { "code": null, "e": 80230, "s": 80073, "text": "Dynamic Models βˆ’ To describe the dynamic structure of a system and show the interaction between classes using interaction diagrams and state–chart diagrams." }, { "code": null, "e": 80387, "s": 80230, "text": "Dynamic Models βˆ’ To describe the dynamic structure of a system and show the interaction between classes using interaction diagrams and state–chart diagrams." }, { "code": null, "e": 80644, "s": 80387, "text": "In this step, the operation to be performed on objects are defined by combining the three models developed in the OOA phase, namely, object model, dynamic model, and functional model. An operation specifies what is to be done and not how it should be done." }, { "code": null, "e": 80701, "s": 80644, "text": "The following tasks are performed regarding operations βˆ’" }, { "code": null, "e": 80773, "s": 80701, "text": "The state transition diagram of each object in the system is developed." }, { "code": null, "e": 80845, "s": 80773, "text": "The state transition diagram of each object in the system is developed." }, { "code": null, "e": 80908, "s": 80845, "text": "Operations are defined for the events received by the objects." }, { "code": null, "e": 80971, "s": 80908, "text": "Operations are defined for the events received by the objects." }, { "code": null, "e": 81063, "s": 80971, "text": "Cases in which one event triggers other events in same or different objects are identified." }, { "code": null, "e": 81155, "s": 81063, "text": "Cases in which one event triggers other events in same or different objects are identified." }, { "code": null, "e": 81209, "s": 81155, "text": "The sub–operations within the actions are identified." }, { "code": null, "e": 81263, "s": 81209, "text": "The sub–operations within the actions are identified." }, { "code": null, "e": 81316, "s": 81263, "text": "The main actions are expanded to data flow diagrams." }, { "code": null, "e": 81369, "s": 81316, "text": "The main actions are expanded to data flow diagrams." }, { "code": null, "e": 81559, "s": 81369, "text": "The operations in the objects are defined using algorithms. An algorithm is a stepwise procedure that solves the problem laid down in an operation. Algorithms focus on how it is to be done." }, { "code": null, "e": 81797, "s": 81559, "text": "There may be more than one algorithm corresponding to a given operation. Once the alternative algorithms are identified, the optimal algorithm is selected for the given problem domain. The metrics for choosing the optimal algorithm are βˆ’" }, { "code": null, "e": 81931, "s": 81797, "text": "Computational Complexity βˆ’ Complexity determines the efficiency of an algorithm in terms of computation time and memory requirements." }, { "code": null, "e": 82065, "s": 81931, "text": "Computational Complexity βˆ’ Complexity determines the efficiency of an algorithm in terms of computation time and memory requirements." }, { "code": null, "e": 82217, "s": 82065, "text": "Flexibility βˆ’ Flexibility determines whether the chosen algorithm can be implemented suitably, without loss of appropriateness in various environments." }, { "code": null, "e": 82369, "s": 82217, "text": "Flexibility βˆ’ Flexibility determines whether the chosen algorithm can be implemented suitably, without loss of appropriateness in various environments." }, { "code": null, "e": 82471, "s": 82369, "text": "Understandability βˆ’ This determines whether the chosen algorithm is easy to understand and implement." }, { "code": null, "e": 82573, "s": 82471, "text": "Understandability βˆ’ This determines whether the chosen algorithm is easy to understand and implement." }, { "code": null, "e": 82773, "s": 82573, "text": "The strategy to implement the relationships needs to be chalked out during the object design phase. The main relationships that are addressed comprise of associations, aggregations, and inheritances." }, { "code": null, "e": 82835, "s": 82773, "text": "The designer should do the following regarding associations βˆ’" }, { "code": null, "e": 82903, "s": 82835, "text": "Identify whether an association is unidirectional or bidirectional." }, { "code": null, "e": 82971, "s": 82903, "text": "Identify whether an association is unidirectional or bidirectional." }, { "code": null, "e": 83034, "s": 82971, "text": "Analyze the path of associations and update them if necessary." }, { "code": null, "e": 83097, "s": 83034, "text": "Analyze the path of associations and update them if necessary." }, { "code": null, "e": 83266, "s": 83097, "text": "Implement the associations as a distinct object, in case of many–to-many relationships; or as a link to other object in case of one–to-one or one–to-many relationships." }, { "code": null, "e": 83435, "s": 83266, "text": "Implement the associations as a distinct object, in case of many–to-many relationships; or as a link to other object in case of one–to-one or one–to-many relationships." }, { "code": null, "e": 83498, "s": 83435, "text": "Regarding inheritances, the designer should do the following βˆ’" }, { "code": null, "e": 83541, "s": 83498, "text": "Adjust the classes and their associations." }, { "code": null, "e": 83584, "s": 83541, "text": "Adjust the classes and their associations." }, { "code": null, "e": 83611, "s": 83584, "text": "Identify abstract classes." }, { "code": null, "e": 83638, "s": 83611, "text": "Identify abstract classes." }, { "code": null, "e": 83696, "s": 83638, "text": "Make provisions so that behaviors are shared when needed." }, { "code": null, "e": 83754, "s": 83696, "text": "Make provisions so that behaviors are shared when needed." }, { "code": null, "e": 84009, "s": 83754, "text": "The object designer may incorporate refinements in the strategy of the state–chart model. In system design, a basic strategy for realizing the dynamic model is made. During object design, this strategy is aptly embellished for appropriate implementation." }, { "code": null, "e": 84070, "s": 84009, "text": "The approaches for implementation of the dynamic model are βˆ’" }, { "code": null, "e": 84468, "s": 84070, "text": "Represent State as a Location within a Program βˆ’ This is the traditional procedure-driven approach whereby the location of control defines the program state. A finite state machine can be implemented as a program. A transition forms an input statement, the main control path forms the sequence of instructions, the branches form the conditions, and the backward paths form the loops or iterations." }, { "code": null, "e": 84866, "s": 84468, "text": "Represent State as a Location within a Program βˆ’ This is the traditional procedure-driven approach whereby the location of control defines the program state. A finite state machine can be implemented as a program. A transition forms an input statement, the main control path forms the sequence of instructions, the branches form the conditions, and the backward paths form the loops or iterations." }, { "code": null, "e": 85085, "s": 84866, "text": "State Machine Engine βˆ’ This approach directly represents a state machine through a state machine engine class. This class executes the state machine through a set of transitions and actions provided by the application." }, { "code": null, "e": 85304, "s": 85085, "text": "State Machine Engine βˆ’ This approach directly represents a state machine through a state machine engine class. This class executes the state machine through a set of transitions and actions provided by the application." }, { "code": null, "e": 85544, "s": 85304, "text": "Control as Concurrent Tasks βˆ’ In this approach, an object is implemented as a task in the programming language or the operating system. Here, an event is implemented as an inter-task call. It preserves inherent concurrency of real objects." }, { "code": null, "e": 85784, "s": 85544, "text": "Control as Concurrent Tasks βˆ’ In this approach, an object is implemented as a task in the programming language or the operating system. Here, an event is implemented as an inter-task call. It preserves inherent concurrency of real objects." }, { "code": null, "e": 86020, "s": 85784, "text": "In any large project, meticulous partitioning of an implementation into modules or packages is important. During object design, classes and objects are grouped into packages to enable multiple groups to work cooperatively on a project." }, { "code": null, "e": 86061, "s": 86020, "text": "The different aspects of packaging are βˆ’" }, { "code": null, "e": 86263, "s": 86061, "text": "Hiding Internal Information from Outside View βˆ’ It allows a class to be viewed as a β€œblack box” and permits class implementation to be changed without requiring any clients of the class to modify code." }, { "code": null, "e": 86465, "s": 86263, "text": "Hiding Internal Information from Outside View βˆ’ It allows a class to be viewed as a β€œblack box” and permits class implementation to be changed without requiring any clients of the class to modify code." }, { "code": null, "e": 86675, "s": 86465, "text": "Coherence of Elements βˆ’ An element, such as a class, an operation, or a module, is coherent if it is organized on a consistent plan and all its parts are intrinsically related so that they serve a common goal." }, { "code": null, "e": 86885, "s": 86675, "text": "Coherence of Elements βˆ’ An element, such as a class, an operation, or a module, is coherent if it is organized on a consistent plan and all its parts are intrinsically related so that they serve a common goal." }, { "code": null, "e": 87427, "s": 86885, "text": "Construction of Physical Modules βˆ’ The following guidelines help while constructing physical modules βˆ’\n\nClasses in a module should represent similar things or components in the same composite object.\nClosely connected classes should be in the same module.\nUnconnected or weakly connected classes should be placed in separate modules.\nModules should have good cohesion, i.e., high cooperation among its components.\nA module should have low coupling with other modules, i.e., interaction or interdependence between modules should be minimum.\n\n" }, { "code": null, "e": 87530, "s": 87427, "text": "Construction of Physical Modules βˆ’ The following guidelines help while constructing physical modules βˆ’" }, { "code": null, "e": 87626, "s": 87530, "text": "Classes in a module should represent similar things or components in the same composite object." }, { "code": null, "e": 87722, "s": 87626, "text": "Classes in a module should represent similar things or components in the same composite object." }, { "code": null, "e": 87778, "s": 87722, "text": "Closely connected classes should be in the same module." }, { "code": null, "e": 87834, "s": 87778, "text": "Closely connected classes should be in the same module." }, { "code": null, "e": 87912, "s": 87834, "text": "Unconnected or weakly connected classes should be placed in separate modules." }, { "code": null, "e": 87990, "s": 87912, "text": "Unconnected or weakly connected classes should be placed in separate modules." }, { "code": null, "e": 88070, "s": 87990, "text": "Modules should have good cohesion, i.e., high cooperation among its components." }, { "code": null, "e": 88150, "s": 88070, "text": "Modules should have good cohesion, i.e., high cooperation among its components." }, { "code": null, "e": 88276, "s": 88150, "text": "A module should have low coupling with other modules, i.e., interaction or interdependence between modules should be minimum." }, { "code": null, "e": 88402, "s": 88276, "text": "A module should have low coupling with other modules, i.e., interaction or interdependence between modules should be minimum." }, { "code": null, "e": 88745, "s": 88402, "text": "The analysis model captures the logical information about the system, while the design model adds details to support efficient information access. Before a design is implemented, it should be optimized so as to make the implementation more efficient. The aim of optimization is to minimize the cost in terms of time, space, and other metrics." }, { "code": null, "e": 89043, "s": 88745, "text": "However, design optimization should not be excess, as ease of implementation, maintainability, and extensibility are also important concerns. It is often seen that a perfectly optimized design is more efficient but less readable and reusable. So the designer must strike a balance between the two." }, { "code": null, "e": 89109, "s": 89043, "text": "The various things that may be done for design optimization are βˆ’" }, { "code": null, "e": 89136, "s": 89109, "text": "Add redundant associations" }, { "code": null, "e": 89165, "s": 89136, "text": "Omit non-usable associations" }, { "code": null, "e": 89192, "s": 89165, "text": "Optimization of algorithms" }, { "code": null, "e": 89263, "s": 89192, "text": "Save derived attributes to avoid re-computation of complex expressions" }, { "code": null, "e": 89479, "s": 89263, "text": "During design optimization, it is checked if deriving new associations can reduce access costs. Though these redundant associations may not add any information, they may increase the efficiency of the overall model." }, { "code": null, "e": 89669, "s": 89479, "text": "Presence of too many associations may render a system indecipherable and hence reduce the overall efficiency of the system. So, during optimization, all non-usable associations are removed." }, { "code": null, "e": 89870, "s": 89669, "text": "In object-oriented systems, optimization of data structure and algorithms are done in a collaborative manner. Once the class design is in place, the operations and the algorithms need to be optimized." }, { "code": null, "e": 89914, "s": 89870, "text": "Optimization of algorithms is obtained by βˆ’" }, { "code": null, "e": 89964, "s": 89914, "text": "Rearrangement of the order of computational tasks" }, { "code": null, "e": 90045, "s": 89964, "text": "Reversal of execution order of loops from that laid down in the functional model" }, { "code": null, "e": 90088, "s": 90045, "text": "Removal of dead paths within the algorithm" }, { "code": null, "e": 90394, "s": 90088, "text": "Derived attributes are those attributes whose values are computed as a function of other attributes (base attributes). Re-computation of the values of derived attributes every time they are needed is a time–consuming procedure. To avoid this, the values can be computed and stored in their computed forms." }, { "code": null, "e": 90600, "s": 90394, "text": "However, this may pose update anomalies, i.e., a change in the values of base attributes with no corresponding change in the values of the derived attributes. To avoid this, the following steps are taken βˆ’" }, { "code": null, "e": 90689, "s": 90600, "text": "With each update of the base attribute value, the derived attribute is also re-computed." }, { "code": null, "e": 90778, "s": 90689, "text": "With each update of the base attribute value, the derived attribute is also re-computed." }, { "code": null, "e": 90888, "s": 90778, "text": "All the derived attributes are re-computed and updated periodically in a group rather than after each update." }, { "code": null, "e": 90998, "s": 90888, "text": "All the derived attributes are re-computed and updated periodically in a group rather than after each update." }, { "code": null, "e": 91238, "s": 90998, "text": "Documentation is an essential part of any software development process that records the procedure of making the software. The design decisions need to be documented for any non–trivial software system for transmitting the design to others." }, { "code": null, "e": 91343, "s": 91238, "text": "Though a secondary product, a good documentation is indispensable, particularly in the following areas βˆ’" }, { "code": null, "e": 91415, "s": 91343, "text": "In designing software that is being developed by a number of developers" }, { "code": null, "e": 91460, "s": 91415, "text": "In iterative software development strategies" }, { "code": null, "e": 91516, "s": 91460, "text": "In developing subsequent versions of a software project" }, { "code": null, "e": 91542, "s": 91516, "text": "For evaluating a software" }, { "code": null, "e": 91586, "s": 91542, "text": "For finding conditions and areas of testing" }, { "code": null, "e": 91619, "s": 91586, "text": "For maintenance of the software." }, { "code": null, "e": 91698, "s": 91619, "text": "A beneficial documentation should essentially include the following contents βˆ’" }, { "code": null, "e": 91768, "s": 91698, "text": "High–level system architecture βˆ’ Process diagrams and module diagrams" }, { "code": null, "e": 91838, "s": 91768, "text": "High–level system architecture βˆ’ Process diagrams and module diagrams" }, { "code": null, "e": 91908, "s": 91838, "text": "Key abstractions and mechanisms βˆ’ Class diagrams and object diagrams." }, { "code": null, "e": 91978, "s": 91908, "text": "Key abstractions and mechanisms βˆ’ Class diagrams and object diagrams." }, { "code": null, "e": 92060, "s": 91978, "text": "Scenarios that illustrate the behavior of the main aspects βˆ’ Behavioural diagrams" }, { "code": null, "e": 92142, "s": 92060, "text": "Scenarios that illustrate the behavior of the main aspects βˆ’ Behavioural diagrams" }, { "code": null, "e": 92185, "s": 92142, "text": "The features of a good documentation are βˆ’" }, { "code": null, "e": 92253, "s": 92185, "text": "Concise and at the same time, unambiguous, consistent, and complete" }, { "code": null, "e": 92321, "s": 92253, "text": "Concise and at the same time, unambiguous, consistent, and complete" }, { "code": null, "e": 92374, "s": 92321, "text": "Traceable to the system’s requirement specifications" }, { "code": null, "e": 92427, "s": 92374, "text": "Traceable to the system’s requirement specifications" }, { "code": null, "e": 92443, "s": 92427, "text": "Well-structured" }, { "code": null, "e": 92459, "s": 92443, "text": "Well-structured" }, { "code": null, "e": 92495, "s": 92459, "text": "Diagrammatic instead of descriptive" }, { "code": null, "e": 92531, "s": 92495, "text": "Diagrammatic instead of descriptive" }, { "code": null, "e": 92723, "s": 92531, "text": "Implementing an object-oriented design generally involves using a standard object oriented programming language (OOPL) or mapping object designs to databases. In most cases, it involves both." }, { "code": null, "e": 92995, "s": 92723, "text": "Usually, the task of transforming an object design into code is a straightforward process. Any object-oriented programming language like C++, Java, Smalltalk, C# and Python, includes provision for representing classes. In this chapter, we exemplify the concept using C++." }, { "code": null, "e": 93072, "s": 92995, "text": "The following figure shows the representation of the class Circle using C++." }, { "code": null, "e": 93230, "s": 93072, "text": "Most programming languages do not provide constructs to implement associations directly. So the task of implementing associations needs considerable thought." }, { "code": null, "e": 93372, "s": 93230, "text": "Associations may be either unidirectional or bidirectional. Besides, each association may be either one–to–one, one–to–many, or many–to–many." }, { "code": null, "e": 93544, "s": 93372, "text": "For implementing unidirectional associations, care should be taken so that unidirectionality is maintained. The implementations for different multiplicity are as follows βˆ’" }, { "code": null, "e": 93777, "s": 93544, "text": "Optional Associations βˆ’ Here, a link may or may not exist between the participating objects. For example, in the association between Customer and Current Account in the figure below, a customer may or may not have a current account." }, { "code": null, "e": 94010, "s": 93777, "text": "Optional Associations βˆ’ Here, a link may or may not exist between the participating objects. For example, in the association between Customer and Current Account in the figure below, a customer may or may not have a current account." }, { "code": null, "e": 94144, "s": 94010, "text": "For implementation, an object of Current Account is included as an attribute in Customer that may be NULL. Implementation using C++ βˆ’" }, { "code": null, "e": 94507, "s": 94144, "text": "class Customer {\n private:\n // attributes\n Current_Account c; //an object of Current_Account as attribute\n \n public: \n\n Customer() {\n c = NULL; \n } // assign c as NULL\n\n Current_Account getCurrAc() {\n return c;\n }\n \n void setCurrAc( Current_Account myacc) {\n c = myacc;\n }\n\n void removeAcc() { \n c = NULL;\n } \n};" }, { "code": null, "e": 94717, "s": 94507, "text": "One–to–one Associations βˆ’ Here, one instance of a class is related to exactly one instance of the associated class. For example, Department and Manager have one–to–one association as shown in the figure below." }, { "code": null, "e": 94927, "s": 94717, "text": "One–to–one Associations βˆ’ Here, one instance of a class is related to exactly one instance of the associated class. For example, Department and Manager have one–to–one association as shown in the figure below." }, { "code": null, "e": 95048, "s": 94927, "text": "This is implemented by including in Department, an object of Manager that should not be NULL. Implementation using C++ βˆ’" }, { "code": null, "e": 95346, "s": 95048, "text": "class Department {\n private:\n // attributes\n Manager mgr; //an object of Manager as attribute\n \n public: \n Department (/*parameters*/, Manager m) { //m is not NULL \n // assign parameters to variables\n mgr = m;\n } \n\n Manager getMgr() { \n return mgr; \n } \n};" }, { "code": null, "e": 95560, "s": 95346, "text": "One–to–many Associations βˆ’ Here, one instance of a class is related to more than one instances of the associated class. For example, consider the association between Employee and Dependent in the following figure." }, { "code": null, "e": 95774, "s": 95560, "text": "One–to–many Associations βˆ’ Here, one instance of a class is related to more than one instances of the associated class. For example, consider the association between Employee and Dependent in the following figure." }, { "code": null, "e": 95893, "s": 95774, "text": "This is implemented by including a list of Dependents in class Employee. Implementation using C++ STL list container βˆ’" }, { "code": null, "e": 96308, "s": 95893, "text": "class Employee {\n private:\n char * deptName;\n list <Dependent> dep; //a list of Dependents as attribute\n\n public: \n void addDependent ( Dependent d) { \n dep.push_back(d); \n } // adds an employee to the department\n\n void removeDeoendent( Dependent d) { \n int index = find ( d, dep );\n // find() function returns the index of d in list dep\n dep.erase(index);\n } \n};" }, { "code": null, "e": 96400, "s": 96308, "text": "To implement bi-directional association, links in both directions require to be maintained." }, { "code": null, "e": 96574, "s": 96400, "text": "Optional or one–to–one Associations βˆ’ Consider the relationship between Project and Project Manager having one–to–one bidirectional association as shown in the figure below." }, { "code": null, "e": 96748, "s": 96574, "text": "Optional or one–to–one Associations βˆ’ Consider the relationship between Project and Project Manager having one–to–one bidirectional association as shown in the figure below." }, { "code": null, "e": 96775, "s": 96748, "text": "Implementation using C++ βˆ’" }, { "code": null, "e": 97106, "s": 96775, "text": "Class Project {\n private:\n // attributes\n Project_Manager pmgr; \n public: \n void setManager ( Project_Manager pm); \n Project_Manager changeManager(); \n};\n\nclass Project_Manager {\n private:\n // attributes\n Project pj; \n\n public: \n void setProject(Project p); \n Project removeProject(); \n};" }, { "code": null, "e": 97252, "s": 97106, "text": "One–to–many Associations βˆ’ Consider the relationship between Department and Employee having one–to–many association as shown in the figure below." }, { "code": null, "e": 97398, "s": 97252, "text": "One–to–many Associations βˆ’ Consider the relationship between Department and Employee having one–to–many association as shown in the figure below." }, { "code": null, "e": 97926, "s": 97398, "text": "class Department {\n private:\n char * deptName;\n list <Employee> emp; //a list of Employees as attribute\n\n public: \n void addEmployee ( Employee e) { \n emp.push_back(e); \n } // adds an employee to the department\n\n void removeEmployee( Employee e) { \n int index = find ( e, emp );\n // find function returns the index of e in list emp\n emp.erase(index);\n } \n};\n\nclass Employee {\n private:\n //attributes\n Department d;\n\n public:\n void addDept();\n void removeDept();\n};" }, { "code": null, "e": 98133, "s": 97926, "text": "If an association has some attributes associated, it should be implemented using a separate class. For example, consider the one–to–one association between Employee and Project as shown in the figure below." }, { "code": null, "e": 98257, "s": 98133, "text": "class WorksOn {\n private:\n Employee e; \n Project p;\n Hours h;\n char * date;\n\n public:\n // class methods\n};\t " }, { "code": null, "e": 98655, "s": 98257, "text": "Constraints in classes restrict the range and type of values that the attributes may take. In order to implement constraints, a valid default value is assigned to the attribute when an object is instantiated from the class. Whenever the value is changed at runtime, it is checked whether the value is valid or not. An invalid value may be handled by an exception handling routine or other methods." }, { "code": null, "e": 98663, "s": 98655, "text": "Example" }, { "code": null, "e": 98804, "s": 98663, "text": "Consider an Employee class where age is an attribute that may have values in the range of 18 to 60. The following C++ code incorporates it βˆ’" }, { "code": null, "e": 99277, "s": 98804, "text": "class Employee {\n private: char * name;\n int age;\n // other attributes\n\n public:\n Employee() { // default constructor \n strcpy(name, \"\");\n age = 18; // default value\n }\n \n class AgeError {}; // Exception class\n void changeAge( int a) { // method that changes age\n\n if ( a < 18 || a > 60 ) // check for invalid condition\n throw AgeError(); // throw exception\n age = a;\t\t\t\n }\n};" }, { "code": null, "e": 99374, "s": 99277, "text": "There are two alternative implementation strategies to implement states in state chart diagrams." }, { "code": null, "e": 99656, "s": 99374, "text": "In this approach, the states are represented by different values of a data member (or set of data members). The values are explicitly defined by an enumeration within the class. The transitions are represented by member functions that change the value of the concerned data member." }, { "code": null, "e": 99896, "s": 99656, "text": "In this approach, the states are arranged in a generalization hierarchy in a manner that they can be referred by a common pointer variable. The following figure shows a transformation from state chart diagram to a generalization hierarchy." }, { "code": null, "e": 100160, "s": 99896, "text": "An important aspect of developing object-oriented systems is persistency of data. Through persistency, objects have longer lifespan than the program that created it. Persistent data is saved on secondary storage medium from where it can be reloaded when required." }, { "code": null, "e": 100213, "s": 100160, "text": "A database is an ordered collection of related data." }, { "code": null, "e": 100407, "s": 100213, "text": "A database management system (DBMS) is a collection of software that facilitates the processes of defining, creating, storing, manipulating, retrieving, sharing, and removing data in databases." }, { "code": null, "e": 100606, "s": 100407, "text": "In relational database management systems (RDBMS), data is stored as relations or tables, where each column or field represents an attribute and each row or tuple represents a record of an instance." }, { "code": null, "e": 100696, "s": 100606, "text": "Each row is uniquely identified by a chosen set of minimal attributes called primary key." }, { "code": null, "e": 100770, "s": 100696, "text": "A foreign key is an attribute that is the primary key of a related table." }, { "code": null, "e": 101048, "s": 100770, "text": "To map a class to a database table, each attribute is represented as a field in the table. Either an existing attribute(s) is assigned as a primary key or a separate ID field is added as a primary key. The class may be partitioned horizontally or vertically as per requirement." }, { "code": null, "e": 101134, "s": 101048, "text": "For example, the Circle class can be converted to table as shown in the figure below." }, { "code": null, "e": 101404, "s": 101134, "text": "Schema for Circle Table: CIRCLE(CID, X_COORD, Y_COORD, RADIUS, COLOR)\nCreating a Table Circle using SQL command:\nCREATE TABLE CIRCLE ( \n CID\tVARCHAR2(4) PRIMARY KEY,\n X_COORD INTEGER NOT NULL,\n Y_COORD INTEGER NOT NULL,\n Z_COORD INTEGER NOT NULL,\n COLOR \n);" }, { "code": null, "e": 101590, "s": 101404, "text": "To implement 1:1 associations, the primary key of any one table is assigned as the foreign key of the other table. For example, consider the association between Department and Manager βˆ’" }, { "code": null, "e": 101862, "s": 101590, "text": "CREATE TABLE DEPARTMENT ( \n DEPT_ID INTEGER PRIMARY KEY,\n DNAME VARCHAR2(30) NOT NULL,\n LOCATION VARCHAR2(20),\n EMPID INTEGER REFERENCES MANAGER \n);\n\nCREATE TABLE MANAGER ( \n EMPID INTEGER PRIMARY KEY,\n ENAME VARCHAR2(50) NOT NULL,\n ADDRESS VARCHAR2(70),\n);" }, { "code": null, "e": 102105, "s": 101862, "text": "To implement 1:N associations, the primary key of the table in the 1-side of the association is assigned as the foreign key of the table at the N-side of the association. For example, consider the association between Department and Employee βˆ’" }, { "code": null, "e": 102379, "s": 102105, "text": "CREATE TABLE DEPARTMENT ( \n DEPT_ID INTEGER PRIMARY KEY,\n DNAME VARCHAR2(30) NOT NULL,\n LOCATION VARCHAR2(20),\n);\n\nCREATE TABLE EMPLOYEE ( \n EMPID INTEGER PRIMARY KEY,\n ENAME VARCHAR2(50) NOT NULL,\n ADDRESS VARCHAR2(70),\n D_ID INTEGER REFERENCES DEPARTMENT\n);" }, { "code": null, "e": 102548, "s": 102379, "text": "To implement M:N associations, a new relation is created that represents the association. For example, consider the following association between Employee and Project βˆ’" }, { "code": null, "e": 102617, "s": 102548, "text": "Schema for Works_On Table βˆ’ WORKS_ON (EMPID, PID, HOURS, START_DATE)" }, { "code": null, "e": 102684, "s": 102617, "text": "SQL command to create Works_On association βˆ’ CREATE TABLE WORKS_ON" }, { "code": null, "e": 102877, "s": 102684, "text": "( \n EMPID INTEGER,\n PID INTEGER, \n HOURS INTEGER,\n START_DATE DATE,\n PRIMARY KEY (EMPID, PID),\n FOREIGN KEY (EMPID) REFERENCES EMPLOYEE,\n FOREIGN KEY (PID) REFERENCES PROJECT \n);" }, { "code": null, "e": 103017, "s": 102877, "text": "To map inheritance, the primary key of the base table(s) is assigned as the primary key as well as the foreign key in the derived table(s)." }, { "code": null, "e": 103025, "s": 103017, "text": "Example" }, { "code": null, "e": 103178, "s": 103025, "text": "Once a program code is written, it must be tested to detect and subsequently handle all errors in it. A number of schemes are used for testing purposes." }, { "code": null, "e": 103358, "s": 103178, "text": "Another important aspect is the fitness of purpose of a program that ascertains whether the program serves the purpose which it aims for. The fitness defines the software quality." }, { "code": null, "e": 103543, "s": 103358, "text": "Testing is a continuous activity during software development. In object-oriented systems, testing encompasses three levels, namely, unit testing, subsystem testing, and system testing." }, { "code": null, "e": 103817, "s": 103543, "text": "In unit testing, the individual classes are tested. It is seen whether the class attributes are implemented as per design and whether the methods and the interfaces are error-free. Unit testing is the responsibility of the application engineer who implements the structure." }, { "code": null, "e": 104141, "s": 103817, "text": "This involves testing a particular module or a subsystem and is the responsibility of the subsystem lead. It involves testing the associations within the subsystem as well as the interaction of the subsystem with the outside. Subsystem tests can be used as regression tests for each newly released version of the subsystem." }, { "code": null, "e": 104335, "s": 104141, "text": "System testing involves testing the system as a whole and is the responsibility of the quality-assurance team. The team often uses system tests as regression tests when assembling new releases." }, { "code": null, "e": 104513, "s": 104335, "text": "The different types of test cases that can be designed for testing object-oriented programs are called grey box test cases. Some of the important types of grey box testing are βˆ’" }, { "code": null, "e": 104637, "s": 104513, "text": "State model based testing βˆ’ This encompasses state coverage, state transition coverage, and state transition path coverage." }, { "code": null, "e": 104761, "s": 104637, "text": "State model based testing βˆ’ This encompasses state coverage, state transition coverage, and state transition path coverage." }, { "code": null, "e": 104828, "s": 104761, "text": "Use case based testing βˆ’ Each scenario in each use case is tested." }, { "code": null, "e": 104895, "s": 104828, "text": "Use case based testing βˆ’ Each scenario in each use case is tested." }, { "code": null, "e": 104995, "s": 104895, "text": "Class diagram based testing βˆ’ Each class, derived class, associations, and aggregations are tested." }, { "code": null, "e": 105095, "s": 104995, "text": "Class diagram based testing βˆ’ Each class, derived class, associations, and aggregations are tested." }, { "code": null, "e": 105193, "s": 105095, "text": "Sequence diagram based testing βˆ’ The methods in the messages in the sequence diagrams are tested." }, { "code": null, "e": 105291, "s": 105193, "text": "Sequence diagram based testing βˆ’ The methods in the messages in the sequence diagrams are tested." }, { "code": null, "e": 105342, "s": 105291, "text": "The two main approaches of subsystem testing are βˆ’" }, { "code": null, "e": 105464, "s": 105342, "text": "Thread based testing βˆ’ All classes that are needed to realize a single use case in a subsystem are integrated and tested." }, { "code": null, "e": 105586, "s": 105464, "text": "Thread based testing βˆ’ All classes that are needed to realize a single use case in a subsystem are integrated and tested." }, { "code": null, "e": 105842, "s": 105586, "text": "Use based testing βˆ’ The interfaces and services of the modules at each level of hierarchy are tested. Testing starts from the individual classes to the small modules comprising of classes, gradually to larger modules, and finally all the major subsystems." }, { "code": null, "e": 106098, "s": 105842, "text": "Use based testing βˆ’ The interfaces and services of the modules at each level of hierarchy are tested. Testing starts from the individual classes to the small modules comprising of classes, gradually to larger modules, and finally all the major subsystems." }, { "code": null, "e": 106202, "s": 106098, "text": "Alpha testing βˆ’ This is carried out by the testing team within the organization that develops software." }, { "code": null, "e": 106306, "s": 106202, "text": "Alpha testing βˆ’ This is carried out by the testing team within the organization that develops software." }, { "code": null, "e": 106384, "s": 106306, "text": "Beta testing βˆ’ This is carried out by select group of co-operating customers." }, { "code": null, "e": 106462, "s": 106384, "text": "Beta testing βˆ’ This is carried out by select group of co-operating customers." }, { "code": null, "e": 106554, "s": 106462, "text": "Acceptance testing βˆ’ This is carried out by the customer before accepting the deliverables." }, { "code": null, "e": 106646, "s": 106554, "text": "Acceptance testing βˆ’ This is carried out by the customer before accepting the deliverables." }, { "code": null, "e": 106918, "s": 106646, "text": "Schulmeyer and McManus have defined software quality as β€œthe fitness for use of the total software product”. A good quality software does exactly what it is supposed to do and is interpreted in terms of satisfaction of the requirement specification laid down by the user." }, { "code": null, "e": 107105, "s": 106918, "text": "Software quality assurance is a methodology that determines the extent to which a software product is fit for use. The activities that are included for determining software quality are βˆ’" }, { "code": null, "e": 107114, "s": 107105, "text": "Auditing" }, { "code": null, "e": 107154, "s": 107114, "text": "Development of standards and guidelines" }, { "code": null, "e": 107176, "s": 107154, "text": "Production of reports" }, { "code": null, "e": 107201, "s": 107176, "text": "Review of quality system" }, { "code": null, "e": 107295, "s": 107201, "text": "Correctness βˆ’ Correctness determines whether the software requirements are appropriately met." }, { "code": null, "e": 107389, "s": 107295, "text": "Correctness βˆ’ Correctness determines whether the software requirements are appropriately met." }, { "code": null, "e": 107529, "s": 107389, "text": "Usability βˆ’ Usability determines whether the software can be used by different categories of users (beginners, non-technical, and experts)." }, { "code": null, "e": 107669, "s": 107529, "text": "Usability βˆ’ Usability determines whether the software can be used by different categories of users (beginners, non-technical, and experts)." }, { "code": null, "e": 107795, "s": 107669, "text": "Portability βˆ’ Portability determines whether the software can operate in different platforms with different hardware devices." }, { "code": null, "e": 107921, "s": 107795, "text": "Portability βˆ’ Portability determines whether the software can operate in different platforms with different hardware devices." }, { "code": null, "e": 108036, "s": 107921, "text": "Maintainability βˆ’ Maintainability determines the ease at which errors can be corrected and modules can be updated." }, { "code": null, "e": 108151, "s": 108036, "text": "Maintainability βˆ’ Maintainability determines the ease at which errors can be corrected and modules can be updated." }, { "code": null, "e": 108274, "s": 108151, "text": "Reusability βˆ’ Reusability determines whether the modules and classes can be reused for developing other software products." }, { "code": null, "e": 108397, "s": 108274, "text": "Reusability βˆ’ Reusability determines whether the modules and classes can be reused for developing other software products." }, { "code": null, "e": 108509, "s": 108397, "text": "Metrics can be broadly classified into three categories: project metrics, product metrics, and process metrics." }, { "code": null, "e": 108697, "s": 108509, "text": "Project Metrics enable a software project manager to assess the status and performance of an ongoing project. The following metrics are appropriate for object-oriented software projects βˆ’" }, { "code": null, "e": 108724, "s": 108697, "text": "Number of scenario scripts" }, { "code": null, "e": 108746, "s": 108724, "text": "Number of key classes" }, { "code": null, "e": 108772, "s": 108746, "text": "Number of support classes" }, { "code": null, "e": 108793, "s": 108772, "text": "Number of subsystems" }, { "code": null, "e": 108949, "s": 108793, "text": "Product metrics measure the characteristics of the software product that has been developed. The product metrics suitable for object-oriented systems are βˆ’" }, { "code": null, "e": 109159, "s": 108949, "text": "Methods per Class βˆ’ It determines the complexity of a class. If all the methods of a class are assumed to be equally complex, then a class with more methods is more complex and thus more susceptible to errors." }, { "code": null, "e": 109369, "s": 109159, "text": "Methods per Class βˆ’ It determines the complexity of a class. If all the methods of a class are assumed to be equally complex, then a class with more methods is more complex and thus more susceptible to errors." }, { "code": null, "e": 109641, "s": 109369, "text": "Inheritance Structure βˆ’ Systems with several small inheritance lattices are more well–structured than systems with a single large inheritance lattice. As a thumb rule, an inheritance tree should not have more than 7 (Β± 2) number of levels and the tree should be balanced." }, { "code": null, "e": 109913, "s": 109641, "text": "Inheritance Structure βˆ’ Systems with several small inheritance lattices are more well–structured than systems with a single large inheritance lattice. As a thumb rule, an inheritance tree should not have more than 7 (Β± 2) number of levels and the tree should be balanced." }, { "code": null, "e": 110077, "s": 109913, "text": "Coupling and Cohesion βˆ’ Modules having low coupling and high cohesion are considered to be better designed, as they permit greater reusability and maintainability." }, { "code": null, "e": 110241, "s": 110077, "text": "Coupling and Cohesion βˆ’ Modules having low coupling and high cohesion are considered to be better designed, as they permit greater reusability and maintainability." }, { "code": null, "e": 110353, "s": 110241, "text": "Response for a Class βˆ’ It measures the efficiency of the methods that are called by the instances of the class." }, { "code": null, "e": 110465, "s": 110353, "text": "Response for a Class βˆ’ It measures the efficiency of the methods that are called by the instances of the class." }, { "code": null, "e": 110692, "s": 110465, "text": "Process metrics help in measuring how a process is performing. They are collected over all projects over long periods of time. They are used as indicators for long-term software process improvements. Some process metrics are βˆ’" }, { "code": null, "e": 110728, "s": 110692, "text": "Number of KLOC (Kilo Lines of Code)" }, { "code": null, "e": 110754, "s": 110728, "text": "Defect removal efficiency" }, { "code": null, "e": 110805, "s": 110754, "text": "Average number of failures detected during testing" }, { "code": null, "e": 110839, "s": 110805, "text": "Number of latent defects per KLOC" }, { "code": null, "e": 110874, "s": 110839, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 110894, "s": 110874, "text": " Harshit Srivastava" }, { "code": null, "e": 110927, "s": 110894, "text": "\n 60 Lectures \n 8 hours \n" }, { "code": null, "e": 110958, "s": 110927, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 110990, "s": 110958, "text": "\n 11 Lectures \n 35 mins\n" }, { "code": null, "e": 111011, "s": 110990, "text": " Sandip Bhattacharya" }, { "code": null, "e": 111044, "s": 111011, "text": "\n 21 Lectures \n 2 hours \n" }, { "code": null, "e": 111064, "s": 111044, "text": " Pranjal Srivastava" }, { "code": null, "e": 111095, "s": 111064, "text": "\n 6 Lectures \n 43 mins\n" }, { "code": null, "e": 111112, "s": 111095, "text": " Frahaan Hussain" }, { "code": null, "e": 111147, "s": 111112, "text": "\n 49 Lectures \n 4.5 hours \n" }, { "code": null, "e": 111164, "s": 111147, "text": " Abhilash Nelson" }, { "code": null, "e": 111171, "s": 111164, "text": " Print" }, { "code": null, "e": 111182, "s": 111171, "text": " Add Notes" } ]
Understanding Customer Churning with Big Data Analytics | by Bowen Chen | Towards Data Science
Take a guess. What is the world’s most valuable asset right now? It is not gold, not crude oil... it is data. You must have heard about the popular buzz word β€œbig data”, and wondering what exactly that term means. Think about your favorite music streaming services β€” Spotify, Pandora... etc. Every second across the world, many different users login to the service, have their fair share of interactions with the service. Since every move corresponds to a collectible data point, you would imagine the challenges to store such large data. Fortunately, these large datasets could bring real value to the business if they are being consumed in the right way. In this blog post, we will discuss a common use case for these big datasets β€” predicting customers churning. Understanding Churn Churning refers to the behavior of discreetly losing customers from a large population of customers. Some of the churned customers might turn to a competitor, while some of them might simply leave the services forever. It might not be noticeable at the beginning, but the effect of such losses accumulates over time. As decision-makers at these music streaming service providers, we would like to understand the contributing factors of such churning behaviors β€” that will serve as the primary objective of our project today. We will start by examining the dataset available. The full dataset is a user log that is stored in a 12 GB .json file β€” a size that could only be handled by some big data tools, such as Spark. To fully understand the fields available, we will start by obtaining a small subset of the data (~128 MB) for exploratory data analysis purposes on a single machine. We will load in our dataset through the following commands, # create a Spark sessionspark = (SparkSession.builder .master("local") .appName("Creating Features") .getOrCreate())# Read in .json file as eventsevents = spark.read.json('mini_sparkify_event_data.json')events.persist() Spark has a great one-line shortcut of showing all the fields and their respective data types events.printSchema()root |-- artist: string (nullable = true) |-- auth: string (nullable = true) |-- firstName: string (nullable = true) |-- gender: string (nullable = true) |-- itemInSession: long (nullable = true) |-- lastName: string (nullable = true) |-- length: double (nullable = true) |-- level: string (nullable = true) |-- location: string (nullable = true) |-- method: string (nullable = true) |-- page: string (nullable = true) |-- registration: long (nullable = true) |-- sessionId: long (nullable = true) |-- song: string (nullable = true) |-- status: long (nullable = true) |-- ts: long (nullable = true) |-- userAgent: string (nullable = true) |-- userId: string (nullable = true) After looking at the head of the dataset, we will recognize that all of the user interactions are recorded in the page column. While most of the users keep playing the next song, there are some users going into the β€œCancel” page β€” and they all confirmed their cancellations through the β€œCancellation Confirmation” page (see the same number of β€œCancel”s and β€œCancellation Confirmation”s. We will define the churning activity specifically as the number of Cancellation Confirmation. The users with page column have β€œCancellation Confirmation” will be the churned users that we are specifically interested in. Feature Engineering We have successfully identified the churned users, now it is time to use our business mindset to think of the contributing factors to users churning. What would you do if you really hate your music streaming services? I have come up with the below 7 features, Representative User Interactions Representative User Interactions We would reasonably expect some of the other user interactions will eventually lead to our user churning. We could use a box plot to perform the first level filtering. Box plots will effectively help us visualize the minimum, 25th percentile, mean, 75th percentile and maximum for particular data distribution. By plotting box plots for both churned and non-churned users, we could clearly interpret the difference between the two types of users for a particular interaction. The following interactions showed significant distribution differences between the two groups, Add Friends β€” Churned users are less likely to add friends Add to Playlist β€” Churned users are less likely to add to playlists Upgrade β€” Churned users have a wide range of upgrade activities NextSong β€” Churned users are less likely to play next song ThumbsUp β€” Churned users are less likely to press thumbs up Roll Advert β€” Churned users have a wider spread on roll advert Settings β€” Churned users less likely to visit the settings page Log out β€” Churned users less likely to log out (due to fewer logins) Help β€” Non-churned users more likely to ask for help Home β€” Churned users less likely to visit the home page Notice that all of our user interactions are in the same column, we will need to pivot and aggregate the total number of a certain interaction for each customer. Based on the above filtering, we will drop some of the less significant interactions. events = events.drop('firstName', 'lastName', 'auth', 'gender', 'song','artist', 'status', 'method', 'location', 'registration', 'itemInSession')events_pivot = (events.groupby(["userId"]) .pivot("page") .count() .fillna(0))events_pivot = events_pivot.drop('About', 'Cancel', 'Login', 'Submit Registration','Register', 'Save Settings') 2. Average Music Play Time For myself, I would probably be using it way shorter than normal users. Therefore, the average length of time the user spent playing music will be a really important factor. A simple visualization showed confirming results on below. We will add this feature to our events_pivot table, # filter events log to contain only next songevents_songs = events.filter(events.page == 'NextSong')# Total songs length playedtotal_length = (events_songs.groupby(events_songs.userId) .agg(sum('length')))# join events pivotevents_pivot = (events_pivot.join(total_length, on = 'userId', how = 'left') .withColumnRenamed("Cancellation Confirmation", "Churn") .withColumnRenamed("sum(length)", "total_length")) 3. Number of active days We would also expect a difference in the number of active days between the churned/non-churned groups. Since the datetime column only contains units in seconds, we will need to use a window function to aggregate the total active time for each customer and convert the value to days. We will add this feature to events_pivot. convert = 1000*60*60*24 # conversion factor to days# Find minimum/maximum time stamp of each usermin_timestmp = events.select(["userId", "ts"]) .groupby("userId") .min("ts")max_timestmp = events.select(["userId", "ts"]) .groupby("userId") .max("ts")# Find days active of each userdaysActive = min_timestmp.join(max_timestmp, on="userId")daysActive = (daysActive.withColumn("days_active", (col("max(ts)")-col("min(ts)")) / convert))daysActive = daysActive.select(["userId", "days_active"])# join events pivotevents_pivot = events_pivot.join(daysActive, on = 'userId', how = 'left') 4. Number of days as paid users Similarly, we could also calculate the number of days as paid users by using a window function, we only need to add a filter for the customer to be a paid customer user. # Find minimum/maximum time stamp of each user as paid userpaid_min_ts = events.filter(events.level == 'paid') .groupby("userId").min("ts")paid_max_ts = events.filter(events.level == 'paid') .groupby("userId").max("ts")# Find days as paid user of each userdaysPaid = paid_min_ts.join(paid_max_ts, on="userId")daysPaid = (daysPaid.withColumn("days_paid", (col("max(ts)")-col("min(ts)")) / convert))daysPaid = daysPaid.select(["userId", "days_paid"])# join events pivotevents_pivot = events_pivot.join(daysPaid, on = 'userId', how='left') 5. Number of days as a free user Now using the free user filter, we can find the number of days as a free user for each customer, # Find minimum/maximum time stamp of each user as paid userfree_min_ts = events.filter(events.level == 'free') .groupby("userId").min("ts")free_max_ts = events.filter(events.level == 'free') .groupby("userId").max("ts")# Find days as paid user of each userdaysFree = free_min_ts.join(free_max_ts, on="userId")daysFree = (daysFree.withColumn("days_free", (col("max(ts)")-col("min(ts)")) / convert))daysFree = daysFree.select(["userId", "days_free"])# join events pivotevents_pivot = events_pivot.join(daysFree, on = 'userId', how='left') 6. Number of sessions The number of music playing sessions could also be a contributing factor. Since the sessionId is available in this dataset, we could directly count the number of unique ids for each user with the groupby clause. # count the number of sessionsnumSessions = (events.select(["userId", "sessionId"]) .distinct() .groupby("userId") .count() .withColumnRenamed("count", "num_sessions"))# join events pivotevents_pivot = events_pivot.join(numSessions, on = 'userId', how = 'left') 7. User access agent The streaming service might have disparate performances on different user agents. We will try to add this factor to the model. Since there are 56 different user agents, we will use Spark’s one-hot encoder to turn these different user agents into a vector. # find user access agents, and perform one-hot encoding on the user userAgents = events.select(['userId', 'userAgent']).distinct()userAgents = userAgents.fillna('Unknown')# build string indexerstringIndexer = StringIndexer(inputCol="userAgent", outputCol="userAgentIndex")model = stringIndexer.fit(userAgents)userAgents = model.transform(userAgents)# one hot encode userAgent columnencoder = OneHotEncoder(inputCol="userAgentIndex", outputCol="userAgentVec")userAgents = encoder.transform(userAgents) .select(['userId', 'userAgentVec'])# join events pivotevents_pivot = events_pivot.join(userAgents, on = 'userId', how ='left') Model Building After we have engineered the appropriate features, we will build three models β€” logistic regression, random forest and gradient boosting trees. To avoid writing redundant code, we will build stage objects and construct pipelines with a different classifier at the end of the pipeline. # Split data into train and test setevents_pivot = events_pivot.withColumnRenamed('Churn', 'label')training, test = events_pivot.randomSplit([0.8, 0.2])# Create vector from feature datafeature_names = events_pivot.drop('label', 'userId').schema.namesvec_asembler = VectorAssembler(inputCols = feature_names, outputCol = "Features")# Scale each columnscalar = MinMaxScaler(inputCol="Features", outputCol="ScaledFeatures")# Build classifiersrf = RandomForestClassifier(featuresCol="ScaledFeatures", labelCol="label", numTrees = 50, featureSubsetStrategy='sqrt')lr = LogisticRegression(featuresCol="ScaledFeatures", labelCol="label", maxIter=10, regParam=0.01)gbt = GBTClassifier(featuresCol="ScaledFeatures", labelCol="label")# Consturct 3 pipelinespipeline_rf = Pipeline(stages=[vec_asembler, scalar, rf])pipeline_lr = Pipeline(stages=[vec_asembler, scalar, lr])pipeline_gbt = Pipeline(stages=[vec_asembler, scalar, gbt])# Fit the modelsrf_model = pipeline_rf.fit(training)lr_model = pipeline_lr.fit(training)gbt_model = pipeline_gbt.fit(training) now the three objects rf_model, lr_model, gbt_model, represents the 3 different fitted models. Model Evaluation We will test the fitted models' performances and select the one that has the best performance as the final model. We will start by building a function especially for this purpose, def modelEvaluations(model, metric, data): """ Evaluate a machine learning model's performance Input: model - pipeline object metric - the metric of the evaluations data - data being evaluated Output: [score, confusion matrix] """ # generate predictions evaluator = MulticlassClassificationEvaluator( metricName = metric) predictions = model.transform(data) # calcualte score score = evaluator.evaluate(predictions) confusion_matrix = (predictions.groupby("label") .pivot("prediction") .count() .toPandas()) return [score, confusion_matrix] We will call the above function to evaluate the above models f1_rf, conf_mtx_rf = modelEvaluations(rf_model, 'f1', test)f1_lr, conf_mtx_lr = modelEvaluations(lr_model, 'f1', test)f1_gbt, conf_mtx_gbt = modelEvaluations(gbt_model, 'f1', test) The gradient boosting model showed the best performance (F1 Score) in the test set. F1 score is defined as the harmonic mean of precision and recall, calculated as the following Precision is computing the proportion of positive class identifications being the correct ones, in mathematical expressions it is precision = tp/(tp + fp) Recall is computing the proportion of actual positive class samples being identified correctly, in mathematical expressions it is, recall = tp/(tp + fn) You might be wondering the reason we opt for a much more complicated metric over the most intuitive accuracy β€” it is due to imbalance class distributions existed in the dataset. Since only a small portion of users will eventually churn, we would like our model to correctly identify them instead of pursuing a high overall performance. Imagine if only 6% of the customer will churn within the true population distributions, predicting everyone as non-churn will still give us 94% accuracy. On the other hand, F1 score will penalize poor performances on a single class, which will effectively mitigate such issues. The imbalance class characteristic will be present in every churn prediction problems β€” F1 will always be the metric to use in the future. Feature Importance We will utilize the feature importance function and visualize the relative importance rank of each feature we built. Due to the last feature userAgentVec is, in fact, a one-hot encoded vector, we will treat the userAgentVec feature as one. The below code will sum up all the feature importance values for all the sub-features obtained from the one-hot encoded vector. feature_importances = np.array(gbt_model.stages[-1] .featureImportances)userAgentVec = feature_importances[len(feature_names) :].sum()feature_importances = feature_importances[:len(feature_names)] + [userAgentVec] Now we plot the feature importance for gradient boosting trees. Most of the features we constructed are quite important contributing factors for user churning, with days_active as the most important factor. Full Dataset Run We have constructed the appropriate framework β€” we are ready to follow the same steps as above to let the model run on the full 12 GB dataset using AWS’s EMR service. We will initialize the session by the following way # Create spark sessionspark = (SparkSession .builder .appName("Sparkify") .getOrCreate())# Read in full sparkify datasetevent_data = "s3n://dsnd-sparkify/sparkify_event_data.json"events = spark.read.json(event_data) We will not repeat the steps again β€” I have attached the full script on the nbviewer site. Eventually, the gradient boosting model produced an F1 score of 0.8896, which is a great performance. +-----+----+---+|label| 0.0|1.0|+-----+----+---+| 0|1612| 70|| 1| 163|344|+-----+----+---+ Business Strategy What a journey we have been through β€” but we have not finished our mission yet. In the data science world, there is a business intention behind every model. With the feature importance we produced, we could definitely come up with some business strategies to counter customer churns. We will briefly discuss two possible strategies that will truly drive some values for our providers. We know that the number of active days is the most significant factor, we could advise the upper management to construct a reward system to encourage low activity users to stay online for extended periods of time. In addition, since the agents that users used to access the service is also quite significant, we could also find out the poor-performing agent and get our engineering team to work specifically to solve the issue. I hope you have enjoyed reading this post as much as I enjoy writing it. Together, we used Spark, the big data analytics framework, to build an end-to-end machine learning workflow to identify potential customer churning for music streaming services from the user logs. We performed the following steps, Exploratory Data AnalysisFeature EngineeringModel BuildingModel EvaluationsModel Scale UpBusiness Strategies Exploratory Data Analysis Feature Engineering Model Building Model Evaluations Model Scale Up Business Strategies Due to the sheer size of the data we are working with, performing hyperparameters search has been particularly difficult. One could imagine leaving the notebook open for extended periods of time would not be the most efficient way to use our resources. Some of the nice tricks in using ssh to keep the program running could definitely help tackle this challenge. If there is one thing we should take away from this piece β€” It comes back to the point we have mentioned at the beginning of the story. As brilliant engineers, we often get drawn to building the best high-performance models through various techniques, but our model needs to solve business problems for it to be valuable.
[ { "code": null, "e": 112, "s": 47, "text": "Take a guess. What is the world’s most valuable asset right now?" }, { "code": null, "e": 586, "s": 112, "text": "It is not gold, not crude oil... it is data. You must have heard about the popular buzz word β€œbig data”, and wondering what exactly that term means. Think about your favorite music streaming services β€” Spotify, Pandora... etc. Every second across the world, many different users login to the service, have their fair share of interactions with the service. Since every move corresponds to a collectible data point, you would imagine the challenges to store such large data." }, { "code": null, "e": 813, "s": 586, "text": "Fortunately, these large datasets could bring real value to the business if they are being consumed in the right way. In this blog post, we will discuss a common use case for these big datasets β€” predicting customers churning." }, { "code": null, "e": 833, "s": 813, "text": "Understanding Churn" }, { "code": null, "e": 1052, "s": 833, "text": "Churning refers to the behavior of discreetly losing customers from a large population of customers. Some of the churned customers might turn to a competitor, while some of them might simply leave the services forever." }, { "code": null, "e": 1358, "s": 1052, "text": "It might not be noticeable at the beginning, but the effect of such losses accumulates over time. As decision-makers at these music streaming service providers, we would like to understand the contributing factors of such churning behaviors β€” that will serve as the primary objective of our project today." }, { "code": null, "e": 1408, "s": 1358, "text": "We will start by examining the dataset available." }, { "code": null, "e": 1777, "s": 1408, "text": "The full dataset is a user log that is stored in a 12 GB .json file β€” a size that could only be handled by some big data tools, such as Spark. To fully understand the fields available, we will start by obtaining a small subset of the data (~128 MB) for exploratory data analysis purposes on a single machine. We will load in our dataset through the following commands," }, { "code": null, "e": 2057, "s": 1777, "text": "# create a Spark sessionspark = (SparkSession.builder .master(\"local\") .appName(\"Creating Features\") .getOrCreate())# Read in .json file as eventsevents = spark.read.json('mini_sparkify_event_data.json')events.persist()" }, { "code": null, "e": 2151, "s": 2057, "text": "Spark has a great one-line shortcut of showing all the fields and their respective data types" }, { "code": null, "e": 2847, "s": 2151, "text": "events.printSchema()root |-- artist: string (nullable = true) |-- auth: string (nullable = true) |-- firstName: string (nullable = true) |-- gender: string (nullable = true) |-- itemInSession: long (nullable = true) |-- lastName: string (nullable = true) |-- length: double (nullable = true) |-- level: string (nullable = true) |-- location: string (nullable = true) |-- method: string (nullable = true) |-- page: string (nullable = true) |-- registration: long (nullable = true) |-- sessionId: long (nullable = true) |-- song: string (nullable = true) |-- status: long (nullable = true) |-- ts: long (nullable = true) |-- userAgent: string (nullable = true) |-- userId: string (nullable = true)" }, { "code": null, "e": 2974, "s": 2847, "text": "After looking at the head of the dataset, we will recognize that all of the user interactions are recorded in the page column." }, { "code": null, "e": 3454, "s": 2974, "text": "While most of the users keep playing the next song, there are some users going into the β€œCancel” page β€” and they all confirmed their cancellations through the β€œCancellation Confirmation” page (see the same number of β€œCancel”s and β€œCancellation Confirmation”s. We will define the churning activity specifically as the number of Cancellation Confirmation. The users with page column have β€œCancellation Confirmation” will be the churned users that we are specifically interested in." }, { "code": null, "e": 3474, "s": 3454, "text": "Feature Engineering" }, { "code": null, "e": 3734, "s": 3474, "text": "We have successfully identified the churned users, now it is time to use our business mindset to think of the contributing factors to users churning. What would you do if you really hate your music streaming services? I have come up with the below 7 features," }, { "code": null, "e": 3767, "s": 3734, "text": "Representative User Interactions" }, { "code": null, "e": 3800, "s": 3767, "text": "Representative User Interactions" }, { "code": null, "e": 4276, "s": 3800, "text": "We would reasonably expect some of the other user interactions will eventually lead to our user churning. We could use a box plot to perform the first level filtering. Box plots will effectively help us visualize the minimum, 25th percentile, mean, 75th percentile and maximum for particular data distribution. By plotting box plots for both churned and non-churned users, we could clearly interpret the difference between the two types of users for a particular interaction." }, { "code": null, "e": 4371, "s": 4276, "text": "The following interactions showed significant distribution differences between the two groups," }, { "code": null, "e": 4430, "s": 4371, "text": "Add Friends β€” Churned users are less likely to add friends" }, { "code": null, "e": 4498, "s": 4430, "text": "Add to Playlist β€” Churned users are less likely to add to playlists" }, { "code": null, "e": 4562, "s": 4498, "text": "Upgrade β€” Churned users have a wide range of upgrade activities" }, { "code": null, "e": 4621, "s": 4562, "text": "NextSong β€” Churned users are less likely to play next song" }, { "code": null, "e": 4681, "s": 4621, "text": "ThumbsUp β€” Churned users are less likely to press thumbs up" }, { "code": null, "e": 4744, "s": 4681, "text": "Roll Advert β€” Churned users have a wider spread on roll advert" }, { "code": null, "e": 4808, "s": 4744, "text": "Settings β€” Churned users less likely to visit the settings page" }, { "code": null, "e": 4877, "s": 4808, "text": "Log out β€” Churned users less likely to log out (due to fewer logins)" }, { "code": null, "e": 4930, "s": 4877, "text": "Help β€” Non-churned users more likely to ask for help" }, { "code": null, "e": 4986, "s": 4930, "text": "Home β€” Churned users less likely to visit the home page" }, { "code": null, "e": 5234, "s": 4986, "text": "Notice that all of our user interactions are in the same column, we will need to pivot and aggregate the total number of a certain interaction for each customer. Based on the above filtering, we will drop some of the less significant interactions." }, { "code": null, "e": 5762, "s": 5234, "text": "events = events.drop('firstName', 'lastName', 'auth', 'gender', 'song','artist', 'status', 'method', 'location', 'registration', 'itemInSession')events_pivot = (events.groupby([\"userId\"]) .pivot(\"page\") .count() .fillna(0))events_pivot = events_pivot.drop('About', 'Cancel', 'Login', 'Submit Registration','Register', 'Save Settings')" }, { "code": null, "e": 5789, "s": 5762, "text": "2. Average Music Play Time" }, { "code": null, "e": 6022, "s": 5789, "text": "For myself, I would probably be using it way shorter than normal users. Therefore, the average length of time the user spent playing music will be a really important factor. A simple visualization showed confirming results on below." }, { "code": null, "e": 6074, "s": 6022, "text": "We will add this feature to our events_pivot table," }, { "code": null, "e": 6662, "s": 6074, "text": "# filter events log to contain only next songevents_songs = events.filter(events.page == 'NextSong')# Total songs length playedtotal_length = (events_songs.groupby(events_songs.userId) .agg(sum('length')))# join events pivotevents_pivot = (events_pivot.join(total_length, on = 'userId', how = 'left') .withColumnRenamed(\"Cancellation Confirmation\", \"Churn\") .withColumnRenamed(\"sum(length)\", \"total_length\"))" }, { "code": null, "e": 6687, "s": 6662, "text": "3. Number of active days" }, { "code": null, "e": 7012, "s": 6687, "text": "We would also expect a difference in the number of active days between the churned/non-churned groups. Since the datetime column only contains units in seconds, we will need to use a window function to aggregate the total active time for each customer and convert the value to days. We will add this feature to events_pivot." }, { "code": null, "e": 7760, "s": 7012, "text": "convert = 1000*60*60*24 # conversion factor to days# Find minimum/maximum time stamp of each usermin_timestmp = events.select([\"userId\", \"ts\"]) .groupby(\"userId\") .min(\"ts\")max_timestmp = events.select([\"userId\", \"ts\"]) .groupby(\"userId\") .max(\"ts\")# Find days active of each userdaysActive = min_timestmp.join(max_timestmp, on=\"userId\")daysActive = (daysActive.withColumn(\"days_active\", (col(\"max(ts)\")-col(\"min(ts)\")) / convert))daysActive = daysActive.select([\"userId\", \"days_active\"])# join events pivotevents_pivot = events_pivot.join(daysActive, on = 'userId', how = 'left')" }, { "code": null, "e": 7792, "s": 7760, "text": "4. Number of days as paid users" }, { "code": null, "e": 7962, "s": 7792, "text": "Similarly, we could also calculate the number of days as paid users by using a window function, we only need to add a filter for the customer to be a paid customer user." }, { "code": null, "e": 8622, "s": 7962, "text": "# Find minimum/maximum time stamp of each user as paid userpaid_min_ts = events.filter(events.level == 'paid') .groupby(\"userId\").min(\"ts\")paid_max_ts = events.filter(events.level == 'paid') .groupby(\"userId\").max(\"ts\")# Find days as paid user of each userdaysPaid = paid_min_ts.join(paid_max_ts, on=\"userId\")daysPaid = (daysPaid.withColumn(\"days_paid\", (col(\"max(ts)\")-col(\"min(ts)\")) / convert))daysPaid = daysPaid.select([\"userId\", \"days_paid\"])# join events pivotevents_pivot = events_pivot.join(daysPaid, on = 'userId', how='left')" }, { "code": null, "e": 8655, "s": 8622, "text": "5. Number of days as a free user" }, { "code": null, "e": 8752, "s": 8655, "text": "Now using the free user filter, we can find the number of days as a free user for each customer," }, { "code": null, "e": 9415, "s": 8752, "text": "# Find minimum/maximum time stamp of each user as paid userfree_min_ts = events.filter(events.level == 'free') .groupby(\"userId\").min(\"ts\")free_max_ts = events.filter(events.level == 'free') .groupby(\"userId\").max(\"ts\")# Find days as paid user of each userdaysFree = free_min_ts.join(free_max_ts, on=\"userId\")daysFree = (daysFree.withColumn(\"days_free\", (col(\"max(ts)\")-col(\"min(ts)\")) / convert))daysFree = daysFree.select([\"userId\", \"days_free\"])# join events pivotevents_pivot = events_pivot.join(daysFree, on = 'userId', how='left')" }, { "code": null, "e": 9437, "s": 9415, "text": "6. Number of sessions" }, { "code": null, "e": 9649, "s": 9437, "text": "The number of music playing sessions could also be a contributing factor. Since the sessionId is available in this dataset, we could directly count the number of unique ids for each user with the groupby clause." }, { "code": null, "e": 10060, "s": 9649, "text": "# count the number of sessionsnumSessions = (events.select([\"userId\", \"sessionId\"]) .distinct() .groupby(\"userId\") .count() .withColumnRenamed(\"count\", \"num_sessions\"))# join events pivotevents_pivot = events_pivot.join(numSessions, on = 'userId', how = 'left')" }, { "code": null, "e": 10081, "s": 10060, "text": "7. User access agent" }, { "code": null, "e": 10337, "s": 10081, "text": "The streaming service might have disparate performances on different user agents. We will try to add this factor to the model. Since there are 56 different user agents, we will use Spark’s one-hot encoder to turn these different user agents into a vector." }, { "code": null, "e": 11108, "s": 10337, "text": "# find user access agents, and perform one-hot encoding on the user userAgents = events.select(['userId', 'userAgent']).distinct()userAgents = userAgents.fillna('Unknown')# build string indexerstringIndexer = StringIndexer(inputCol=\"userAgent\", outputCol=\"userAgentIndex\")model = stringIndexer.fit(userAgents)userAgents = model.transform(userAgents)# one hot encode userAgent columnencoder = OneHotEncoder(inputCol=\"userAgentIndex\", outputCol=\"userAgentVec\")userAgents = encoder.transform(userAgents) .select(['userId', 'userAgentVec'])# join events pivotevents_pivot = events_pivot.join(userAgents, on = 'userId', how ='left')" }, { "code": null, "e": 11123, "s": 11108, "text": "Model Building" }, { "code": null, "e": 11408, "s": 11123, "text": "After we have engineered the appropriate features, we will build three models β€” logistic regression, random forest and gradient boosting trees. To avoid writing redundant code, we will build stage objects and construct pipelines with a different classifier at the end of the pipeline." }, { "code": null, "e": 12682, "s": 11408, "text": "# Split data into train and test setevents_pivot = events_pivot.withColumnRenamed('Churn', 'label')training, test = events_pivot.randomSplit([0.8, 0.2])# Create vector from feature datafeature_names = events_pivot.drop('label', 'userId').schema.namesvec_asembler = VectorAssembler(inputCols = feature_names, outputCol = \"Features\")# Scale each columnscalar = MinMaxScaler(inputCol=\"Features\", outputCol=\"ScaledFeatures\")# Build classifiersrf = RandomForestClassifier(featuresCol=\"ScaledFeatures\", labelCol=\"label\", numTrees = 50, featureSubsetStrategy='sqrt')lr = LogisticRegression(featuresCol=\"ScaledFeatures\", labelCol=\"label\", maxIter=10, regParam=0.01)gbt = GBTClassifier(featuresCol=\"ScaledFeatures\", labelCol=\"label\")# Consturct 3 pipelinespipeline_rf = Pipeline(stages=[vec_asembler, scalar, rf])pipeline_lr = Pipeline(stages=[vec_asembler, scalar, lr])pipeline_gbt = Pipeline(stages=[vec_asembler, scalar, gbt])# Fit the modelsrf_model = pipeline_rf.fit(training)lr_model = pipeline_lr.fit(training)gbt_model = pipeline_gbt.fit(training)" }, { "code": null, "e": 12777, "s": 12682, "text": "now the three objects rf_model, lr_model, gbt_model, represents the 3 different fitted models." }, { "code": null, "e": 12794, "s": 12777, "text": "Model Evaluation" }, { "code": null, "e": 12974, "s": 12794, "text": "We will test the fitted models' performances and select the one that has the best performance as the final model. We will start by building a function especially for this purpose," }, { "code": null, "e": 13723, "s": 12974, "text": "def modelEvaluations(model, metric, data): \"\"\" Evaluate a machine learning model's performance Input: model - pipeline object metric - the metric of the evaluations data - data being evaluated Output: [score, confusion matrix] \"\"\" # generate predictions evaluator = MulticlassClassificationEvaluator( metricName = metric) predictions = model.transform(data) # calcualte score score = evaluator.evaluate(predictions) confusion_matrix = (predictions.groupby(\"label\") .pivot(\"prediction\") .count() .toPandas()) return [score, confusion_matrix]" }, { "code": null, "e": 13784, "s": 13723, "text": "We will call the above function to evaluate the above models" }, { "code": null, "e": 13965, "s": 13784, "text": "f1_rf, conf_mtx_rf = modelEvaluations(rf_model, 'f1', test)f1_lr, conf_mtx_lr = modelEvaluations(lr_model, 'f1', test)f1_gbt, conf_mtx_gbt = modelEvaluations(gbt_model, 'f1', test)" }, { "code": null, "e": 14143, "s": 13965, "text": "The gradient boosting model showed the best performance (F1 Score) in the test set. F1 score is defined as the harmonic mean of precision and recall, calculated as the following" }, { "code": null, "e": 14273, "s": 14143, "text": "Precision is computing the proportion of positive class identifications being the correct ones, in mathematical expressions it is" }, { "code": null, "e": 14298, "s": 14273, "text": "precision = tp/(tp + fp)" }, { "code": null, "e": 14429, "s": 14298, "text": "Recall is computing the proportion of actual positive class samples being identified correctly, in mathematical expressions it is," }, { "code": null, "e": 14451, "s": 14429, "text": "recall = tp/(tp + fn)" }, { "code": null, "e": 15204, "s": 14451, "text": "You might be wondering the reason we opt for a much more complicated metric over the most intuitive accuracy β€” it is due to imbalance class distributions existed in the dataset. Since only a small portion of users will eventually churn, we would like our model to correctly identify them instead of pursuing a high overall performance. Imagine if only 6% of the customer will churn within the true population distributions, predicting everyone as non-churn will still give us 94% accuracy. On the other hand, F1 score will penalize poor performances on a single class, which will effectively mitigate such issues. The imbalance class characteristic will be present in every churn prediction problems β€” F1 will always be the metric to use in the future." }, { "code": null, "e": 15223, "s": 15204, "text": "Feature Importance" }, { "code": null, "e": 15591, "s": 15223, "text": "We will utilize the feature importance function and visualize the relative importance rank of each feature we built. Due to the last feature userAgentVec is, in fact, a one-hot encoded vector, we will treat the userAgentVec feature as one. The below code will sum up all the feature importance values for all the sub-features obtained from the one-hot encoded vector." }, { "code": null, "e": 15856, "s": 15591, "text": "feature_importances = np.array(gbt_model.stages[-1] .featureImportances)userAgentVec = feature_importances[len(feature_names) :].sum()feature_importances = feature_importances[:len(feature_names)] + [userAgentVec]" }, { "code": null, "e": 15920, "s": 15856, "text": "Now we plot the feature importance for gradient boosting trees." }, { "code": null, "e": 16063, "s": 15920, "text": "Most of the features we constructed are quite important contributing factors for user churning, with days_active as the most important factor." }, { "code": null, "e": 16080, "s": 16063, "text": "Full Dataset Run" }, { "code": null, "e": 16299, "s": 16080, "text": "We have constructed the appropriate framework β€” we are ready to follow the same steps as above to let the model run on the full 12 GB dataset using AWS’s EMR service. We will initialize the session by the following way" }, { "code": null, "e": 16539, "s": 16299, "text": "# Create spark sessionspark = (SparkSession .builder .appName(\"Sparkify\") .getOrCreate())# Read in full sparkify datasetevent_data = \"s3n://dsnd-sparkify/sparkify_event_data.json\"events = spark.read.json(event_data)" }, { "code": null, "e": 16630, "s": 16539, "text": "We will not repeat the steps again β€” I have attached the full script on the nbviewer site." }, { "code": null, "e": 16732, "s": 16630, "text": "Eventually, the gradient boosting model produced an F1 score of 0.8896, which is a great performance." }, { "code": null, "e": 16829, "s": 16732, "text": "+-----+----+---+|label| 0.0|1.0|+-----+----+---+| 0|1612| 70|| 1| 163|344|+-----+----+---+" }, { "code": null, "e": 16847, "s": 16829, "text": "Business Strategy" }, { "code": null, "e": 17232, "s": 16847, "text": "What a journey we have been through β€” but we have not finished our mission yet. In the data science world, there is a business intention behind every model. With the feature importance we produced, we could definitely come up with some business strategies to counter customer churns. We will briefly discuss two possible strategies that will truly drive some values for our providers." }, { "code": null, "e": 17446, "s": 17232, "text": "We know that the number of active days is the most significant factor, we could advise the upper management to construct a reward system to encourage low activity users to stay online for extended periods of time." }, { "code": null, "e": 17660, "s": 17446, "text": "In addition, since the agents that users used to access the service is also quite significant, we could also find out the poor-performing agent and get our engineering team to work specifically to solve the issue." }, { "code": null, "e": 17964, "s": 17660, "text": "I hope you have enjoyed reading this post as much as I enjoy writing it. Together, we used Spark, the big data analytics framework, to build an end-to-end machine learning workflow to identify potential customer churning for music streaming services from the user logs. We performed the following steps," }, { "code": null, "e": 18073, "s": 17964, "text": "Exploratory Data AnalysisFeature EngineeringModel BuildingModel EvaluationsModel Scale UpBusiness Strategies" }, { "code": null, "e": 18099, "s": 18073, "text": "Exploratory Data Analysis" }, { "code": null, "e": 18119, "s": 18099, "text": "Feature Engineering" }, { "code": null, "e": 18134, "s": 18119, "text": "Model Building" }, { "code": null, "e": 18152, "s": 18134, "text": "Model Evaluations" }, { "code": null, "e": 18167, "s": 18152, "text": "Model Scale Up" }, { "code": null, "e": 18187, "s": 18167, "text": "Business Strategies" }, { "code": null, "e": 18550, "s": 18187, "text": "Due to the sheer size of the data we are working with, performing hyperparameters search has been particularly difficult. One could imagine leaving the notebook open for extended periods of time would not be the most efficient way to use our resources. Some of the nice tricks in using ssh to keep the program running could definitely help tackle this challenge." } ]
C# | Boolean.ToString() Method - GeeksforGeeks
04 Oct, 2021 This method is used to convert the value of this instance to its equivalent string representation i.e. either β€œTrue” or β€œFalse”. Syntax: public override string ToString (); Return Value: This method returns β€œTrue” (the value of the TrueString property) if the value of this instance is true, or β€œFalse” (the value of the FalseString property) if the value of this instance is false. Below programs illustrate the use of Boolean.ToString() Method: Example 1: C# // C# program to demonstrate// Boolean.ToString()// Methodusing System; class GFG { // Main Method public static void Main() { // initializing the bool variables bool cat = false; bool dog = true; // getting the value of string property string value1 = cat.ToString(); string value2 = dog.ToString(); // print the string property Console.WriteLine("cat.ToString() returns {0}", value1); Console.WriteLine("dog.ToString() returns {0}", value2); }} cat.ToString() returns False dog.ToString() returns True Example 2: C# // C# program to demonstrate// Boolean.ToString()// Methodusing System; class GFG { // Main Method public static void Main() { // initializing the bool variables bool alpha = false; bool beta = true; bool gamma = true; bool delta = false; bool theta = true; // calling getValue() method getValue(alpha); getValue(beta); getValue(gamma); getValue(delta); getValue(theta); } // defining getValue() method public static void getValue(bool variable) { // getting the value of string property string value = variable.ToString(); // print the string property Console.WriteLine("{0}", value); }} False True True False True Note: XML is case-sensitive, and that the XML specification recognizes β€œtrue” and β€œfalse” as the valid set of Boolean values. If the string returned by the ToString() method is to be written to an XML file, its String.ToLowerInvariant method should be called first to convert it to lowercase. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.boolean.tostring?view=netframework-4.7.2#System_Boolean_ToString rajeev0719singh sagartomar9927 CSharp Boolean Struct CSharp-method 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# Extension Method in C# C# | Class and Object C# | Constructors Introduction to .NET Framework C# | Data Types
[ { "code": null, "e": 25757, "s": 25729, "text": "\n04 Oct, 2021" }, { "code": null, "e": 25886, "s": 25757, "text": "This method is used to convert the value of this instance to its equivalent string representation i.e. either β€œTrue” or β€œFalse”." }, { "code": null, "e": 25894, "s": 25886, "text": "Syntax:" }, { "code": null, "e": 25930, "s": 25894, "text": "public override string ToString ();" }, { "code": null, "e": 26140, "s": 25930, "text": "Return Value: This method returns β€œTrue” (the value of the TrueString property) if the value of this instance is true, or β€œFalse” (the value of the FalseString property) if the value of this instance is false." }, { "code": null, "e": 26204, "s": 26140, "text": "Below programs illustrate the use of Boolean.ToString() Method:" }, { "code": null, "e": 26216, "s": 26204, "text": "Example 1: " }, { "code": null, "e": 26219, "s": 26216, "text": "C#" }, { "code": "// C# program to demonstrate// Boolean.ToString()// Methodusing System; class GFG { // Main Method public static void Main() { // initializing the bool variables bool cat = false; bool dog = true; // getting the value of string property string value1 = cat.ToString(); string value2 = dog.ToString(); // print the string property Console.WriteLine(\"cat.ToString() returns {0}\", value1); Console.WriteLine(\"dog.ToString() returns {0}\", value2); }}", "e": 26745, "s": 26219, "text": null }, { "code": null, "e": 26802, "s": 26745, "text": "cat.ToString() returns False\ndog.ToString() returns True" }, { "code": null, "e": 26815, "s": 26804, "text": "Example 2:" }, { "code": null, "e": 26818, "s": 26815, "text": "C#" }, { "code": "// C# program to demonstrate// Boolean.ToString()// Methodusing System; class GFG { // Main Method public static void Main() { // initializing the bool variables bool alpha = false; bool beta = true; bool gamma = true; bool delta = false; bool theta = true; // calling getValue() method getValue(alpha); getValue(beta); getValue(gamma); getValue(delta); getValue(theta); } // defining getValue() method public static void getValue(bool variable) { // getting the value of string property string value = variable.ToString(); // print the string property Console.WriteLine(\"{0}\", value); }}", "e": 27549, "s": 26818, "text": null }, { "code": null, "e": 27576, "s": 27549, "text": "False\nTrue\nTrue\nFalse\nTrue" }, { "code": null, "e": 27871, "s": 27578, "text": "Note: XML is case-sensitive, and that the XML specification recognizes β€œtrue” and β€œfalse” as the valid set of Boolean values. If the string returned by the ToString() method is to be written to an XML file, its String.ToLowerInvariant method should be called first to convert it to lowercase." }, { "code": null, "e": 27883, "s": 27871, "text": "Reference: " }, { "code": null, "e": 27999, "s": 27883, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.boolean.tostring?view=netframework-4.7.2#System_Boolean_ToString" }, { "code": null, "e": 28015, "s": 27999, "text": "rajeev0719singh" }, { "code": null, "e": 28030, "s": 28015, "text": "sagartomar9927" }, { "code": null, "e": 28052, "s": 28030, "text": "CSharp Boolean Struct" }, { "code": null, "e": 28066, "s": 28052, "text": "CSharp-method" }, { "code": null, "e": 28069, "s": 28066, "text": "C#" }, { "code": null, "e": 28167, "s": 28069, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28195, "s": 28167, "text": "C# Dictionary with examples" }, { "code": null, "e": 28210, "s": 28195, "text": "C# | Delegates" }, { "code": null, "e": 28233, "s": 28210, "text": "C# | Method Overriding" }, { "code": null, "e": 28255, "s": 28233, "text": "C# | Abstract Classes" }, { "code": null, "e": 28301, "s": 28255, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 28324, "s": 28301, "text": "Extension Method in C#" }, { "code": null, "e": 28346, "s": 28324, "text": "C# | Class and Object" }, { "code": null, "e": 28364, "s": 28346, "text": "C# | Constructors" }, { "code": null, "e": 28395, "s": 28364, "text": "Introduction to .NET Framework" } ]
Integer toString() in Java
05 Dec, 2018 The java.lang.Integer.toString() is an inbuilt method in Java which is used to return the String object representing this Integer’s value.Syntax :public static String toString()Parameters: The method does not accept any parameters.Return Value:The method returns the string object of the particular Integer value.Below program illustrates the Java.lang.Integer.toString() method:// Java program to illustrate the// toString() Methodimport java.lang.*; public class Geeks{ public static void main(String[] args) { Integer obj = new Integer(8); //It will return a string representation String stringvalue1 = obj.toString(); System.out.println("String Value= " + stringvalue1); Integer obj3 = new Integer(10); //It will return a string representation String stringvalue3 = obj3.toString(); System.out.println("String Value = " + stringvalue3); }}Output:String Value= 8 String Value = 10 The java.lang.Integer.toString(int a) is an inbuilt method in Java which is used to return a String object, representing the specified integer in the parameter.Syntax :public static String toString(int a)Parameters: The method accepts one parameter a of integer type and refers to the integer needed to be converted to string.Return Value: The method returns the string representation of the argument in a particular base.Examples:For base 8: Input: int a = 75 Output: "75" For base 10: Input: int a = -787 Output: "-787" Below programs illustrate the Java.lang.Integer.toString(int a) method:Program 1:// Java program to illustrate the// toString(int a) methodimport java.lang.*; public class Geeks{ public static void main(String[] args) { Integer obj = new Integer(8); // It will return a string representation // in base 8 String stringvalue1 = obj.toString(75); System.out.println("String Value = " + stringvalue1); Integer obj2 = new Integer(8); // It will return a string representation // in base 2 String stringvalue2 = obj2.toString(6787); System.out.println("String Value = " + stringvalue2); Integer obj3 = new Integer(10); // It will return a string representation // in base 10 String stringvalue3 = obj3.toString(-787); System.out.println("String Value = " + stringvalue3); }} Output:String Value = 75 String Value = 6787 String Value = -787 Program 2: For decimal and string parameters.Note: This results in an error and as well for the absence of suitable Integer constructor.// Java program to illustrate the// Java.lang.Integer.toString(int a)methodimport java.lang.*;public class Geeks{ public static void main(String[] args) { Integer obj = new Integer(8); String stringvalue1 = obj.toString(58.5); System.out.println("String Value = " + stringvalue1); Integer obj2 = new Integer(8); String stringvalue2 = obj2.toString("317"); System.out.println("String Value = " + stringvalue2); // Empty constructor will result in an error Integer obj3 = new Integer(); String stringvalue3 = obj3.toString(-787); System.out.println("String Value = " + stringvalue3); }} Output:prog.java:8: error: incompatible types: possible lossy conversion from double to int String stringvalue1 = obj.toString(58.5); ^ prog.java:12: error: incompatible types: String cannot be converted to int String stringvalue2 = obj2.toString("317"); ^ prog.java:17: error: no suitable constructor found for Integer(no arguments) Integer obj3 = new Integer(); ^ constructor Integer.Integer(int) is not applicable (actual and formal argument lists differ in length) constructor Integer.Integer(String) is not applicable (actual and formal argument lists differ in length) Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output 3 errorsThe java.lang.Integer.toString(int a, int base) is an inbuilt method in Java which is used to return a string representation of the argument a in the base, specified by the second argument base. If the radix/base is smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX, then the base 10 is used. The ASCII characters which are used as digits: 0 to 9 and a to z.Syntax:public static String toString(int a, int base)Parameter: The method accepts two parameters:a: This is of integer type and refers to the integer value that is to be converted.base: This is also of integer type and refers to the base that is to be used while representing the strings.Return Value: The method returns a string representation of the specified argument in the specified base.Examples:Input: a = 71, base = 2 Output: 1000111 Input: a = 314, base = 16 Output: 13a Below programs illustrate the Java.lang.Integer.toString(int a, int base) Method:Program 1:// Java program to illustrate the// toString(int, int) Methodimport java.lang.*; public class Geeks{ public static void main(String[] args) { Integer a = new Integer(10); // It returns a string representation // in base 2 String returnvalue = a.toString(5254, 2); System.out.println("String Value = " + returnvalue); // It returns a string representation // in base 8 returnvalue = a.toString(35, 8); System.out.println("String Value = " + returnvalue); // It returns a string representation // in base 16 returnvalue = a.toString(47, 16); System.out.println("String Value = " + returnvalue); // It returns a string representation // in base 10 returnvalue = a.toString(451, 10); System.out.println("String Value = " + returnvalue);}} Output:String Value = 1010010000110 String Value = 43 String Value = 2f String Value = 451 Program 2:// Java program to illustrate the// toString(int, int) Methodimport java.lang.*; public class Geeks{ public static void main(String[] args) { Integer a = new Integer(10); // It returns a string representation // in base 2 String returnvalue = a.toString(-525, 2); System.out.println("String Value = " + returnvalue); // It returns a string representation // in base 8 returnvalue = a.toString(31, 8); System.out.println("String Value = " + returnvalue); // It returns a string representation // in base 16 returnvalue = a.toString(28, 16); System.out.println("String Value = " + returnvalue); // It returns a string representation // in base 10 returnvalue = a.toString(29, 10); System.out.println("String Value = " + returnvalue);}} Output:String Value = -1000001101 String Value = 37 String Value = 1c String Value = 29 My Personal Notes arrow_drop_upSave The java.lang.Integer.toString() is an inbuilt method in Java which is used to return the String object representing this Integer’s value.Syntax :public static String toString()Parameters: The method does not accept any parameters.Return Value:The method returns the string object of the particular Integer value.Below program illustrates the Java.lang.Integer.toString() method:// Java program to illustrate the// toString() Methodimport java.lang.*; public class Geeks{ public static void main(String[] args) { Integer obj = new Integer(8); //It will return a string representation String stringvalue1 = obj.toString(); System.out.println("String Value= " + stringvalue1); Integer obj3 = new Integer(10); //It will return a string representation String stringvalue3 = obj3.toString(); System.out.println("String Value = " + stringvalue3); }}Output:String Value= 8 String Value = 10 Syntax : public static String toString() Parameters: The method does not accept any parameters. Return Value:The method returns the string object of the particular Integer value. Below program illustrates the Java.lang.Integer.toString() method: // Java program to illustrate the// toString() Methodimport java.lang.*; public class Geeks{ public static void main(String[] args) { Integer obj = new Integer(8); //It will return a string representation String stringvalue1 = obj.toString(); System.out.println("String Value= " + stringvalue1); Integer obj3 = new Integer(10); //It will return a string representation String stringvalue3 = obj3.toString(); System.out.println("String Value = " + stringvalue3); }} String Value= 8 String Value = 10 The java.lang.Integer.toString(int a) is an inbuilt method in Java which is used to return a String object, representing the specified integer in the parameter.Syntax :public static String toString(int a)Parameters: The method accepts one parameter a of integer type and refers to the integer needed to be converted to string.Return Value: The method returns the string representation of the argument in a particular base.Examples:For base 8: Input: int a = 75 Output: "75" For base 10: Input: int a = -787 Output: "-787" Below programs illustrate the Java.lang.Integer.toString(int a) method:Program 1:// Java program to illustrate the// toString(int a) methodimport java.lang.*; public class Geeks{ public static void main(String[] args) { Integer obj = new Integer(8); // It will return a string representation // in base 8 String stringvalue1 = obj.toString(75); System.out.println("String Value = " + stringvalue1); Integer obj2 = new Integer(8); // It will return a string representation // in base 2 String stringvalue2 = obj2.toString(6787); System.out.println("String Value = " + stringvalue2); Integer obj3 = new Integer(10); // It will return a string representation // in base 10 String stringvalue3 = obj3.toString(-787); System.out.println("String Value = " + stringvalue3); }} Output:String Value = 75 String Value = 6787 String Value = -787 Program 2: For decimal and string parameters.Note: This results in an error and as well for the absence of suitable Integer constructor.// Java program to illustrate the// Java.lang.Integer.toString(int a)methodimport java.lang.*;public class Geeks{ public static void main(String[] args) { Integer obj = new Integer(8); String stringvalue1 = obj.toString(58.5); System.out.println("String Value = " + stringvalue1); Integer obj2 = new Integer(8); String stringvalue2 = obj2.toString("317"); System.out.println("String Value = " + stringvalue2); // Empty constructor will result in an error Integer obj3 = new Integer(); String stringvalue3 = obj3.toString(-787); System.out.println("String Value = " + stringvalue3); }} Output:prog.java:8: error: incompatible types: possible lossy conversion from double to int String stringvalue1 = obj.toString(58.5); ^ prog.java:12: error: incompatible types: String cannot be converted to int String stringvalue2 = obj2.toString("317"); ^ prog.java:17: error: no suitable constructor found for Integer(no arguments) Integer obj3 = new Integer(); ^ constructor Integer.Integer(int) is not applicable (actual and formal argument lists differ in length) constructor Integer.Integer(String) is not applicable (actual and formal argument lists differ in length) Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output 3 errors public static String toString(int a) Parameters: The method accepts one parameter a of integer type and refers to the integer needed to be converted to string. Return Value: The method returns the string representation of the argument in a particular base. Examples: For base 8: Input: int a = 75 Output: "75" For base 10: Input: int a = -787 Output: "-787" Below programs illustrate the Java.lang.Integer.toString(int a) method:Program 1: // Java program to illustrate the// toString(int a) methodimport java.lang.*; public class Geeks{ public static void main(String[] args) { Integer obj = new Integer(8); // It will return a string representation // in base 8 String stringvalue1 = obj.toString(75); System.out.println("String Value = " + stringvalue1); Integer obj2 = new Integer(8); // It will return a string representation // in base 2 String stringvalue2 = obj2.toString(6787); System.out.println("String Value = " + stringvalue2); Integer obj3 = new Integer(10); // It will return a string representation // in base 10 String stringvalue3 = obj3.toString(-787); System.out.println("String Value = " + stringvalue3); }} String Value = 75 String Value = 6787 String Value = -787 Program 2: For decimal and string parameters.Note: This results in an error and as well for the absence of suitable Integer constructor. // Java program to illustrate the// Java.lang.Integer.toString(int a)methodimport java.lang.*;public class Geeks{ public static void main(String[] args) { Integer obj = new Integer(8); String stringvalue1 = obj.toString(58.5); System.out.println("String Value = " + stringvalue1); Integer obj2 = new Integer(8); String stringvalue2 = obj2.toString("317"); System.out.println("String Value = " + stringvalue2); // Empty constructor will result in an error Integer obj3 = new Integer(); String stringvalue3 = obj3.toString(-787); System.out.println("String Value = " + stringvalue3); }} Output: prog.java:8: error: incompatible types: possible lossy conversion from double to int String stringvalue1 = obj.toString(58.5); ^ prog.java:12: error: incompatible types: String cannot be converted to int String stringvalue2 = obj2.toString("317"); ^ prog.java:17: error: no suitable constructor found for Integer(no arguments) Integer obj3 = new Integer(); ^ constructor Integer.Integer(int) is not applicable (actual and formal argument lists differ in length) constructor Integer.Integer(String) is not applicable (actual and formal argument lists differ in length) Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output 3 errors The java.lang.Integer.toString(int a, int base) is an inbuilt method in Java which is used to return a string representation of the argument a in the base, specified by the second argument base. If the radix/base is smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX, then the base 10 is used. The ASCII characters which are used as digits: 0 to 9 and a to z.Syntax:public static String toString(int a, int base)Parameter: The method accepts two parameters:a: This is of integer type and refers to the integer value that is to be converted.base: This is also of integer type and refers to the base that is to be used while representing the strings.Return Value: The method returns a string representation of the specified argument in the specified base.Examples:Input: a = 71, base = 2 Output: 1000111 Input: a = 314, base = 16 Output: 13a Below programs illustrate the Java.lang.Integer.toString(int a, int base) Method:Program 1:// Java program to illustrate the// toString(int, int) Methodimport java.lang.*; public class Geeks{ public static void main(String[] args) { Integer a = new Integer(10); // It returns a string representation // in base 2 String returnvalue = a.toString(5254, 2); System.out.println("String Value = " + returnvalue); // It returns a string representation // in base 8 returnvalue = a.toString(35, 8); System.out.println("String Value = " + returnvalue); // It returns a string representation // in base 16 returnvalue = a.toString(47, 16); System.out.println("String Value = " + returnvalue); // It returns a string representation // in base 10 returnvalue = a.toString(451, 10); System.out.println("String Value = " + returnvalue);}} Output:String Value = 1010010000110 String Value = 43 String Value = 2f String Value = 451 Program 2:// Java program to illustrate the// toString(int, int) Methodimport java.lang.*; public class Geeks{ public static void main(String[] args) { Integer a = new Integer(10); // It returns a string representation // in base 2 String returnvalue = a.toString(-525, 2); System.out.println("String Value = " + returnvalue); // It returns a string representation // in base 8 returnvalue = a.toString(31, 8); System.out.println("String Value = " + returnvalue); // It returns a string representation // in base 16 returnvalue = a.toString(28, 16); System.out.println("String Value = " + returnvalue); // It returns a string representation // in base 10 returnvalue = a.toString(29, 10); System.out.println("String Value = " + returnvalue);}} Output:String Value = -1000001101 String Value = 37 String Value = 1c String Value = 29 My Personal Notes arrow_drop_upSave public static String toString(int a, int base) Parameter: The method accepts two parameters: a: This is of integer type and refers to the integer value that is to be converted. base: This is also of integer type and refers to the base that is to be used while representing the strings. Return Value: The method returns a string representation of the specified argument in the specified base. Examples: Input: a = 71, base = 2 Output: 1000111 Input: a = 314, base = 16 Output: 13a Below programs illustrate the Java.lang.Integer.toString(int a, int base) Method:Program 1: // Java program to illustrate the// toString(int, int) Methodimport java.lang.*; public class Geeks{ public static void main(String[] args) { Integer a = new Integer(10); // It returns a string representation // in base 2 String returnvalue = a.toString(5254, 2); System.out.println("String Value = " + returnvalue); // It returns a string representation // in base 8 returnvalue = a.toString(35, 8); System.out.println("String Value = " + returnvalue); // It returns a string representation // in base 16 returnvalue = a.toString(47, 16); System.out.println("String Value = " + returnvalue); // It returns a string representation // in base 10 returnvalue = a.toString(451, 10); System.out.println("String Value = " + returnvalue);}} String Value = 1010010000110 String Value = 43 String Value = 2f String Value = 451 Program 2: // Java program to illustrate the// toString(int, int) Methodimport java.lang.*; public class Geeks{ public static void main(String[] args) { Integer a = new Integer(10); // It returns a string representation // in base 2 String returnvalue = a.toString(-525, 2); System.out.println("String Value = " + returnvalue); // It returns a string representation // in base 8 returnvalue = a.toString(31, 8); System.out.println("String Value = " + returnvalue); // It returns a string representation // in base 16 returnvalue = a.toString(28, 16); System.out.println("String Value = " + returnvalue); // It returns a string representation // in base 10 returnvalue = a.toString(29, 10); System.out.println("String Value = " + returnvalue);}} String Value = -1000001101 String Value = 37 String Value = 1c String Value = 29 Java-Functions Java-Integer Java-lang package 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": "\n05 Dec, 2018" }, { "code": null, "e": 7312, "s": 28, "text": "The java.lang.Integer.toString() is an inbuilt method in Java which is used to return the String object representing this Integer’s value.Syntax :public static String toString()Parameters: The method does not accept any parameters.Return Value:The method returns the string object of the particular Integer value.Below program illustrates the Java.lang.Integer.toString() method:// Java program to illustrate the// toString() Methodimport java.lang.*; public class Geeks{ public static void main(String[] args) { Integer obj = new Integer(8); //It will return a string representation String stringvalue1 = obj.toString(); System.out.println(\"String Value= \" + stringvalue1); Integer obj3 = new Integer(10); //It will return a string representation String stringvalue3 = obj3.toString(); System.out.println(\"String Value = \" + stringvalue3); }}Output:String Value= 8\nString Value = 10\nThe java.lang.Integer.toString(int a) is an inbuilt method in Java which is used to return a String object, representing the specified integer in the parameter.Syntax :public static String toString(int a)Parameters: The method accepts one parameter a of integer type and refers to the integer needed to be converted to string.Return Value: The method returns the string representation of the argument in a particular base.Examples:For base 8: \nInput: int a = 75 \nOutput: \"75\"\n\nFor base 10:\nInput: int a = -787 \nOutput: \"-787\"\nBelow programs illustrate the Java.lang.Integer.toString(int a) method:Program 1:// Java program to illustrate the// toString(int a) methodimport java.lang.*; public class Geeks{ public static void main(String[] args) { Integer obj = new Integer(8); // It will return a string representation // in base 8 String stringvalue1 = obj.toString(75); System.out.println(\"String Value = \" + stringvalue1); Integer obj2 = new Integer(8); // It will return a string representation // in base 2 String stringvalue2 = obj2.toString(6787); System.out.println(\"String Value = \" + stringvalue2); Integer obj3 = new Integer(10); // It will return a string representation // in base 10 String stringvalue3 = obj3.toString(-787); System.out.println(\"String Value = \" + stringvalue3); }} Output:String Value = 75\nString Value = 6787\nString Value = -787\nProgram 2: For decimal and string parameters.Note: This results in an error and as well for the absence of suitable Integer constructor.// Java program to illustrate the// Java.lang.Integer.toString(int a)methodimport java.lang.*;public class Geeks{ public static void main(String[] args) { Integer obj = new Integer(8); String stringvalue1 = obj.toString(58.5); System.out.println(\"String Value = \" + stringvalue1); Integer obj2 = new Integer(8); String stringvalue2 = obj2.toString(\"317\"); System.out.println(\"String Value = \" + stringvalue2); // Empty constructor will result in an error Integer obj3 = new Integer(); String stringvalue3 = obj3.toString(-787); System.out.println(\"String Value = \" + stringvalue3); }} Output:prog.java:8: error: incompatible types: possible \nlossy conversion from double to int\n String stringvalue1 = obj.toString(58.5);\n ^\nprog.java:12: error: incompatible types: String cannot \nbe converted to int\n String stringvalue2 = obj2.toString(\"317\");\n ^\nprog.java:17: error: no suitable constructor found for \nInteger(no arguments)\n Integer obj3 = new Integer();\n ^\n constructor Integer.Integer(int) is not applicable\n (actual and formal argument lists differ in length)\n constructor Integer.Integer(String) is not applicable\n (actual and formal argument lists differ in length)\nNote: Some messages have been simplified; recompile with \n-Xdiags:verbose to get full output\n3 errorsThe java.lang.Integer.toString(int a, int base) is an inbuilt method in Java which is used to return a string representation of the argument a in the base, specified by the second argument base. If the radix/base is smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX, then the base 10 is used. The ASCII characters which are used as digits: 0 to 9 and a to z.Syntax:public static String toString(int a, int base)Parameter: The method accepts two parameters:a: This is of integer type and refers to the integer value that is to be converted.base: This is also of integer type and refers to the base that is to be used while representing the strings.Return Value: The method returns a string representation of the specified argument in the specified base.Examples:Input: a = 71, base = 2\nOutput: 1000111\n\nInput: a = 314, base = 16\nOutput: 13a\nBelow programs illustrate the Java.lang.Integer.toString(int a, int base) Method:Program 1:// Java program to illustrate the// toString(int, int) Methodimport java.lang.*; public class Geeks{ public static void main(String[] args) { Integer a = new Integer(10); // It returns a string representation // in base 2 String returnvalue = a.toString(5254, 2); System.out.println(\"String Value = \" + returnvalue); // It returns a string representation // in base 8 returnvalue = a.toString(35, 8); System.out.println(\"String Value = \" + returnvalue); // It returns a string representation // in base 16 returnvalue = a.toString(47, 16); System.out.println(\"String Value = \" + returnvalue); // It returns a string representation // in base 10 returnvalue = a.toString(451, 10); System.out.println(\"String Value = \" + returnvalue);}} Output:String Value = 1010010000110\nString Value = 43\nString Value = 2f\nString Value = 451\nProgram 2:// Java program to illustrate the// toString(int, int) Methodimport java.lang.*; public class Geeks{ public static void main(String[] args) { Integer a = new Integer(10); // It returns a string representation // in base 2 String returnvalue = a.toString(-525, 2); System.out.println(\"String Value = \" + returnvalue); // It returns a string representation // in base 8 returnvalue = a.toString(31, 8); System.out.println(\"String Value = \" + returnvalue); // It returns a string representation // in base 16 returnvalue = a.toString(28, 16); System.out.println(\"String Value = \" + returnvalue); // It returns a string representation // in base 10 returnvalue = a.toString(29, 10); System.out.println(\"String Value = \" + returnvalue);}} Output:String Value = -1000001101\nString Value = 37\nString Value = 1c\nString Value = 29\nMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 8320, "s": 7312, "text": "The java.lang.Integer.toString() is an inbuilt method in Java which is used to return the String object representing this Integer’s value.Syntax :public static String toString()Parameters: The method does not accept any parameters.Return Value:The method returns the string object of the particular Integer value.Below program illustrates the Java.lang.Integer.toString() method:// Java program to illustrate the// toString() Methodimport java.lang.*; public class Geeks{ public static void main(String[] args) { Integer obj = new Integer(8); //It will return a string representation String stringvalue1 = obj.toString(); System.out.println(\"String Value= \" + stringvalue1); Integer obj3 = new Integer(10); //It will return a string representation String stringvalue3 = obj3.toString(); System.out.println(\"String Value = \" + stringvalue3); }}Output:String Value= 8\nString Value = 10\n" }, { "code": null, "e": 8329, "s": 8320, "text": "Syntax :" }, { "code": null, "e": 8361, "s": 8329, "text": "public static String toString()" }, { "code": null, "e": 8416, "s": 8361, "text": "Parameters: The method does not accept any parameters." }, { "code": null, "e": 8499, "s": 8416, "text": "Return Value:The method returns the string object of the particular Integer value." }, { "code": null, "e": 8566, "s": 8499, "text": "Below program illustrates the Java.lang.Integer.toString() method:" }, { "code": "// Java program to illustrate the// toString() Methodimport java.lang.*; public class Geeks{ public static void main(String[] args) { Integer obj = new Integer(8); //It will return a string representation String stringvalue1 = obj.toString(); System.out.println(\"String Value= \" + stringvalue1); Integer obj3 = new Integer(10); //It will return a string representation String stringvalue3 = obj3.toString(); System.out.println(\"String Value = \" + stringvalue3); }}", "e": 9154, "s": 8566, "text": null }, { "code": null, "e": 9189, "s": 9154, "text": "String Value= 8\nString Value = 10\n" }, { "code": null, "e": 12418, "s": 9189, "text": "The java.lang.Integer.toString(int a) is an inbuilt method in Java which is used to return a String object, representing the specified integer in the parameter.Syntax :public static String toString(int a)Parameters: The method accepts one parameter a of integer type and refers to the integer needed to be converted to string.Return Value: The method returns the string representation of the argument in a particular base.Examples:For base 8: \nInput: int a = 75 \nOutput: \"75\"\n\nFor base 10:\nInput: int a = -787 \nOutput: \"-787\"\nBelow programs illustrate the Java.lang.Integer.toString(int a) method:Program 1:// Java program to illustrate the// toString(int a) methodimport java.lang.*; public class Geeks{ public static void main(String[] args) { Integer obj = new Integer(8); // It will return a string representation // in base 8 String stringvalue1 = obj.toString(75); System.out.println(\"String Value = \" + stringvalue1); Integer obj2 = new Integer(8); // It will return a string representation // in base 2 String stringvalue2 = obj2.toString(6787); System.out.println(\"String Value = \" + stringvalue2); Integer obj3 = new Integer(10); // It will return a string representation // in base 10 String stringvalue3 = obj3.toString(-787); System.out.println(\"String Value = \" + stringvalue3); }} Output:String Value = 75\nString Value = 6787\nString Value = -787\nProgram 2: For decimal and string parameters.Note: This results in an error and as well for the absence of suitable Integer constructor.// Java program to illustrate the// Java.lang.Integer.toString(int a)methodimport java.lang.*;public class Geeks{ public static void main(String[] args) { Integer obj = new Integer(8); String stringvalue1 = obj.toString(58.5); System.out.println(\"String Value = \" + stringvalue1); Integer obj2 = new Integer(8); String stringvalue2 = obj2.toString(\"317\"); System.out.println(\"String Value = \" + stringvalue2); // Empty constructor will result in an error Integer obj3 = new Integer(); String stringvalue3 = obj3.toString(-787); System.out.println(\"String Value = \" + stringvalue3); }} Output:prog.java:8: error: incompatible types: possible \nlossy conversion from double to int\n String stringvalue1 = obj.toString(58.5);\n ^\nprog.java:12: error: incompatible types: String cannot \nbe converted to int\n String stringvalue2 = obj2.toString(\"317\");\n ^\nprog.java:17: error: no suitable constructor found for \nInteger(no arguments)\n Integer obj3 = new Integer();\n ^\n constructor Integer.Integer(int) is not applicable\n (actual and formal argument lists differ in length)\n constructor Integer.Integer(String) is not applicable\n (actual and formal argument lists differ in length)\nNote: Some messages have been simplified; recompile with \n-Xdiags:verbose to get full output\n3 errors" }, { "code": null, "e": 12455, "s": 12418, "text": "public static String toString(int a)" }, { "code": null, "e": 12578, "s": 12455, "text": "Parameters: The method accepts one parameter a of integer type and refers to the integer needed to be converted to string." }, { "code": null, "e": 12675, "s": 12578, "text": "Return Value: The method returns the string representation of the argument in a particular base." }, { "code": null, "e": 12685, "s": 12675, "text": "Examples:" }, { "code": null, "e": 12781, "s": 12685, "text": "For base 8: \nInput: int a = 75 \nOutput: \"75\"\n\nFor base 10:\nInput: int a = -787 \nOutput: \"-787\"\n" }, { "code": null, "e": 12863, "s": 12781, "text": "Below programs illustrate the Java.lang.Integer.toString(int a) method:Program 1:" }, { "code": "// Java program to illustrate the// toString(int a) methodimport java.lang.*; public class Geeks{ public static void main(String[] args) { Integer obj = new Integer(8); // It will return a string representation // in base 8 String stringvalue1 = obj.toString(75); System.out.println(\"String Value = \" + stringvalue1); Integer obj2 = new Integer(8); // It will return a string representation // in base 2 String stringvalue2 = obj2.toString(6787); System.out.println(\"String Value = \" + stringvalue2); Integer obj3 = new Integer(10); // It will return a string representation // in base 10 String stringvalue3 = obj3.toString(-787); System.out.println(\"String Value = \" + stringvalue3); }} ", "e": 13744, "s": 12863, "text": null }, { "code": null, "e": 13803, "s": 13744, "text": "String Value = 75\nString Value = 6787\nString Value = -787\n" }, { "code": null, "e": 13940, "s": 13803, "text": "Program 2: For decimal and string parameters.Note: This results in an error and as well for the absence of suitable Integer constructor." }, { "code": "// Java program to illustrate the// Java.lang.Integer.toString(int a)methodimport java.lang.*;public class Geeks{ public static void main(String[] args) { Integer obj = new Integer(8); String stringvalue1 = obj.toString(58.5); System.out.println(\"String Value = \" + stringvalue1); Integer obj2 = new Integer(8); String stringvalue2 = obj2.toString(\"317\"); System.out.println(\"String Value = \" + stringvalue2); // Empty constructor will result in an error Integer obj3 = new Integer(); String stringvalue3 = obj3.toString(-787); System.out.println(\"String Value = \" + stringvalue3); }} ", "e": 14672, "s": 13940, "text": null }, { "code": null, "e": 14680, "s": 14672, "text": "Output:" }, { "code": null, "e": 15483, "s": 14680, "text": "prog.java:8: error: incompatible types: possible \nlossy conversion from double to int\n String stringvalue1 = obj.toString(58.5);\n ^\nprog.java:12: error: incompatible types: String cannot \nbe converted to int\n String stringvalue2 = obj2.toString(\"317\");\n ^\nprog.java:17: error: no suitable constructor found for \nInteger(no arguments)\n Integer obj3 = new Integer();\n ^\n constructor Integer.Integer(int) is not applicable\n (actual and formal argument lists differ in length)\n constructor Integer.Integer(String) is not applicable\n (actual and formal argument lists differ in length)\nNote: Some messages have been simplified; recompile with \n-Xdiags:verbose to get full output\n3 errors" }, { "code": null, "e": 18532, "s": 15483, "text": "The java.lang.Integer.toString(int a, int base) is an inbuilt method in Java which is used to return a string representation of the argument a in the base, specified by the second argument base. If the radix/base is smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX, then the base 10 is used. The ASCII characters which are used as digits: 0 to 9 and a to z.Syntax:public static String toString(int a, int base)Parameter: The method accepts two parameters:a: This is of integer type and refers to the integer value that is to be converted.base: This is also of integer type and refers to the base that is to be used while representing the strings.Return Value: The method returns a string representation of the specified argument in the specified base.Examples:Input: a = 71, base = 2\nOutput: 1000111\n\nInput: a = 314, base = 16\nOutput: 13a\nBelow programs illustrate the Java.lang.Integer.toString(int a, int base) Method:Program 1:// Java program to illustrate the// toString(int, int) Methodimport java.lang.*; public class Geeks{ public static void main(String[] args) { Integer a = new Integer(10); // It returns a string representation // in base 2 String returnvalue = a.toString(5254, 2); System.out.println(\"String Value = \" + returnvalue); // It returns a string representation // in base 8 returnvalue = a.toString(35, 8); System.out.println(\"String Value = \" + returnvalue); // It returns a string representation // in base 16 returnvalue = a.toString(47, 16); System.out.println(\"String Value = \" + returnvalue); // It returns a string representation // in base 10 returnvalue = a.toString(451, 10); System.out.println(\"String Value = \" + returnvalue);}} Output:String Value = 1010010000110\nString Value = 43\nString Value = 2f\nString Value = 451\nProgram 2:// Java program to illustrate the// toString(int, int) Methodimport java.lang.*; public class Geeks{ public static void main(String[] args) { Integer a = new Integer(10); // It returns a string representation // in base 2 String returnvalue = a.toString(-525, 2); System.out.println(\"String Value = \" + returnvalue); // It returns a string representation // in base 8 returnvalue = a.toString(31, 8); System.out.println(\"String Value = \" + returnvalue); // It returns a string representation // in base 16 returnvalue = a.toString(28, 16); System.out.println(\"String Value = \" + returnvalue); // It returns a string representation // in base 10 returnvalue = a.toString(29, 10); System.out.println(\"String Value = \" + returnvalue);}} Output:String Value = -1000001101\nString Value = 37\nString Value = 1c\nString Value = 29\nMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 18579, "s": 18532, "text": "public static String toString(int a, int base)" }, { "code": null, "e": 18625, "s": 18579, "text": "Parameter: The method accepts two parameters:" }, { "code": null, "e": 18709, "s": 18625, "text": "a: This is of integer type and refers to the integer value that is to be converted." }, { "code": null, "e": 18818, "s": 18709, "text": "base: This is also of integer type and refers to the base that is to be used while representing the strings." }, { "code": null, "e": 18924, "s": 18818, "text": "Return Value: The method returns a string representation of the specified argument in the specified base." }, { "code": null, "e": 18934, "s": 18924, "text": "Examples:" }, { "code": null, "e": 19014, "s": 18934, "text": "Input: a = 71, base = 2\nOutput: 1000111\n\nInput: a = 314, base = 16\nOutput: 13a\n" }, { "code": null, "e": 19106, "s": 19014, "text": "Below programs illustrate the Java.lang.Integer.toString(int a, int base) Method:Program 1:" }, { "code": "// Java program to illustrate the// toString(int, int) Methodimport java.lang.*; public class Geeks{ public static void main(String[] args) { Integer a = new Integer(10); // It returns a string representation // in base 2 String returnvalue = a.toString(5254, 2); System.out.println(\"String Value = \" + returnvalue); // It returns a string representation // in base 8 returnvalue = a.toString(35, 8); System.out.println(\"String Value = \" + returnvalue); // It returns a string representation // in base 16 returnvalue = a.toString(47, 16); System.out.println(\"String Value = \" + returnvalue); // It returns a string representation // in base 10 returnvalue = a.toString(451, 10); System.out.println(\"String Value = \" + returnvalue);}} ", "e": 20045, "s": 19106, "text": null }, { "code": null, "e": 20130, "s": 20045, "text": "String Value = 1010010000110\nString Value = 43\nString Value = 2f\nString Value = 451\n" }, { "code": null, "e": 20141, "s": 20130, "text": "Program 2:" }, { "code": "// Java program to illustrate the// toString(int, int) Methodimport java.lang.*; public class Geeks{ public static void main(String[] args) { Integer a = new Integer(10); // It returns a string representation // in base 2 String returnvalue = a.toString(-525, 2); System.out.println(\"String Value = \" + returnvalue); // It returns a string representation // in base 8 returnvalue = a.toString(31, 8); System.out.println(\"String Value = \" + returnvalue); // It returns a string representation // in base 16 returnvalue = a.toString(28, 16); System.out.println(\"String Value = \" + returnvalue); // It returns a string representation // in base 10 returnvalue = a.toString(29, 10); System.out.println(\"String Value = \" + returnvalue);}} ", "e": 21079, "s": 20141, "text": null }, { "code": null, "e": 21161, "s": 21079, "text": "String Value = -1000001101\nString Value = 37\nString Value = 1c\nString Value = 29\n" }, { "code": null, "e": 21176, "s": 21161, "text": "Java-Functions" }, { "code": null, "e": 21189, "s": 21176, "text": "Java-Integer" }, { "code": null, "e": 21207, "s": 21189, "text": "Java-lang package" }, { "code": null, "e": 21212, "s": 21207, "text": "Java" }, { "code": null, "e": 21217, "s": 21212, "text": "Java" } ]
Reverse a string in PL/SQL
29 Jun, 2018 Prerequisite – PL/SQL introduction In PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations. Given a string, the task is to reverse a string using PL/SQL. Examples: Input: skeegrofskeeg Output: geeksforgeeks Input: geeks Output: skeeg Approach: Find the length of the string. Then traverse the string in a reverse manner. Store the characters in another string. Print the final string. Below is the required implementation: DECLARE -- declare variable str , len -- and str1 of datatype varchar str VARCHAR(20) := 'skeegrofskeeg'; len NUMBER; str1 VARCHAR(20);BEGIN -- Here we find the length of string len := Length(str); -- here we starting a loop from max len to 1 FOR i IN REVERSE 1.. len LOOP -- assigning the reverse string in str1 str1 := str1 || Substr(str, i, 1); END LOOP; dbms_output.Put_line('Reverse of string is ' || str1);END;-- Program End Output : Reverse of string is geeksforgeeks SQL-PL/SQL SQL SQL 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, 2018" }, { "code": null, "e": 63, "s": 28, "text": "Prerequisite – PL/SQL introduction" }, { "code": null, "e": 273, "s": 63, "text": "In PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations." }, { "code": null, "e": 335, "s": 273, "text": "Given a string, the task is to reverse a string using PL/SQL." }, { "code": null, "e": 345, "s": 335, "text": "Examples:" }, { "code": null, "e": 417, "s": 345, "text": "Input: skeegrofskeeg\nOutput: geeksforgeeks\n\nInput: geeks\nOutput: skeeg\n" }, { "code": null, "e": 427, "s": 417, "text": "Approach:" }, { "code": null, "e": 458, "s": 427, "text": "Find the length of the string." }, { "code": null, "e": 504, "s": 458, "text": "Then traverse the string in a reverse manner." }, { "code": null, "e": 544, "s": 504, "text": "Store the characters in another string." }, { "code": null, "e": 568, "s": 544, "text": "Print the final string." }, { "code": null, "e": 606, "s": 568, "text": "Below is the required implementation:" }, { "code": "DECLARE -- declare variable str , len -- and str1 of datatype varchar str VARCHAR(20) := 'skeegrofskeeg'; len NUMBER; str1 VARCHAR(20);BEGIN -- Here we find the length of string len := Length(str); -- here we starting a loop from max len to 1 FOR i IN REVERSE 1.. len LOOP -- assigning the reverse string in str1 str1 := str1 || Substr(str, i, 1); END LOOP; dbms_output.Put_line('Reverse of string is ' || str1);END;-- Program End ", "e": 1146, "s": 606, "text": null }, { "code": null, "e": 1155, "s": 1146, "text": "Output :" }, { "code": null, "e": 1191, "s": 1155, "text": "Reverse of string is geeksforgeeks\n" }, { "code": null, "e": 1202, "s": 1191, "text": "SQL-PL/SQL" }, { "code": null, "e": 1206, "s": 1202, "text": "SQL" }, { "code": null, "e": 1210, "s": 1206, "text": "SQL" } ]
Parallel (Othographic & Oblique) Projection in Computer Graphics
15 Feb, 2022 Projection is a kind of phenomena that are used in computer graphics to map the view of a 3D object onto the projecting display panel where the viewing volume is specified by the world coordinate and then map these world coordinate over the view port. Projection is of the following kind : a) Parallel Projection b) Perspective Projection Parallel Projection : Parallel projection is a kind of projection where the projecting lines emerge parallelly from the polygon surface and then incident parallelly on the plane. In parallel projection, the centre of the projection lies at infinity. In parallel projection, the view of the object obtained at the plane is less-realistic as there is no for-shortcoming. and the relative dimension of the object remains preserves. Parallel projection is further divided into two categories : a) Orthographic Projection b) Oblique Projection (a) Orthographic Projection : It is a kind of parallel projection where the projecting lines emerge parallelly from the object surface and incident perpendicularly at the projecting plane. Orthographic Projection is of two categories : (a).1. Multiview Projection : It is further divided into three categories – (1) Top-View : In this projection, the rays that emerge from the top of the polygon surface are observed. 2) Side-View : It is another type of projection orthographic projection where the side view of the polygon surface is observed. 3) Front-view : In this orthographic projection front face view of the object is observed. a.2) Axonometric : Axonometric projection is an orthographic projection, where the projection lines are perpendicular to the plane of projection, and the object is rotated around one or more of its axes to show multiple sides. It is further divided into three categories : (1) Isometric Projection : It is a method for visually representing three-dimensional objects in two-dimensional display in technical and engineering drawings. Here in this projection, the three coordinate axes appear equally foreshortened and the angle between any two of them is 120 degrees. (2) Dimetric Projection : It is a kind of orthographic projection where the visualized object appears to have only two adjacent sides and angles are equal. (3) Trimetric Projection : It is a kind of orthographic projection where the visualized object appears to have all the adjacent sides and angles unequal. (b) Oblique Projection : It is a kind of parallel projection where projecting rays emerges parallelly from the surface of the polygon and incident at an angle other than 90 degrees on the plane. It is of two kinds : (b).1. Cavalier Projection : It is a kind of oblique projection where the projecting lines emerge parallelly from the object surface and incident at 45β€˜ rather than 90β€² at the projecting plane. In this projection, the length of the reading axis is larger than the cabinet projection. (b). 2. Cabinet Projection : It is similar to that cavalier projection but here the length of reading axes just half than the cavalier projection and the incident angle at the projecting plane is 63.4β€² rather 45β€². sagar0719kumar computer-graphics Software Engineering Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Software Engineering | Black box testing Unit Testing | Software Testing Difference Between Edge Computing and Fog Computing System Testing Software Engineering | Integration Testing Software Engineering | Calculation of Function Point (FP) What is DFD(Data Flow Diagram)? Software Development Life Cycle (SDLC) Software Processes in Software Engineering Software Engineering | Re-engineering
[ { "code": null, "e": 52, "s": 24, "text": "\n15 Feb, 2022" }, { "code": null, "e": 304, "s": 52, "text": "Projection is a kind of phenomena that are used in computer graphics to map the view of a 3D object onto the projecting display panel where the viewing volume is specified by the world coordinate and then map these world coordinate over the view port." }, { "code": null, "e": 343, "s": 304, "text": "Projection is of the following kind : " }, { "code": null, "e": 414, "s": 343, "text": " a) Parallel Projection b) Perspective Projection" }, { "code": null, "e": 843, "s": 414, "text": "Parallel Projection : Parallel projection is a kind of projection where the projecting lines emerge parallelly from the polygon surface and then incident parallelly on the plane. In parallel projection, the centre of the projection lies at infinity. In parallel projection, the view of the object obtained at the plane is less-realistic as there is no for-shortcoming. and the relative dimension of the object remains preserves." }, { "code": null, "e": 907, "s": 845, "text": "Parallel projection is further divided into two categories : " }, { "code": null, "e": 957, "s": 907, "text": "a) Orthographic Projection\n\nb) Oblique Projection" }, { "code": null, "e": 1146, "s": 957, "text": "(a) Orthographic Projection : It is a kind of parallel projection where the projecting lines emerge parallelly from the object surface and incident perpendicularly at the projecting plane." }, { "code": null, "e": 1193, "s": 1146, "text": "Orthographic Projection is of two categories :" }, { "code": null, "e": 1269, "s": 1193, "text": "(a).1. Multiview Projection : It is further divided into three categories –" }, { "code": null, "e": 1375, "s": 1269, "text": "(1) Top-View : In this projection, the rays that emerge from the top of the polygon surface are observed." }, { "code": null, "e": 1508, "s": 1379, "text": "2) Side-View : It is another type of projection orthographic projection where the side view of the polygon surface is observed. " }, { "code": null, "e": 1602, "s": 1510, "text": "3) Front-view : In this orthographic projection front face view of the object is observed. " }, { "code": null, "e": 1831, "s": 1604, "text": "a.2) Axonometric : Axonometric projection is an orthographic projection, where the projection lines are perpendicular to the plane of projection, and the object is rotated around one or more of its axes to show multiple sides." }, { "code": null, "e": 1877, "s": 1831, "text": "It is further divided into three categories :" }, { "code": null, "e": 2171, "s": 1877, "text": "(1) Isometric Projection : It is a method for visually representing three-dimensional objects in two-dimensional display in technical and engineering drawings. Here in this projection, the three coordinate axes appear equally foreshortened and the angle between any two of them is 120 degrees." }, { "code": null, "e": 2329, "s": 2173, "text": "(2) Dimetric Projection : It is a kind of orthographic projection where the visualized object appears to have only two adjacent sides and angles are equal." }, { "code": null, "e": 2485, "s": 2331, "text": "(3) Trimetric Projection : It is a kind of orthographic projection where the visualized object appears to have all the adjacent sides and angles unequal." }, { "code": null, "e": 2682, "s": 2487, "text": "(b) Oblique Projection : It is a kind of parallel projection where projecting rays emerges parallelly from the surface of the polygon and incident at an angle other than 90 degrees on the plane." }, { "code": null, "e": 2703, "s": 2682, "text": "It is of two kinds :" }, { "code": null, "e": 2987, "s": 2703, "text": "(b).1. Cavalier Projection : It is a kind of oblique projection where the projecting lines emerge parallelly from the object surface and incident at 45β€˜ rather than 90β€² at the projecting plane. In this projection, the length of the reading axis is larger than the cabinet projection." }, { "code": null, "e": 3203, "s": 2989, "text": "(b). 2. Cabinet Projection : It is similar to that cavalier projection but here the length of reading axes just half than the cavalier projection and the incident angle at the projecting plane is 63.4β€² rather 45β€²." }, { "code": null, "e": 3222, "s": 3207, "text": "sagar0719kumar" }, { "code": null, "e": 3240, "s": 3222, "text": "computer-graphics" }, { "code": null, "e": 3261, "s": 3240, "text": "Software Engineering" }, { "code": null, "e": 3359, "s": 3261, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3400, "s": 3359, "text": "Software Engineering | Black box testing" }, { "code": null, "e": 3432, "s": 3400, "text": "Unit Testing | Software Testing" }, { "code": null, "e": 3484, "s": 3432, "text": "Difference Between Edge Computing and Fog Computing" }, { "code": null, "e": 3499, "s": 3484, "text": "System Testing" }, { "code": null, "e": 3542, "s": 3499, "text": "Software Engineering | Integration Testing" }, { "code": null, "e": 3600, "s": 3542, "text": "Software Engineering | Calculation of Function Point (FP)" }, { "code": null, "e": 3632, "s": 3600, "text": "What is DFD(Data Flow Diagram)?" }, { "code": null, "e": 3671, "s": 3632, "text": "Software Development Life Cycle (SDLC)" }, { "code": null, "e": 3714, "s": 3671, "text": "Software Processes in Software Engineering" } ]
How to Find Duplicate Records that Meet Certain Conditions in SQL?
28 Oct, 2021 In this article, we will understand how to find Duplicate Records that meet certain conditions in SQL. Using the GROUP BY and HAVING clauses we can show the duplicates in table data. The GROUP BY statement in SQL is used to arrange identical data into groups with the help of some functions. i.e if a particular column has the same values in different rows then it will arrange these rows in a group. For the purpose of demonstration, we will be creating a Participant table in a database called β€œGeeksForGeeksDatabaseβ€œ. Step 1: Creating the Database Use the below SQL statement to create a database called GeeksForGeeksDatabase. Query: CREATE DATABASE GeeksForGeeksDatabase; Step 2: Using the Database Use the below SQL statement to switch the database context to GeeksForGeeksDatabase. Query: USE GeeksForGeeksDatabase; Step 3: Table Definition Query: CREATE TABLE Geeks( GeekID INTEGER PRIMARY KEY, GeekName VARCHAR(255) NOT NULL, GeekRank INTEGER NOT NULL, GeekSchool VARCHAR(255) NOT NULL ); INSERT INTO Geeks VALUES (101, 'Nix',2 ,'Code Valley School'); INSERT INTO Geeks VALUES (102, 'Rutz',4 ,'Blue Chip School'); INSERT INTO Geeks VALUES (103, 'Shrey',1 ,'GCOEA School'); INSERT INTO Geeks VALUES (104, 'Ankx',3 ,'Round Robin Play School'); INSERT INTO Geeks VALUES (105, 'Ridz',7 ,'Dream School'); INSERT INTO Geeks VALUES (106, 'Mayo',6 ,'Silver Shining School'); INSERT INTO Geeks VALUES (107, 'Bugs',5 ,'Twinkle Star Convent'); Step 4: To see the contents of the created table we use given below query: Query: SELECT * FROM Geeks; Output: The above the geeks table has normal records with no duplicate values. Step 5: Let’s imagine a situation where a bug occurred in the geek’s table due to some reasons few duplicates are inserted. Ideally, each row should have a unique value for GeekRank but now in our table duplicate geeks with duplicate ranks are inserted. Query: INSERT INTO Geeks VALUES (108, 'Maria', 5 ,'Code Valley School'); In the above newly updated table, we could see there are 2 records with the same geek rank of 5 . GeekID 107 and GeekID 108 are having the same rank of 5. Now we need to find this duplication using SQL Query. One way to find duplicate records from the table is the GROUP BY statement. The GROUP BY statement in SQL is used to arrange identical data into groups with the help of some functions. i.e if a particular column has the same values in different rows then it will arrange these rows in a group. Query to find the duplicates : Query to find the duplicate records having the same GeekRank : Query: SELECT GeekRank, COUNT(GeekID) AS DuplicateRanks FROM Geeks GROUP BY GeekRank HAVING COUNT(GeekRank)>1; Using the GROUP BY and HAVING clauses we can show the duplicates in table data. By β€˜GROUP BY GeekRankβ€˜ means, to place all the rows with the same value of only that particular column i.e GeekRank in one group. We use β€˜HAVING COUNT(GeekRank)>1β€² to select a column having more than 1 rank of geeks in output. The COUNT() function of SQL is used here to count the duplicate rows . Here we are naming our new column as β€˜DuplicateRanksβ€˜ which count duplicate ranks. Output: As we can see, the rows with duplicate GeekRank are grouped under the same GeekRank and their corresponding COUNT is the count of the GeekRank of duplicate rows. GeekID 107 and GeekID 108 are having the same rank 5. Thus in the above output, we could see GeekRank as 5 (because this 5th rank is found duplicated )and since two GeekIDs were having the same GeekRank 5 so DuplicateRank i.e count of duplicate record is 2. Once you found the duplicate rows, you may choose to remove those duplicate rows using the DELETE statement. Picked SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Oct, 2021" }, { "code": null, "e": 453, "s": 52, "text": "In this article, we will understand how to find Duplicate Records that meet certain conditions in SQL. Using the GROUP BY and HAVING clauses we can show the duplicates in table data. The GROUP BY statement in SQL is used to arrange identical data into groups with the help of some functions. i.e if a particular column has the same values in different rows then it will arrange these rows in a group." }, { "code": null, "e": 573, "s": 453, "text": "For the purpose of demonstration, we will be creating a Participant table in a database called β€œGeeksForGeeksDatabaseβ€œ." }, { "code": null, "e": 603, "s": 573, "text": "Step 1: Creating the Database" }, { "code": null, "e": 682, "s": 603, "text": "Use the below SQL statement to create a database called GeeksForGeeksDatabase." }, { "code": null, "e": 689, "s": 682, "text": "Query:" }, { "code": null, "e": 728, "s": 689, "text": "CREATE DATABASE GeeksForGeeksDatabase;" }, { "code": null, "e": 755, "s": 728, "text": "Step 2: Using the Database" }, { "code": null, "e": 840, "s": 755, "text": "Use the below SQL statement to switch the database context to GeeksForGeeksDatabase." }, { "code": null, "e": 847, "s": 840, "text": "Query:" }, { "code": null, "e": 874, "s": 847, "text": "USE GeeksForGeeksDatabase;" }, { "code": null, "e": 899, "s": 874, "text": "Step 3: Table Definition" }, { "code": null, "e": 906, "s": 899, "text": "Query:" }, { "code": null, "e": 1049, "s": 906, "text": "CREATE TABLE Geeks(\nGeekID INTEGER PRIMARY KEY,\nGeekName VARCHAR(255) NOT NULL,\nGeekRank INTEGER NOT NULL,\nGeekSchool VARCHAR(255) NOT NULL\n);" }, { "code": null, "e": 1493, "s": 1049, "text": "INSERT INTO Geeks VALUES (101, 'Nix',2 ,'Code Valley School');\nINSERT INTO Geeks VALUES (102, 'Rutz',4 ,'Blue Chip School');\nINSERT INTO Geeks VALUES (103, 'Shrey',1 ,'GCOEA School');\nINSERT INTO Geeks VALUES (104, 'Ankx',3 ,'Round Robin Play School');\nINSERT INTO Geeks VALUES (105, 'Ridz',7 ,'Dream School');\nINSERT INTO Geeks VALUES (106, 'Mayo',6 ,'Silver Shining School');\nINSERT INTO Geeks VALUES (107, 'Bugs',5 ,'Twinkle Star Convent');" }, { "code": null, "e": 1569, "s": 1493, "text": "Step 4: To see the contents of the created table we use given below query:" }, { "code": null, "e": 1576, "s": 1569, "text": "Query:" }, { "code": null, "e": 1597, "s": 1576, "text": "SELECT * FROM Geeks;" }, { "code": null, "e": 1605, "s": 1597, "text": "Output:" }, { "code": null, "e": 1677, "s": 1605, "text": "The above the geeks table has normal records with no duplicate values. " }, { "code": null, "e": 1931, "s": 1677, "text": "Step 5: Let’s imagine a situation where a bug occurred in the geek’s table due to some reasons few duplicates are inserted. Ideally, each row should have a unique value for GeekRank but now in our table duplicate geeks with duplicate ranks are inserted." }, { "code": null, "e": 1938, "s": 1931, "text": "Query:" }, { "code": null, "e": 2004, "s": 1938, "text": "INSERT INTO Geeks VALUES (108, 'Maria', 5 ,'Code Valley School');" }, { "code": null, "e": 2213, "s": 2004, "text": "In the above newly updated table, we could see there are 2 records with the same geek rank of 5 . GeekID 107 and GeekID 108 are having the same rank of 5. Now we need to find this duplication using SQL Query." }, { "code": null, "e": 2507, "s": 2213, "text": "One way to find duplicate records from the table is the GROUP BY statement. The GROUP BY statement in SQL is used to arrange identical data into groups with the help of some functions. i.e if a particular column has the same values in different rows then it will arrange these rows in a group." }, { "code": null, "e": 2538, "s": 2507, "text": "Query to find the duplicates :" }, { "code": null, "e": 2601, "s": 2538, "text": "Query to find the duplicate records having the same GeekRank :" }, { "code": null, "e": 2608, "s": 2601, "text": "Query:" }, { "code": null, "e": 2712, "s": 2608, "text": "SELECT GeekRank, COUNT(GeekID) AS DuplicateRanks\nFROM Geeks\nGROUP BY GeekRank\nHAVING COUNT(GeekRank)>1;" }, { "code": null, "e": 3173, "s": 2712, "text": "Using the GROUP BY and HAVING clauses we can show the duplicates in table data. By β€˜GROUP BY GeekRankβ€˜ means, to place all the rows with the same value of only that particular column i.e GeekRank in one group. We use β€˜HAVING COUNT(GeekRank)>1β€² to select a column having more than 1 rank of geeks in output. The COUNT() function of SQL is used here to count the duplicate rows . Here we are naming our new column as β€˜DuplicateRanksβ€˜ which count duplicate ranks." }, { "code": null, "e": 3181, "s": 3173, "text": "Output:" }, { "code": null, "e": 3710, "s": 3181, "text": "As we can see, the rows with duplicate GeekRank are grouped under the same GeekRank and their corresponding COUNT is the count of the GeekRank of duplicate rows. GeekID 107 and GeekID 108 are having the same rank 5. Thus in the above output, we could see GeekRank as 5 (because this 5th rank is found duplicated )and since two GeekIDs were having the same GeekRank 5 so DuplicateRank i.e count of duplicate record is 2. Once you found the duplicate rows, you may choose to remove those duplicate rows using the DELETE statement." }, { "code": null, "e": 3719, "s": 3712, "text": "Picked" }, { "code": null, "e": 3730, "s": 3719, "text": "SQL-Server" }, { "code": null, "e": 3734, "s": 3730, "text": "SQL" }, { "code": null, "e": 3738, "s": 3734, "text": "SQL" } ]
HTML textarea autocomplete Attribute
09 May, 2022 The HTML <textarea> autocomplete Attribute is used to specify whether the Textarea field has autocomplete on or off. When the autocomplete attribute is set to on, the browser will automatically complete the values based on which the user entered before. It works with many input fields such as text, search, URL, email, password, date pickers, range, and color.Syntax: <Textarea autocomplete="on | off"> Attribute Values: on: It has a default value. It specifies that autocomplete is enabled. off: It specifies that the autocomplete is disabled. Example: This example illustrates the use of autocomplete attribute in textarea element html <!DOCTYPE html><html> <head> <title> HTML textarea autocomplete Attribute </title></head> <body style="text-align:center"> <h1 style="color: green;"> GeeksforGeeks </h1> <h2> HTML Textarea autocomplete Attribute </h2> <textarea id="geeks" autocomplete="on" autofocus> write something here---- </textarea></body> </html> Output: Supported Browsers: The browsers supported by HTML | <textarea> autocomplete attribute are listed below: Google Chrome Internet Explorer Firefox Opera Safari chhabradhanvi rkbhola5 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n09 May, 2022" }, { "code": null, "e": 423, "s": 52, "text": "The HTML <textarea> autocomplete Attribute is used to specify whether the Textarea field has autocomplete on or off. When the autocomplete attribute is set to on, the browser will automatically complete the values based on which the user entered before. It works with many input fields such as text, search, URL, email, password, date pickers, range, and color.Syntax: " }, { "code": null, "e": 458, "s": 423, "text": "<Textarea autocomplete=\"on | off\">" }, { "code": null, "e": 478, "s": 458, "text": "Attribute Values: " }, { "code": null, "e": 549, "s": 478, "text": "on: It has a default value. It specifies that autocomplete is enabled." }, { "code": null, "e": 602, "s": 549, "text": "off: It specifies that the autocomplete is disabled." }, { "code": null, "e": 692, "s": 602, "text": "Example: This example illustrates the use of autocomplete attribute in textarea element " }, { "code": null, "e": 697, "s": 692, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML textarea autocomplete Attribute </title></head> <body style=\"text-align:center\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h2> HTML Textarea autocomplete Attribute </h2> <textarea id=\"geeks\" autocomplete=\"on\" autofocus> write something here---- </textarea></body> </html>", "e": 1084, "s": 697, "text": null }, { "code": null, "e": 1094, "s": 1084, "text": "Output: " }, { "code": null, "e": 1201, "s": 1094, "text": "Supported Browsers: The browsers supported by HTML | <textarea> autocomplete attribute are listed below: " }, { "code": null, "e": 1215, "s": 1201, "text": "Google Chrome" }, { "code": null, "e": 1233, "s": 1215, "text": "Internet Explorer" }, { "code": null, "e": 1241, "s": 1233, "text": "Firefox" }, { "code": null, "e": 1247, "s": 1241, "text": "Opera" }, { "code": null, "e": 1254, "s": 1247, "text": "Safari" }, { "code": null, "e": 1270, "s": 1256, "text": "chhabradhanvi" }, { "code": null, "e": 1279, "s": 1270, "text": "rkbhola5" }, { "code": null, "e": 1295, "s": 1279, "text": "HTML-Attributes" }, { "code": null, "e": 1300, "s": 1295, "text": "HTML" }, { "code": null, "e": 1317, "s": 1300, "text": "Web Technologies" }, { "code": null, "e": 1322, "s": 1317, "text": "HTML" } ]
std::remove_const in C++ with Examples
21 Jun, 2020 The std::remove_const template of C++ STL is present in the <type_traits> header file. The std::remove_const template of C++ STL is used to get the type T without const qualification. It return the boolean value true if T is without const qualified, otherwise return false. Below is the syntax for the same: Header File: #include<type_traits> Template Class: template <class T> struct remove_const; Syntax: std::remove_const<T>::value Parameter: This template std::remove_const accepts a single parameter T(Trait class) to check whether T is without const qualified or not. Return Value: The template std::remove_const returns a boolean value: True: If type T is without const qualified. False: If type T is with const qualified. Below is the program to demonstrate std::remove_const in C++: Program: // C++ program to illustrate// std::remove_const#include <bits/stdc++.h>#include <type_traits>using namespace std; // Driver Codeint main(){ // Declare variable of type // int, const int, const int*, // int * const and const int& typedef remove_const<int>::type A; typedef remove_const<const int>::type B; typedef remove_const<const int*>::type C; typedef remove_const<int* const>::type D; typedef remove_const<const int&>::type E; cout << std::boolalpha; // Checking const of the above // declared variables cout << "A is without const int? " << is_same<int, A>::value << endl; cout << "B is without const int? " << is_same<int, B>::value << endl; cout << "C is without const int? " << is_same<int, C>::value << endl; cout << "D is without const int? " << is_same<int, D>::value << endl; cout << "E is without const int? " << is_same<const int, E>::value << endl; return 0;} A is without const int? true B is without const int? true C is without const int? false D is without const int? false E is without const int? false Reference: http://www.cplusplus.com/reference/type_traits/remove_const/ CPP-Functions STL C++ C++ Programs STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jun, 2020" }, { "code": null, "e": 336, "s": 28, "text": "The std::remove_const template of C++ STL is present in the <type_traits> header file. The std::remove_const template of C++ STL is used to get the type T without const qualification. It return the boolean value true if T is without const qualified, otherwise return false. Below is the syntax for the same:" }, { "code": null, "e": 349, "s": 336, "text": "Header File:" }, { "code": null, "e": 372, "s": 349, "text": "#include<type_traits>\n" }, { "code": null, "e": 388, "s": 372, "text": "Template Class:" }, { "code": null, "e": 429, "s": 388, "text": "template <class T>\nstruct remove_const;\n" }, { "code": null, "e": 437, "s": 429, "text": "Syntax:" }, { "code": null, "e": 466, "s": 437, "text": "std::remove_const<T>::value\n" }, { "code": null, "e": 605, "s": 466, "text": "Parameter: This template std::remove_const accepts a single parameter T(Trait class) to check whether T is without const qualified or not." }, { "code": null, "e": 675, "s": 605, "text": "Return Value: The template std::remove_const returns a boolean value:" }, { "code": null, "e": 719, "s": 675, "text": "True: If type T is without const qualified." }, { "code": null, "e": 761, "s": 719, "text": "False: If type T is with const qualified." }, { "code": null, "e": 823, "s": 761, "text": "Below is the program to demonstrate std::remove_const in C++:" }, { "code": null, "e": 832, "s": 823, "text": "Program:" }, { "code": "// C++ program to illustrate// std::remove_const#include <bits/stdc++.h>#include <type_traits>using namespace std; // Driver Codeint main(){ // Declare variable of type // int, const int, const int*, // int * const and const int& typedef remove_const<int>::type A; typedef remove_const<const int>::type B; typedef remove_const<const int*>::type C; typedef remove_const<int* const>::type D; typedef remove_const<const int&>::type E; cout << std::boolalpha; // Checking const of the above // declared variables cout << \"A is without const int? \" << is_same<int, A>::value << endl; cout << \"B is without const int? \" << is_same<int, B>::value << endl; cout << \"C is without const int? \" << is_same<int, C>::value << endl; cout << \"D is without const int? \" << is_same<int, D>::value << endl; cout << \"E is without const int? \" << is_same<const int, E>::value << endl; return 0;}", "e": 1854, "s": 832, "text": null }, { "code": null, "e": 2003, "s": 1854, "text": "A is without const int? true\nB is without const int? true\nC is without const int? false\nD is without const int? false\nE is without const int? false\n" }, { "code": null, "e": 2075, "s": 2003, "text": "Reference: http://www.cplusplus.com/reference/type_traits/remove_const/" }, { "code": null, "e": 2089, "s": 2075, "text": "CPP-Functions" }, { "code": null, "e": 2093, "s": 2089, "text": "STL" }, { "code": null, "e": 2097, "s": 2093, "text": "C++" }, { "code": null, "e": 2110, "s": 2097, "text": "C++ Programs" }, { "code": null, "e": 2114, "s": 2110, "text": "STL" }, { "code": null, "e": 2118, "s": 2114, "text": "CPP" } ]
How to generate a random letter in Python?
03 Mar, 2021 In this article, let’s discuss how to generate a random letter. Python provides rich module support and some of these modules can help us to generate random numbers and letters. There are multiple ways we can do that using various Python modules. Method 1: Using string and random module The string module has a special function ascii_letters which returns a string containing all the alphabets from a-z and A-Z, i.e. all the lowercase and uppercase alphabets. Using random.choice() we can choose any of the particular characters from that string. Code: Python3 # Import string and random moduleimport stringimport random # Randomly choose a letter from all the ascii_lettersrandomLetter = random.choice(string.ascii_letters)print(randomLetter) Output: w Method 2: Using the only random module Using random.randint(x,y) we can generate random integers from x to y. So we can randomly generate ASCII value of one of the alphabets and then typecast them to char using chr() function. Code: Python3 # Import string and random moduleimport random # Randomly generate a ascii value# from 'a' to 'z' and 'A' to 'Z'randomLowerLetter = chr(random.randint(ord('a'), ord('z')))randomUpperLetter = chr(random.randint(ord('A'), ord('Z')))print(randomLowerLetter, randomUpperLetter) Output: n M Picked Python-random Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n03 Mar, 2021" }, { "code": null, "e": 300, "s": 53, "text": "In this article, let’s discuss how to generate a random letter. Python provides rich module support and some of these modules can help us to generate random numbers and letters. There are multiple ways we can do that using various Python modules." }, { "code": null, "e": 341, "s": 300, "text": "Method 1: Using string and random module" }, { "code": null, "e": 601, "s": 341, "text": "The string module has a special function ascii_letters which returns a string containing all the alphabets from a-z and A-Z, i.e. all the lowercase and uppercase alphabets. Using random.choice() we can choose any of the particular characters from that string." }, { "code": null, "e": 607, "s": 601, "text": "Code:" }, { "code": null, "e": 615, "s": 607, "text": "Python3" }, { "code": "# Import string and random moduleimport stringimport random # Randomly choose a letter from all the ascii_lettersrandomLetter = random.choice(string.ascii_letters)print(randomLetter)", "e": 799, "s": 615, "text": null }, { "code": null, "e": 807, "s": 799, "text": "Output:" }, { "code": null, "e": 809, "s": 807, "text": "w" }, { "code": null, "e": 848, "s": 809, "text": "Method 2: Using the only random module" }, { "code": null, "e": 1036, "s": 848, "text": "Using random.randint(x,y) we can generate random integers from x to y. So we can randomly generate ASCII value of one of the alphabets and then typecast them to char using chr() function." }, { "code": null, "e": 1042, "s": 1036, "text": "Code:" }, { "code": null, "e": 1050, "s": 1042, "text": "Python3" }, { "code": "# Import string and random moduleimport random # Randomly generate a ascii value# from 'a' to 'z' and 'A' to 'Z'randomLowerLetter = chr(random.randint(ord('a'), ord('z')))randomUpperLetter = chr(random.randint(ord('A'), ord('Z')))print(randomLowerLetter, randomUpperLetter)", "e": 1325, "s": 1050, "text": null }, { "code": null, "e": 1333, "s": 1325, "text": "Output:" }, { "code": null, "e": 1337, "s": 1333, "text": "n M" }, { "code": null, "e": 1344, "s": 1337, "text": "Picked" }, { "code": null, "e": 1358, "s": 1344, "text": "Python-random" }, { "code": null, "e": 1382, "s": 1358, "text": "Technical Scripter 2020" }, { "code": null, "e": 1389, "s": 1382, "text": "Python" }, { "code": null, "e": 1408, "s": 1389, "text": "Technical Scripter" } ]
How to close window using JavaScript which is opened by the user with a URL ?
05 Nov, 2020 JavaScript does not allow one to close a window opened by the user, using the window.close() method due to security issues. However, we can close a window by using a workaround. The approach to be followed is by opening the current URL using JavaScript so that it could be closed with a script. The steps below demonstrate this approach: Step 1: Opening a new window using the open() method: First we need to open a new window using the window.open() method. The current URL can be accessed using the location property of the window object. The target attribute or name value of the window is given as _self. This is important as it makes the URL replace the current page. Step 2: Close this open window using the close() method: The window.close() method closes the window on which it is called. The window that was opened in the first step is closed by using this method. This works because the window has now been opened by our script instead of the user. Note: This approach may not work on all browsers due to different implementations of browser security. The example below demonstrates the above steps: Example: HTML <!DOCTYPE html><html> <body> <h1 style="color: green;"> GeeksforGeeks </h1> <p> Click on the button below to close the current window. </p> <!-- Define the button to close the window --> <button onclick="return closeWindow();"> Close Window </button> <script type="text/javascript"> function closeWindow() { // Open the new window // with the URL replacing the // current page using the // _self value let new_window = open(location, '_self'); // Close this window new_window.close(); return false; } </script></body> </html> Output: HTML-Misc JavaScript-Misc HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Design a Tribute Page using HTML & CSS Build a Survey Form using HTML and CSS How to auto-resize an image to fit a div container using CSS? Angular File Upload Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Differences between Functional Components and Class Components in React Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Nov, 2020" }, { "code": null, "e": 349, "s": 54, "text": "JavaScript does not allow one to close a window opened by the user, using the window.close() method due to security issues. However, we can close a window by using a workaround. The approach to be followed is by opening the current URL using JavaScript so that it could be closed with a script." }, { "code": null, "e": 392, "s": 349, "text": "The steps below demonstrate this approach:" }, { "code": null, "e": 727, "s": 392, "text": "Step 1: Opening a new window using the open() method: First we need to open a new window using the window.open() method. The current URL can be accessed using the location property of the window object. The target attribute or name value of the window is given as _self. This is important as it makes the URL replace the current page." }, { "code": null, "e": 1013, "s": 727, "text": "Step 2: Close this open window using the close() method: The window.close() method closes the window on which it is called. The window that was opened in the first step is closed by using this method. This works because the window has now been opened by our script instead of the user." }, { "code": null, "e": 1116, "s": 1013, "text": "Note: This approach may not work on all browsers due to different implementations of browser security." }, { "code": null, "e": 1164, "s": 1116, "text": "The example below demonstrates the above steps:" }, { "code": null, "e": 1173, "s": 1164, "text": "Example:" }, { "code": null, "e": 1178, "s": 1173, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <p> Click on the button below to close the current window. </p> <!-- Define the button to close the window --> <button onclick=\"return closeWindow();\"> Close Window </button> <script type=\"text/javascript\"> function closeWindow() { // Open the new window // with the URL replacing the // current page using the // _self value let new_window = open(location, '_self'); // Close this window new_window.close(); return false; } </script></body> </html>", "e": 1902, "s": 1178, "text": null }, { "code": null, "e": 1910, "s": 1902, "text": "Output:" }, { "code": null, "e": 1920, "s": 1910, "text": "HTML-Misc" }, { "code": null, "e": 1936, "s": 1920, "text": "JavaScript-Misc" }, { "code": null, "e": 1941, "s": 1936, "text": "HTML" }, { "code": null, "e": 1952, "s": 1941, "text": "JavaScript" }, { "code": null, "e": 1969, "s": 1952, "text": "Web Technologies" }, { "code": null, "e": 1974, "s": 1969, "text": "HTML" }, { "code": null, "e": 2072, "s": 1974, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2096, "s": 2072, "text": "REST API (Introduction)" }, { "code": null, "e": 2135, "s": 2096, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 2174, "s": 2135, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 2236, "s": 2174, "text": "How to auto-resize an image to fit a div container using CSS?" }, { "code": null, "e": 2256, "s": 2236, "text": "Angular File Upload" }, { "code": null, "e": 2317, "s": 2256, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2357, "s": 2317, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2429, "s": 2357, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2471, "s": 2429, "text": "Roadmap to Learn JavaScript For Beginners" } ]
PHP | Send Attachment With Email
16 Jun, 2022 Sending an email is a very common activity in a web browser. For example, sending an email when a new user joins a network, sending a newsletter, sending greeting mail, or sending an invoice. We can use the built-in mail() function to send an email programmatically. This function needs three required arguments that hold the information about the recipient, the subject of the message and the message body. Along with these three required arguments, there are two more arguments which are optional. One of them is the header and the other one is parameters. We have already discussed sending text-based emails in PHP in our previous article. In this article, we will see how we can send an email with attachments using the Mime-Versionmail() function.When the mail() function is called PHP will attempt to send the mail immediately to the recipient then it will return true upon successful delivery of the mail and false if an error occurs.Syntax: bool mail( $to, $subject, $message, $headers, $parameters ); Here is the description of each parameter. When we are sending mail through PHP, all content in the message will be treated as simple text only. If we put any HTML tag inside the message body, it will not be formatted as HTML syntax. HTML tag will be displayed as simple text. To format any HTML tag according to HTML syntax, we can specify the MIME (Multipurpose Internet Mail Extension) version, content type and character set of the message body. To send an attachment along with the email, we need to set the Content-type as mixed/multipart and we have to define the text and attachment sections within a Boundary. Approach: Make sure you have a XAMPP server or WAMP server installed on your machine. In this article, we will be using the WAMP server. Follow the steps given below: Create an HTML form: Below is the HTML source code for the HTML form. In the HTML <form> tag, we are using β€œenctype=’multipart/form-data” which is an encoding type that allows files to be sent through a POST method. Without this encoding, the files cannot be sent through the POST method. We must use this enctype if you want to allow users to upload a file through a form. HTML <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css"> <title>Send Attachment With Email</title></head><body> <div style="display:flex; justify-content: center; margin-top:10%;"> <form enctype="multipart/form-data" method="POST" action="" style="width: 500px;"> <div class="form-group"> <input class="form-control" type="text" name="sender_name" placeholder="Your Name" required/> </div> <div class="form-group"> <input class="form-control" type="email" name="sender_email" placeholder="Recipient's Email Address" required/> </div> <div class="form-group"> <input class="form-control" type="text" name="subject" placeholder="Subject"/> </div> <div class="form-group"> <textarea class="form-control" name="message" placeholder="Message"></textarea> </div> <div class="form-group"> <input class="form-control" type="file" name="attachment" placeholder="Attachment" required/> </div> <div class="form-group"> <input class="btn btn-primary" type="submit" name="button" value="Submit" /> </div> </form> </div></body></html> PHP Script for handling the form data: PHP <?php if(isset($_POST['button']) && isset($_FILES['attachment'])){ $from_email = 'sender@abc.com'; //from mail, sender email address $recipient_email = 'recipient@xyz.com'; //recipient email address //Load POST data from HTML form $sender_name = $_POST["sender_name"]; //sender name $reply_to_email = $_POST["sender_email"]; //sender email, it will be used in "reply-to" header $subject = $_POST["subject"]; //subject for the email $message = $_POST["message"]; //body of the email /*Always remember to validate the form fields like this if(strlen($sender_name)<1) { die('Name is too short or empty!'); } */ //Get uploaded file data using $_FILES array $tmp_name = $_FILES['attachment']['tmp_name']; // get the temporary file name of the file on the server $name = $_FILES['attachment']['name']; // get the name of the file $size = $_FILES['attachment']['size']; // get size of the file for size validation $type = $_FILES['attachment']['type']; // get type of the file $error = $_FILES['attachment']['error']; // get the error (if any) //validate form field for attaching the file if($error > 0) { die('Upload error or No files uploaded'); } //read from the uploaded file & base64_encode content $handle = fopen($tmp_name, "r"); // set the file handle only for reading the file $content = fread($handle, $size); // reading the file fclose($handle); // close upon completion $encoded_content = chunk_split(base64_encode($content)); $boundary = md5("random"); // define boundary with a md5 hashed value //header $headers = "MIME-Version: 1.0\r\n"; // Defining the MIME version $headers .= "From:".$from_email."\r\n"; // Sender Email $headers .= "Reply-To: ".$reply_to_email."\r\n"; // Email address to reach back $headers .= "Content-Type: multipart/mixed;"; // Defining Content-Type $headers .= "boundary = $boundary\r\n"; //Defining the Boundary //plain text $body = "--$boundary\r\n"; $body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n"; $body .= "Content-Transfer-Encoding: base64\r\n\r\n"; $body .= chunk_split(base64_encode($message)); //attachment $body .= "--$boundary\r\n"; $body .="Content-Type: $type; name=".$name."\r\n"; $body .="Content-Disposition: attachment; filename=".$name."\r\n"; $body .="Content-Transfer-Encoding: base64\r\n"; $body .="X-Attachment-Id: ".rand(1000, 99999)."\r\n\r\n"; $body .= $encoded_content; // Attaching the encoded file with email $sentMailResult = mail($recipient_email, $subject, $body, $headers); if($sentMailResult ) { echo "<h3>File Sent Successfully.<h3>"; // unlink($name); // delete the file after attachment sent. } else { die("Sorry but the email could not be sent. Please go back and try again!"); }}?> Complete Code: The final code for sending attachments with Emails is as follows: PHP <?php if(isset($_POST['button']) && isset($_FILES['attachment'])){ $from_email = 'sender@abc.com'; //from mail, sender email address $recipient_email = 'recipient@xyz.com'; //recipient email address //Load POST data from HTML form $sender_name = $_POST["sender_name"]; //sender name $reply_to_email = $_POST["sender_email"]; //sender email, it will be used in "reply-to" header $subject = $_POST["subject"]; //subject for the email $message = $_POST["message"]; //body of the email /*Always remember to validate the form fields like this if(strlen($sender_name)<1) { die('Name is too short or empty!'); } */ //Get uploaded file data using $_FILES array $tmp_name = $_FILES['attachment']['tmp_name']; // get the temporary file name of the file on the server $name = $_FILES['attachment']['name']; // get the name of the file $size = $_FILES['attachment']['size']; // get size of the file for size validation $type = $_FILES['attachment']['type']; // get type of the file $error = $_FILES['attachment']['error']; // get the error (if any) //validate form field for attaching the file if($error > 0) { die('Upload error or No files uploaded'); } //read from the uploaded file & base64_encode content $handle = fopen($tmp_name, "r"); // set the file handle only for reading the file $content = fread($handle, $size); // reading the file fclose($handle); // close upon completion $encoded_content = chunk_split(base64_encode($content)); $boundary = md5("random"); // define boundary with a md5 hashed value //header $headers = "MIME-Version: 1.0\r\n"; // Defining the MIME version $headers .= "From:".$from_email."\r\n"; // Sender Email $headers .= "Reply-To: ".$reply_to_email."\r\n"; // Email address to reach back $headers .= "Content-Type: multipart/mixed;"; // Defining Content-Type $headers .= "boundary = $boundary\r\n"; //Defining the Boundary //plain text $body = "--$boundary\r\n"; $body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n"; $body .= "Content-Transfer-Encoding: base64\r\n\r\n"; $body .= chunk_split(base64_encode($message)); //attachment $body .= "--$boundary\r\n"; $body .="Content-Type: $type; name=".$name."\r\n"; $body .="Content-Disposition: attachment; filename=".$name."\r\n"; $body .="Content-Transfer-Encoding: base64\r\n"; $body .="X-Attachment-Id: ".rand(1000, 99999)."\r\n\r\n"; $body .= $encoded_content; // Attaching the encoded file with email $sentMailResult = mail($recipient_email, $subject, $body, $headers); if($sentMailResult ){ echo "<h3>File Sent Successfully.<h3>"; // unlink($name); // delete the file after attachment sent. } else{ die("Sorry but the email could not be sent. Please go back and try again!"); }}?> <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css"> <title>Send Attachment With Email</title></head><body> <div style="display:flex; justify-content: center; margin-top:10%;"> <form enctype="multipart/form-data" method="POST" action="" style="width: 500px;"> <div class="form-group"> <input class="form-control" type="text" name="sender_name" placeholder="Your Name" required/> </div> <div class="form-group"> <input class="form-control" type="email" name="sender_email" placeholder="Recipient's Email Address" required/> </div> <div class="form-group"> <input class="form-control" type="text" name="subject" placeholder="Subject"/> </div> <div class="form-group"> <textarea class="form-control" name="message" placeholder="Message"></textarea> </div> <div class="form-group"> <input class="form-control" type="file" name="attachment" placeholder="Attachment" required/> </div> <div class="form-group"> <input class="btn btn-primary" type="submit" name="button" value="Submit" /> </div> </form> </div></body></html> Output: 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. gabaa406 boblipscomb sweetyty sanjyotpanure PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Jun, 2022" }, { "code": null, "e": 1003, "s": 52, "text": "Sending an email is a very common activity in a web browser. For example, sending an email when a new user joins a network, sending a newsletter, sending greeting mail, or sending an invoice. We can use the built-in mail() function to send an email programmatically. This function needs three required arguments that hold the information about the recipient, the subject of the message and the message body. Along with these three required arguments, there are two more arguments which are optional. One of them is the header and the other one is parameters. We have already discussed sending text-based emails in PHP in our previous article. In this article, we will see how we can send an email with attachments using the Mime-Versionmail() function.When the mail() function is called PHP will attempt to send the mail immediately to the recipient then it will return true upon successful delivery of the mail and false if an error occurs.Syntax: " }, { "code": null, "e": 1064, "s": 1003, "text": "bool mail( $to, $subject, $message, $headers, $parameters );" }, { "code": null, "e": 1109, "s": 1064, "text": "Here is the description of each parameter. " }, { "code": null, "e": 1685, "s": 1109, "text": "When we are sending mail through PHP, all content in the message will be treated as simple text only. If we put any HTML tag inside the message body, it will not be formatted as HTML syntax. HTML tag will be displayed as simple text. To format any HTML tag according to HTML syntax, we can specify the MIME (Multipurpose Internet Mail Extension) version, content type and character set of the message body. To send an attachment along with the email, we need to set the Content-type as mixed/multipart and we have to define the text and attachment sections within a Boundary." }, { "code": null, "e": 1822, "s": 1685, "text": "Approach: Make sure you have a XAMPP server or WAMP server installed on your machine. In this article, we will be using the WAMP server." }, { "code": null, "e": 1852, "s": 1822, "text": "Follow the steps given below:" }, { "code": null, "e": 2226, "s": 1852, "text": "Create an HTML form: Below is the HTML source code for the HTML form. In the HTML <form> tag, we are using β€œenctype=’multipart/form-data” which is an encoding type that allows files to be sent through a POST method. Without this encoding, the files cannot be sent through the POST method. We must use this enctype if you want to allow users to upload a file through a form." }, { "code": null, "e": 2231, "s": 2226, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css\"> <title>Send Attachment With Email</title></head><body> <div style=\"display:flex; justify-content: center; margin-top:10%;\"> <form enctype=\"multipart/form-data\" method=\"POST\" action=\"\" style=\"width: 500px;\"> <div class=\"form-group\"> <input class=\"form-control\" type=\"text\" name=\"sender_name\" placeholder=\"Your Name\" required/> </div> <div class=\"form-group\"> <input class=\"form-control\" type=\"email\" name=\"sender_email\" placeholder=\"Recipient's Email Address\" required/> </div> <div class=\"form-group\"> <input class=\"form-control\" type=\"text\" name=\"subject\" placeholder=\"Subject\"/> </div> <div class=\"form-group\"> <textarea class=\"form-control\" name=\"message\" placeholder=\"Message\"></textarea> </div> <div class=\"form-group\"> <input class=\"form-control\" type=\"file\" name=\"attachment\" placeholder=\"Attachment\" required/> </div> <div class=\"form-group\"> <input class=\"btn btn-primary\" type=\"submit\" name=\"button\" value=\"Submit\" /> </div> </form> </div></body></html>", "e": 3752, "s": 2231, "text": null }, { "code": null, "e": 3793, "s": 3752, "text": "PHP Script for handling the form data: " }, { "code": null, "e": 3797, "s": 3793, "text": "PHP" }, { "code": "<?php if(isset($_POST['button']) && isset($_FILES['attachment'])){ $from_email = 'sender@abc.com'; //from mail, sender email address $recipient_email = 'recipient@xyz.com'; //recipient email address //Load POST data from HTML form $sender_name = $_POST[\"sender_name\"]; //sender name $reply_to_email = $_POST[\"sender_email\"]; //sender email, it will be used in \"reply-to\" header $subject = $_POST[\"subject\"]; //subject for the email $message = $_POST[\"message\"]; //body of the email /*Always remember to validate the form fields like this if(strlen($sender_name)<1) { die('Name is too short or empty!'); } */ //Get uploaded file data using $_FILES array $tmp_name = $_FILES['attachment']['tmp_name']; // get the temporary file name of the file on the server $name = $_FILES['attachment']['name']; // get the name of the file $size = $_FILES['attachment']['size']; // get size of the file for size validation $type = $_FILES['attachment']['type']; // get type of the file $error = $_FILES['attachment']['error']; // get the error (if any) //validate form field for attaching the file if($error > 0) { die('Upload error or No files uploaded'); } //read from the uploaded file & base64_encode content $handle = fopen($tmp_name, \"r\"); // set the file handle only for reading the file $content = fread($handle, $size); // reading the file fclose($handle); // close upon completion $encoded_content = chunk_split(base64_encode($content)); $boundary = md5(\"random\"); // define boundary with a md5 hashed value //header $headers = \"MIME-Version: 1.0\\r\\n\"; // Defining the MIME version $headers .= \"From:\".$from_email.\"\\r\\n\"; // Sender Email $headers .= \"Reply-To: \".$reply_to_email.\"\\r\\n\"; // Email address to reach back $headers .= \"Content-Type: multipart/mixed;\"; // Defining Content-Type $headers .= \"boundary = $boundary\\r\\n\"; //Defining the Boundary //plain text $body = \"--$boundary\\r\\n\"; $body .= \"Content-Type: text/plain; charset=ISO-8859-1\\r\\n\"; $body .= \"Content-Transfer-Encoding: base64\\r\\n\\r\\n\"; $body .= chunk_split(base64_encode($message)); //attachment $body .= \"--$boundary\\r\\n\"; $body .=\"Content-Type: $type; name=\".$name.\"\\r\\n\"; $body .=\"Content-Disposition: attachment; filename=\".$name.\"\\r\\n\"; $body .=\"Content-Transfer-Encoding: base64\\r\\n\"; $body .=\"X-Attachment-Id: \".rand(1000, 99999).\"\\r\\n\\r\\n\"; $body .= $encoded_content; // Attaching the encoded file with email $sentMailResult = mail($recipient_email, $subject, $body, $headers); if($sentMailResult ) { echo \"<h3>File Sent Successfully.<h3>\"; // unlink($name); // delete the file after attachment sent. } else { die(\"Sorry but the email could not be sent. Please go back and try again!\"); }}?>", "e": 6749, "s": 3797, "text": null }, { "code": null, "e": 6830, "s": 6749, "text": "Complete Code: The final code for sending attachments with Emails is as follows:" }, { "code": null, "e": 6834, "s": 6830, "text": "PHP" }, { "code": "<?php if(isset($_POST['button']) && isset($_FILES['attachment'])){ $from_email = 'sender@abc.com'; //from mail, sender email address $recipient_email = 'recipient@xyz.com'; //recipient email address //Load POST data from HTML form $sender_name = $_POST[\"sender_name\"]; //sender name $reply_to_email = $_POST[\"sender_email\"]; //sender email, it will be used in \"reply-to\" header $subject = $_POST[\"subject\"]; //subject for the email $message = $_POST[\"message\"]; //body of the email /*Always remember to validate the form fields like this if(strlen($sender_name)<1) { die('Name is too short or empty!'); } */ //Get uploaded file data using $_FILES array $tmp_name = $_FILES['attachment']['tmp_name']; // get the temporary file name of the file on the server $name = $_FILES['attachment']['name']; // get the name of the file $size = $_FILES['attachment']['size']; // get size of the file for size validation $type = $_FILES['attachment']['type']; // get type of the file $error = $_FILES['attachment']['error']; // get the error (if any) //validate form field for attaching the file if($error > 0) { die('Upload error or No files uploaded'); } //read from the uploaded file & base64_encode content $handle = fopen($tmp_name, \"r\"); // set the file handle only for reading the file $content = fread($handle, $size); // reading the file fclose($handle); // close upon completion $encoded_content = chunk_split(base64_encode($content)); $boundary = md5(\"random\"); // define boundary with a md5 hashed value //header $headers = \"MIME-Version: 1.0\\r\\n\"; // Defining the MIME version $headers .= \"From:\".$from_email.\"\\r\\n\"; // Sender Email $headers .= \"Reply-To: \".$reply_to_email.\"\\r\\n\"; // Email address to reach back $headers .= \"Content-Type: multipart/mixed;\"; // Defining Content-Type $headers .= \"boundary = $boundary\\r\\n\"; //Defining the Boundary //plain text $body = \"--$boundary\\r\\n\"; $body .= \"Content-Type: text/plain; charset=ISO-8859-1\\r\\n\"; $body .= \"Content-Transfer-Encoding: base64\\r\\n\\r\\n\"; $body .= chunk_split(base64_encode($message)); //attachment $body .= \"--$boundary\\r\\n\"; $body .=\"Content-Type: $type; name=\".$name.\"\\r\\n\"; $body .=\"Content-Disposition: attachment; filename=\".$name.\"\\r\\n\"; $body .=\"Content-Transfer-Encoding: base64\\r\\n\"; $body .=\"X-Attachment-Id: \".rand(1000, 99999).\"\\r\\n\\r\\n\"; $body .= $encoded_content; // Attaching the encoded file with email $sentMailResult = mail($recipient_email, $subject, $body, $headers); if($sentMailResult ){ echo \"<h3>File Sent Successfully.<h3>\"; // unlink($name); // delete the file after attachment sent. } else{ die(\"Sorry but the email could not be sent. Please go back and try again!\"); }}?> <!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css\"> <title>Send Attachment With Email</title></head><body> <div style=\"display:flex; justify-content: center; margin-top:10%;\"> <form enctype=\"multipart/form-data\" method=\"POST\" action=\"\" style=\"width: 500px;\"> <div class=\"form-group\"> <input class=\"form-control\" type=\"text\" name=\"sender_name\" placeholder=\"Your Name\" required/> </div> <div class=\"form-group\"> <input class=\"form-control\" type=\"email\" name=\"sender_email\" placeholder=\"Recipient's Email Address\" required/> </div> <div class=\"form-group\"> <input class=\"form-control\" type=\"text\" name=\"subject\" placeholder=\"Subject\"/> </div> <div class=\"form-group\"> <textarea class=\"form-control\" name=\"message\" placeholder=\"Message\"></textarea> </div> <div class=\"form-group\"> <input class=\"form-control\" type=\"file\" name=\"attachment\" placeholder=\"Attachment\" required/> </div> <div class=\"form-group\"> <input class=\"btn btn-primary\" type=\"submit\" name=\"button\" value=\"Submit\" /> </div> </form> </div></body></html>", "e": 11311, "s": 6834, "text": null }, { "code": null, "e": 11320, "s": 11311, "text": "Output: " }, { "code": null, "e": 11491, "s": 11322, "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": 11500, "s": 11491, "text": "gabaa406" }, { "code": null, "e": 11512, "s": 11500, "text": "boblipscomb" }, { "code": null, "e": 11521, "s": 11512, "text": "sweetyty" }, { "code": null, "e": 11535, "s": 11521, "text": "sanjyotpanure" }, { "code": null, "e": 11539, "s": 11535, "text": "PHP" }, { "code": null, "e": 11556, "s": 11539, "text": "Web Technologies" }, { "code": null, "e": 11560, "s": 11556, "text": "PHP" } ]
Translator App Project using Django
16 Mar, 2021 Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? In this article we will make a translator app using Django. Installation pip install django Text translation from one language to another is increasingly becoming common for various websites as they cater to an international audience. The python package which helps us do this is called translate. pip install translate Then create new project django-admin startproject translator cd translator Then create new app inside the project python manage.py startapp main Then add the app name inside the settings.py views.py Python3 from django.shortcuts import render,HttpResponsefrom translate import Translator# Create your views here. def home(request): if request.method == "POST": text = request.POST["translate"] language = request.POST["language"] translator= Translator(to_lang=language) translation = translator.translate(text) return HttpResponse(translation) return render(request,"main/index.html") Then create directory templates inside the app. Inside that create new directory main Create new file index.html HTML <!DOCTYPE html><html><head> <title>GFG</title></head><body><form method="post"> {% csrf_token %} <input type="text" name="translate" required> <br> <select required name="language"> <option value="Hindi">Hindi</option> <option value="Marathi">Marathi</option> <option value="German">German</option> </select> <br> <button type="submit">Translate</button></form></body></html> Then create new file urls.py inside the app Python3 from django.urls import pathfrom .views import * urlpatterns = [ path('',home,name="home"),] Then add then main.urls inside url translator/urls.py Python3 from django.contrib import adminfrom django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include("main.urls"))] To run this app open cmd or terminal python manage.py runserver Output :- Django-Projects Python Django Python Framework Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 53, "s": 25, "text": "\n16 Mar, 2021" }, { "code": null, "e": 352, "s": 53, "text": "Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source." }, { "code": null, "e": 439, "s": 352, "text": "Refer to the following articles to check how to create a project and an app in Django." }, { "code": null, "e": 490, "s": 439, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 523, "s": 490, "text": "How to Create an App in Django ?" }, { "code": null, "e": 583, "s": 523, "text": "In this article we will make a translator app using Django." }, { "code": null, "e": 596, "s": 583, "text": "Installation" }, { "code": null, "e": 615, "s": 596, "text": "pip install django" }, { "code": null, "e": 821, "s": 615, "text": "Text translation from one language to another is increasingly becoming common for various websites as they cater to an international audience. The python package which helps us do this is called translate." }, { "code": null, "e": 843, "s": 821, "text": "pip install translate" }, { "code": null, "e": 867, "s": 843, "text": "Then create new project" }, { "code": null, "e": 904, "s": 867, "text": "django-admin startproject translator" }, { "code": null, "e": 918, "s": 904, "text": "cd translator" }, { "code": null, "e": 957, "s": 918, "text": "Then create new app inside the project" }, { "code": null, "e": 988, "s": 957, "text": "python manage.py startapp main" }, { "code": null, "e": 1034, "s": 988, "text": "Then add the app name inside the settings.py " }, { "code": null, "e": 1043, "s": 1034, "text": "views.py" }, { "code": null, "e": 1051, "s": 1043, "text": "Python3" }, { "code": "from django.shortcuts import render,HttpResponsefrom translate import Translator# Create your views here. def home(request): if request.method == \"POST\": text = request.POST[\"translate\"] language = request.POST[\"language\"] translator= Translator(to_lang=language) translation = translator.translate(text) return HttpResponse(translation) return render(request,\"main/index.html\")", "e": 1472, "s": 1051, "text": null }, { "code": null, "e": 1520, "s": 1472, "text": "Then create directory templates inside the app." }, { "code": null, "e": 1558, "s": 1520, "text": "Inside that create new directory main" }, { "code": null, "e": 1585, "s": 1558, "text": "Create new file index.html" }, { "code": null, "e": 1590, "s": 1585, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>GFG</title></head><body><form method=\"post\"> {% csrf_token %} <input type=\"text\" name=\"translate\" required> <br> <select required name=\"language\"> <option value=\"Hindi\">Hindi</option> <option value=\"Marathi\">Marathi</option> <option value=\"German\">German</option> </select> <br> <button type=\"submit\">Translate</button></form></body></html>", "e": 2011, "s": 1590, "text": null }, { "code": null, "e": 2055, "s": 2011, "text": "Then create new file urls.py inside the app" }, { "code": null, "e": 2063, "s": 2055, "text": "Python3" }, { "code": "from django.urls import pathfrom .views import * urlpatterns = [ path('',home,name=\"home\"),]", "e": 2160, "s": 2063, "text": null }, { "code": null, "e": 2214, "s": 2160, "text": "Then add then main.urls inside url translator/urls.py" }, { "code": null, "e": 2222, "s": 2214, "text": "Python3" }, { "code": "from django.contrib import adminfrom django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include(\"main.urls\"))]", "e": 2378, "s": 2222, "text": null }, { "code": null, "e": 2416, "s": 2378, "text": "To run this app open cmd or terminal " }, { "code": null, "e": 2443, "s": 2416, "text": "python manage.py runserver" }, { "code": null, "e": 2453, "s": 2443, "text": "Output :-" }, { "code": null, "e": 2469, "s": 2453, "text": "Django-Projects" }, { "code": null, "e": 2483, "s": 2469, "text": "Python Django" }, { "code": null, "e": 2500, "s": 2483, "text": "Python Framework" }, { "code": null, "e": 2507, "s": 2500, "text": "Python" }, { "code": null, "e": 2605, "s": 2507, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2637, "s": 2605, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2664, "s": 2637, "text": "Python Classes and Objects" }, { "code": null, "e": 2685, "s": 2664, "text": "Python OOPs Concepts" }, { "code": null, "e": 2708, "s": 2685, "text": "Introduction To PYTHON" }, { "code": null, "e": 2764, "s": 2708, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2795, "s": 2764, "text": "Python | os.path.join() method" }, { "code": null, "e": 2837, "s": 2795, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2879, "s": 2837, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2918, "s": 2879, "text": "Python | Get unique values from a list" } ]
SMTP Commands
13 Sep, 2021 Simple Mail Transfer Protocol (SMTP) is an ASCII protocol. It is based on client-server model. It uses TCP port number 25 for this service. Therefore e-mail; is delivered from source to destination by having the source machine established a TCP to port 25 of the destination machine. To send mail, a system must contain client MTA and to receive a mail, a system must have server MTA. SMTP transfers this message from client MTA to the server MTA. To send a mail, SMTP is used two times: one between sender and sender’s mail server and the other between the two mail servers. SMTP Commands : These commands are sent from the client to the server. Each command consists of a keyword followed by zero or more arguments. It means there are also some keywords that do not contain any argument. The format of the command is as follows : Keywords : argument(s) There are 14 different SMTP commands which are given in the following table : avtarkumar719 Computer Networks GATE CS Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GSM in Wireless Communication Wireless Application Protocol Secure Socket Layer (SSL) Mobile Internet Protocol (or Mobile IP) Advanced Encryption Standard (AES) ACID Properties in DBMS Types of Operating Systems Normal Forms in DBMS Page Replacement Algorithms in Operating Systems Inter Process Communication (IPC)
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Sep, 2021" }, { "code": null, "e": 605, "s": 28, "text": "Simple Mail Transfer Protocol (SMTP) is an ASCII protocol. It is based on client-server model. It uses TCP port number 25 for this service. Therefore e-mail; is delivered from source to destination by having the source machine established a TCP to port 25 of the destination machine. To send mail, a system must contain client MTA and to receive a mail, a system must have server MTA. SMTP transfers this message from client MTA to the server MTA. To send a mail, SMTP is used two times: one between sender and sender’s mail server and the other between the two mail servers. " }, { "code": null, "e": 862, "s": 605, "text": "SMTP Commands : These commands are sent from the client to the server. Each command consists of a keyword followed by zero or more arguments. It means there are also some keywords that do not contain any argument. The format of the command is as follows : " }, { "code": null, "e": 887, "s": 862, "text": " Keywords : argument(s) " }, { "code": null, "e": 966, "s": 887, "text": "There are 14 different SMTP commands which are given in the following table : " }, { "code": null, "e": 982, "s": 968, "text": "avtarkumar719" }, { "code": null, "e": 1000, "s": 982, "text": "Computer Networks" }, { "code": null, "e": 1008, "s": 1000, "text": "GATE CS" }, { "code": null, "e": 1026, "s": 1008, "text": "Computer Networks" }, { "code": null, "e": 1124, "s": 1026, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1154, "s": 1124, "text": "GSM in Wireless Communication" }, { "code": null, "e": 1184, "s": 1154, "text": "Wireless Application Protocol" }, { "code": null, "e": 1210, "s": 1184, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 1250, "s": 1210, "text": "Mobile Internet Protocol (or Mobile IP)" }, { "code": null, "e": 1285, "s": 1250, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 1309, "s": 1285, "text": "ACID Properties in DBMS" }, { "code": null, "e": 1336, "s": 1309, "text": "Types of Operating Systems" }, { "code": null, "e": 1357, "s": 1336, "text": "Normal Forms in DBMS" }, { "code": null, "e": 1406, "s": 1357, "text": "Page Replacement Algorithms in Operating Systems" } ]
R – Bar Charts
21 Apr, 2020 A bar chart is a pictorial representation of data that presents categorical data with rectangular bars with heights or lengths proportional to the values that they represent. In other words, it is the pictorial representation of dataset. These data sets contain the numerical values of variables that represent the length or height. R uses the function barplot() to create bar charts. Here, both vertical and Horizontal bars can be drawn. Syntax: barplot(H, xlab, ylab, main, names.arg, col) Parameters: H: This parameter is a vector or matrix containing numeric values which are used in bar chart. xlab: This parameter is the label for x axis in bar chart. ylab: This parameter is the label for y axis in bar chart. main: This parameter is the title of the bar chart. names.arg: This parameter is a vector of names appearing under each bar in bar chart. col: This parameter is used to give colors to the bars in the graph. Approach: In order to create a Bar Chart: A vector (H <- c(Values...)) is taken which contain numeral values to be used.This vector H is plot using barplot(). A vector (H <- c(Values...)) is taken which contain numeral values to be used. This vector H is plot using barplot(). Example: # Create the data for the chartA <- c(17, 32, 8, 53, 1) # Plot the bar chart barplot(A, xlab = "X-axis", ylab = "Y-axis", main ="Bar-Chart") Output: Approach: To create a horizontal bar chart: Take all parameters which are required to make simple bar chart.Now to make it horizontal new parameter is added.barplot(A, horiz=TRUE ) Take all parameters which are required to make simple bar chart. Now to make it horizontal new parameter is added.barplot(A, horiz=TRUE ) barplot(A, horiz=TRUE ) Example: Creating a horizontal bar chart # Create the data for the chartA <- c(17, 32, 8, 53, 1) # Plot the bar chart barplot(A, horiz = TRUE, xlab = "X-axis", ylab = "Y-axis", main ="Bar-Chart") Output: Label, title and colors are some properties in the bar chart which can be added to the bar by adding and passing an argument.Approach: To add the title in bar chart.barplot( A, main = title_name )X-axis and Y-axis can be labeled in bar chart. To add the label in bar chart.barplot( A, xlab= x_label_name, ylab= y_label_name)To add the color in bar chart.barplot( A, col=color_name) To add the title in bar chart.barplot( A, main = title_name ) barplot( A, main = title_name ) X-axis and Y-axis can be labeled in bar chart. To add the label in bar chart.barplot( A, xlab= x_label_name, ylab= y_label_name) barplot( A, xlab= x_label_name, ylab= y_label_name) To add the color in bar chart.barplot( A, col=color_name) barplot( A, col=color_name) Example : # Create the data for the chartA <- c(17, 2, 8, 13, 1, 22)B <- c("Jan", "feb", "Mar", "Apr", "May", "Jun") # Plot the bar chart barplot(A, names.arg = B, xlab ="Month", ylab ="Articles", col ="green", main ="GeeksforGeeks-Article chart") Output: The bar chart can be represented in two form group of bars and stacked.Approach: Take a vector value and make it matrix M which to be grouped or stacked. Making of matrix can be done by.M <- matrix(c(values...), nrow = no_of_rows, ncol = no_of_column, byrow = TRUE)To display the bar explicitly we can use the beside parameter.barplot( beside=TRUE ) Take a vector value and make it matrix M which to be grouped or stacked. Making of matrix can be done by.M <- matrix(c(values...), nrow = no_of_rows, ncol = no_of_column, byrow = TRUE) M <- matrix(c(values...), nrow = no_of_rows, ncol = no_of_column, byrow = TRUE) To display the bar explicitly we can use the beside parameter.barplot( beside=TRUE ) barplot( beside=TRUE ) Example 1: colors = c("green", "orange", "brown")months <- c("Mar", "Apr", "May", "Jun", "Jul")regions <- c("East", "West", "North") # Create the matrix of the values.Values <- matrix(c(2, 9, 3, 11, 9, 4, 8, 7, 3, 12, 5, 2, 8, 10, 11), nrow = 3, ncol = 5, byrow = TRUE) # Create the bar chartbarplot(Values, main = "Total Revenue", names.arg = months, xlab = "Month", ylab = "Revenue", col = colors, beside = TRUE) # Add the legend to the chartlegend("topleft", regions, cex = 0.7, fill = colors) Output: Example 2: colors = c("green", "orange", "brown")months <- c("Mar", "Apr", "May", "Jun", "Jul")regions <- c("East", "West", "North") # Create the matrix of the values.Values <- matrix(c(2, 9, 3, 11, 9, 4, 8, 7, 3, 12, 5, 2, 8, 10, 11), nrow = 3, ncol = 5, byrow = TRUE) # Create the bar chartbarplot(Values, main = "Total Revenue", names.arg = months, xlab = "Month", ylab = "Revenue", col = colors) # Add the legend to the chartlegend("topleft", regions, cex = 0.7, fill = colors) Output: Picked R-plots R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change column name of a given DataFrame in R Filter data by multiple conditions in R using Dplyr How to Replace specific values in column in R DataFrame ? Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Loops in R (for, while, repeat) Adding elements in a vector in R programming - append() method Group by function in R using Dplyr How to change Row Names of DataFrame in R ? Convert Factor to Numeric and Numeric to Factor in R Programming
[ { "code": null, "e": 53, "s": 25, "text": "\n21 Apr, 2020" }, { "code": null, "e": 386, "s": 53, "text": "A bar chart is a pictorial representation of data that presents categorical data with rectangular bars with heights or lengths proportional to the values that they represent. In other words, it is the pictorial representation of dataset. These data sets contain the numerical values of variables that represent the length or height." }, { "code": null, "e": 492, "s": 386, "text": "R uses the function barplot() to create bar charts. Here, both vertical and Horizontal bars can be drawn." }, { "code": null, "e": 500, "s": 492, "text": "Syntax:" }, { "code": null, "e": 545, "s": 500, "text": "barplot(H, xlab, ylab, main, names.arg, col)" }, { "code": null, "e": 557, "s": 545, "text": "Parameters:" }, { "code": null, "e": 652, "s": 557, "text": "H: This parameter is a vector or matrix containing numeric values which are used in bar chart." }, { "code": null, "e": 711, "s": 652, "text": "xlab: This parameter is the label for x axis in bar chart." }, { "code": null, "e": 770, "s": 711, "text": "ylab: This parameter is the label for y axis in bar chart." }, { "code": null, "e": 822, "s": 770, "text": "main: This parameter is the title of the bar chart." }, { "code": null, "e": 908, "s": 822, "text": "names.arg: This parameter is a vector of names appearing under each bar in bar chart." }, { "code": null, "e": 977, "s": 908, "text": "col: This parameter is used to give colors to the bars in the graph." }, { "code": null, "e": 1019, "s": 977, "text": "Approach: In order to create a Bar Chart:" }, { "code": null, "e": 1136, "s": 1019, "text": "A vector (H <- c(Values...)) is taken which contain numeral values to be used.This vector H is plot using barplot()." }, { "code": null, "e": 1215, "s": 1136, "text": "A vector (H <- c(Values...)) is taken which contain numeral values to be used." }, { "code": null, "e": 1254, "s": 1215, "text": "This vector H is plot using barplot()." }, { "code": null, "e": 1263, "s": 1254, "text": "Example:" }, { "code": "# Create the data for the chartA <- c(17, 32, 8, 53, 1) # Plot the bar chart barplot(A, xlab = \"X-axis\", ylab = \"Y-axis\", main =\"Bar-Chart\")", "e": 1405, "s": 1263, "text": null }, { "code": null, "e": 1413, "s": 1405, "text": "Output:" }, { "code": null, "e": 1457, "s": 1413, "text": "Approach: To create a horizontal bar chart:" }, { "code": null, "e": 1594, "s": 1457, "text": "Take all parameters which are required to make simple bar chart.Now to make it horizontal new parameter is added.barplot(A, horiz=TRUE )" }, { "code": null, "e": 1659, "s": 1594, "text": "Take all parameters which are required to make simple bar chart." }, { "code": null, "e": 1732, "s": 1659, "text": "Now to make it horizontal new parameter is added.barplot(A, horiz=TRUE )" }, { "code": null, "e": 1756, "s": 1732, "text": "barplot(A, horiz=TRUE )" }, { "code": null, "e": 1797, "s": 1756, "text": "Example: Creating a horizontal bar chart" }, { "code": "# Create the data for the chartA <- c(17, 32, 8, 53, 1) # Plot the bar chart barplot(A, horiz = TRUE, xlab = \"X-axis\", ylab = \"Y-axis\", main =\"Bar-Chart\")", "e": 1961, "s": 1797, "text": null }, { "code": null, "e": 1969, "s": 1961, "text": "Output:" }, { "code": null, "e": 2104, "s": 1969, "text": "Label, title and colors are some properties in the bar chart which can be added to the bar by adding and passing an argument.Approach:" }, { "code": null, "e": 2351, "s": 2104, "text": "To add the title in bar chart.barplot( A, main = title_name )X-axis and Y-axis can be labeled in bar chart. To add the label in bar chart.barplot( A, xlab= x_label_name, ylab= y_label_name)To add the color in bar chart.barplot( A, col=color_name)" }, { "code": null, "e": 2413, "s": 2351, "text": "To add the title in bar chart.barplot( A, main = title_name )" }, { "code": null, "e": 2445, "s": 2413, "text": "barplot( A, main = title_name )" }, { "code": null, "e": 2574, "s": 2445, "text": "X-axis and Y-axis can be labeled in bar chart. To add the label in bar chart.barplot( A, xlab= x_label_name, ylab= y_label_name)" }, { "code": null, "e": 2626, "s": 2574, "text": "barplot( A, xlab= x_label_name, ylab= y_label_name)" }, { "code": null, "e": 2684, "s": 2626, "text": "To add the color in bar chart.barplot( A, col=color_name)" }, { "code": null, "e": 2712, "s": 2684, "text": "barplot( A, col=color_name)" }, { "code": null, "e": 2722, "s": 2712, "text": "Example :" }, { "code": "# Create the data for the chartA <- c(17, 2, 8, 13, 1, 22)B <- c(\"Jan\", \"feb\", \"Mar\", \"Apr\", \"May\", \"Jun\") # Plot the bar chart barplot(A, names.arg = B, xlab =\"Month\", ylab =\"Articles\", col =\"green\", main =\"GeeksforGeeks-Article chart\")", "e": 2977, "s": 2722, "text": null }, { "code": null, "e": 2985, "s": 2977, "text": "Output:" }, { "code": null, "e": 3066, "s": 2985, "text": "The bar chart can be represented in two form group of bars and stacked.Approach:" }, { "code": null, "e": 3335, "s": 3066, "text": "Take a vector value and make it matrix M which to be grouped or stacked. Making of matrix can be done by.M <- matrix(c(values...), nrow = no_of_rows, ncol = no_of_column, byrow = TRUE)To display the bar explicitly we can use the beside parameter.barplot( beside=TRUE )" }, { "code": null, "e": 3520, "s": 3335, "text": "Take a vector value and make it matrix M which to be grouped or stacked. Making of matrix can be done by.M <- matrix(c(values...), nrow = no_of_rows, ncol = no_of_column, byrow = TRUE)" }, { "code": null, "e": 3600, "s": 3520, "text": "M <- matrix(c(values...), nrow = no_of_rows, ncol = no_of_column, byrow = TRUE)" }, { "code": null, "e": 3685, "s": 3600, "text": "To display the bar explicitly we can use the beside parameter.barplot( beside=TRUE )" }, { "code": null, "e": 3708, "s": 3685, "text": "barplot( beside=TRUE )" }, { "code": null, "e": 3719, "s": 3708, "text": "Example 1:" }, { "code": "colors = c(\"green\", \"orange\", \"brown\")months <- c(\"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\")regions <- c(\"East\", \"West\", \"North\") # Create the matrix of the values.Values <- matrix(c(2, 9, 3, 11, 9, 4, 8, 7, 3, 12, 5, 2, 8, 10, 11), nrow = 3, ncol = 5, byrow = TRUE) # Create the bar chartbarplot(Values, main = \"Total Revenue\", names.arg = months, xlab = \"Month\", ylab = \"Revenue\", col = colors, beside = TRUE) # Add the legend to the chartlegend(\"topleft\", regions, cex = 0.7, fill = colors)", "e": 4277, "s": 3719, "text": null }, { "code": null, "e": 4285, "s": 4277, "text": "Output:" }, { "code": null, "e": 4296, "s": 4285, "text": "Example 2:" }, { "code": "colors = c(\"green\", \"orange\", \"brown\")months <- c(\"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\")regions <- c(\"East\", \"West\", \"North\") # Create the matrix of the values.Values <- matrix(c(2, 9, 3, 11, 9, 4, 8, 7, 3, 12, 5, 2, 8, 10, 11), nrow = 3, ncol = 5, byrow = TRUE) # Create the bar chartbarplot(Values, main = \"Total Revenue\", names.arg = months, xlab = \"Month\", ylab = \"Revenue\", col = colors) # Add the legend to the chartlegend(\"topleft\", regions, cex = 0.7, fill = colors)", "e": 4799, "s": 4296, "text": null }, { "code": null, "e": 4807, "s": 4799, "text": "Output:" }, { "code": null, "e": 4814, "s": 4807, "text": "Picked" }, { "code": null, "e": 4822, "s": 4814, "text": "R-plots" }, { "code": null, "e": 4833, "s": 4822, "text": "R Language" }, { "code": null, "e": 4931, "s": 4833, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4976, "s": 4931, "text": "Change column name of a given DataFrame in R" }, { "code": null, "e": 5028, "s": 4976, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 5086, "s": 5028, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 5138, "s": 5086, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 5196, "s": 5138, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 5228, "s": 5196, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 5291, "s": 5228, "text": "Adding elements in a vector in R programming - append() method" }, { "code": null, "e": 5326, "s": 5291, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 5370, "s": 5326, "text": "How to change Row Names of DataFrame in R ?" } ]
Count minimum number of subsets (or subsequences) with consecutive numbers
06 Jul, 2022 Given an array of distinct positive numbers, the task is to calculate the number of subsets (or subsequences) from the array such that each subset contains consecutive numbers. Examples: Input : arr[] = {100, 56, 5, 6, 102, 58, 101, 57, 7, 103, 59} Output : 3 {5, 6, 7}, { 56, 57, 58, 59}, {100, 101, 102, 103} are 3 subset in which numbers are consecutive. Input : arr[] = {10, 100, 105} Output : 3 {10}, {100} and {105} are 3 subset in which numbers are consecutive. The idea is to sort the array and traverse the sorted array to count the number of such subsets. To count the number of such subsets, we need to count the consecutive numbers such that the difference between them is not equal to one. Following is the algorithm for the finding number of subset containing consecutive numbers: 1. Sort the array arr[ ] and count = 1. 2. Traverse the sorted array and for each element arr[i]. If arr[i] + 1 != arr[i+1], then increment the count by one. 3. Return the count. Below is the implementation of this approach : C++ Java Python3 C# PHP Javascript // C++ program to find number of subset containing// consecutive numbers#include <bits/stdc++.h>using namespace std; // Returns count of subsets with consecutive numbersint numofsubset(int arr[], int n){ // Sort the array so that elements which are // consecutive in nature became consecutive // in the array. sort(arr, arr + n); int count = 1; // Initialize result for (int i = 0; i < n - 1; i++) { // Check if there is beginning of another // subset of consecutive number if (arr[i] + 1 != arr[i + 1]) count++; } return count;} // Driven Programint main(){ int arr[] = { 100, 56, 5, 6, 102, 58, 101, 57, 7, 103, 59 }; int n = sizeof(arr) / sizeof(arr[0]); cout << numofsubset(arr, n) << endl; return 0;} // Java program to find number of subset// containing consecutive numbersimport java.util.*;class GFG { // Returns count of subsets with consecutive numbers static int numofsubset(int arr[], int n) { // Sort the array so that elements // which are consecutive in nature // became consecutive in the array. Arrays.sort(arr); // Initialize result int count = 1; for (int i = 0; i < n - 1; i++) { // Check if there is beginning // of another subset of // consecutive number if (arr[i] + 1 != arr[i + 1]) count++; } return count; } // Driven Program public static void main(String[] args) { int arr[] = { 100, 56, 5, 6, 102, 58, 101, 57, 7, 103, 59 }; int n = arr.length; System.out.println(numofsubset(arr, n)); }} // This code is contributed by prerna saini. # Python program to find number of subset containing# consecutive numbersdef numofsubset(arr, n): # Sort the array so that elements which are consecutive # in nature became consecutive in the array. x = sorted(arr) count = 1 for i in range(0, n-1): # Check if there is beginning of another subset of # consecutive number if (x[i] + 1 != x[i + 1]): count = count + 1 return count # Driven Programarr = [ 100, 56, 5, 6, 102, 58, 101, 57, 7, 103, 59 ]n = len(arr)print (numofsubset(arr, n)) # This code is contributed by Afzal Ansari. // C# program to find number of subset// containing consecutive numbersusing System; class GFG { // Returns count of subsets with // consecutive numbers static int numofsubset(int[] arr, int n) { // Sort the array so that elements // which are consecutive in nature // became consecutive in the array. Array.Sort(arr); // Initialize result int count = 1; for (int i = 0; i < n - 1; i++) { // Check if there is beginning // of another subset of // consecutive number if (arr[i] + 1 != arr[i + 1]) count++; } return count; } // Driven Program public static void Main() { int[] arr = { 100, 56, 5, 6, 102, 58, 101, 57, 7, 103, 59 }; int n = arr.Length; Console.WriteLine(numofsubset(arr, n)); }} // This code is contributed by vt_m. <?php// PHP program to find number// of subset containing// consecutive numbers // Returns count of subsets// with consecutive numbersfunction numofsubset( $arr, $n){ // Sort the array so that // elements which are // consecutive in nature // became consecutive // in the array. sort($arr); // Initialize result $count = 1; for ($i = 0; $i < $n - 1; $i++) { // Check if there is // beginning of another // subset of consecutive // number if ($arr[$i] + 1 != $arr[$i + 1]) $count++; } return $count;} // Driver Code $arr = array(100, 56, 5, 6, 102, 58, 101, 57, 7, 103, 59 ); $n = sizeof($arr); echo numofsubset($arr, $n); // This code is contributed by Anuj_67?> <script>// javascript program to find number of subset// containing consecutive numbers // Returns count of subsets with consecutive numbers function numofsubset(arr , n) { // Sort the array so that elements // which are consecutive in nature // became consecutive in the array. arr.sort((a,b)=>a-b); // Initialize result var count = 1; for (i = 0; i < n - 1; i++) { // Check if there is beginning // of another subset of // consecutive number if (arr[i] + 1 != arr[i + 1]) count++; } return count; } // Driven Program var arr = [ 100, 56, 5, 6, 102, 58, 101, 57, 7, 103, 59 ]; var n = arr.length; document.write(numofsubset(arr, n)); // This code contributed by Rajput-Ji</script> 3 Time Complexity : O(nlogn) Count minimum number of subsets (or subsequences) with consecutive numbers | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersCount minimum number of subsets (or subsequences) with consecutive numbers | GeeksforGeeksWatch 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:000:00 / 1:43β€’Liveβ€’<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=EOw1Of_ZwPU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Anuj Chauhan(anuj0503). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. vt_m Rajput-Ji amartyaghoshgfg hardikkoriintern subsequence subset Arrays Sorting Arrays Sorting subset Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Merge Sort Bubble Sort Algorithm QuickSort Insertion Sort Selection Sort Algorithm
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2022" }, { "code": null, "e": 229, "s": 52, "text": "Given an array of distinct positive numbers, the task is to calculate the number of subsets (or subsequences) from the array such that each subset contains consecutive numbers." }, { "code": null, "e": 240, "s": 229, "text": "Examples: " }, { "code": null, "e": 556, "s": 240, "text": "Input : arr[] = {100, 56, 5, 6, 102, 58, \n 101, 57, 7, 103, 59}\nOutput : 3\n{5, 6, 7}, { 56, 57, 58, 59}, {100, 101, 102, 103}\nare 3 subset in which numbers are consecutive.\n\nInput : arr[] = {10, 100, 105}\nOutput : 3\n{10}, {100} and {105} are 3 subset in which \nnumbers are consecutive. " }, { "code": null, "e": 790, "s": 556, "text": "The idea is to sort the array and traverse the sorted array to count the number of such subsets. To count the number of such subsets, we need to count the consecutive numbers such that the difference between them is not equal to one." }, { "code": null, "e": 883, "s": 790, "text": "Following is the algorithm for the finding number of subset containing consecutive numbers: " }, { "code": null, "e": 1074, "s": 883, "text": "1. Sort the array arr[ ] and count = 1.\n2. Traverse the sorted array and for each element arr[i].\n If arr[i] + 1 != arr[i+1], \n then increment the count by one.\n3. Return the count. " }, { "code": null, "e": 1123, "s": 1074, "text": "Below is the implementation of this approach : " }, { "code": null, "e": 1127, "s": 1123, "text": "C++" }, { "code": null, "e": 1132, "s": 1127, "text": "Java" }, { "code": null, "e": 1140, "s": 1132, "text": "Python3" }, { "code": null, "e": 1143, "s": 1140, "text": "C#" }, { "code": null, "e": 1147, "s": 1143, "text": "PHP" }, { "code": null, "e": 1158, "s": 1147, "text": "Javascript" }, { "code": "// C++ program to find number of subset containing// consecutive numbers#include <bits/stdc++.h>using namespace std; // Returns count of subsets with consecutive numbersint numofsubset(int arr[], int n){ // Sort the array so that elements which are // consecutive in nature became consecutive // in the array. sort(arr, arr + n); int count = 1; // Initialize result for (int i = 0; i < n - 1; i++) { // Check if there is beginning of another // subset of consecutive number if (arr[i] + 1 != arr[i + 1]) count++; } return count;} // Driven Programint main(){ int arr[] = { 100, 56, 5, 6, 102, 58, 101, 57, 7, 103, 59 }; int n = sizeof(arr) / sizeof(arr[0]); cout << numofsubset(arr, n) << endl; return 0;}", "e": 1951, "s": 1158, "text": null }, { "code": "// Java program to find number of subset// containing consecutive numbersimport java.util.*;class GFG { // Returns count of subsets with consecutive numbers static int numofsubset(int arr[], int n) { // Sort the array so that elements // which are consecutive in nature // became consecutive in the array. Arrays.sort(arr); // Initialize result int count = 1; for (int i = 0; i < n - 1; i++) { // Check if there is beginning // of another subset of // consecutive number if (arr[i] + 1 != arr[i + 1]) count++; } return count; } // Driven Program public static void main(String[] args) { int arr[] = { 100, 56, 5, 6, 102, 58, 101, 57, 7, 103, 59 }; int n = arr.length; System.out.println(numofsubset(arr, n)); }} // This code is contributed by prerna saini.", "e": 2900, "s": 1951, "text": null }, { "code": "# Python program to find number of subset containing# consecutive numbersdef numofsubset(arr, n): # Sort the array so that elements which are consecutive # in nature became consecutive in the array. x = sorted(arr) count = 1 for i in range(0, n-1): # Check if there is beginning of another subset of # consecutive number if (x[i] + 1 != x[i + 1]): count = count + 1 return count # Driven Programarr = [ 100, 56, 5, 6, 102, 58, 101, 57, 7, 103, 59 ]n = len(arr)print (numofsubset(arr, n)) # This code is contributed by Afzal Ansari.", "e": 3460, "s": 2900, "text": null }, { "code": "// C# program to find number of subset// containing consecutive numbersusing System; class GFG { // Returns count of subsets with // consecutive numbers static int numofsubset(int[] arr, int n) { // Sort the array so that elements // which are consecutive in nature // became consecutive in the array. Array.Sort(arr); // Initialize result int count = 1; for (int i = 0; i < n - 1; i++) { // Check if there is beginning // of another subset of // consecutive number if (arr[i] + 1 != arr[i + 1]) count++; } return count; } // Driven Program public static void Main() { int[] arr = { 100, 56, 5, 6, 102, 58, 101, 57, 7, 103, 59 }; int n = arr.Length; Console.WriteLine(numofsubset(arr, n)); }} // This code is contributed by vt_m.", "e": 4409, "s": 3460, "text": null }, { "code": "<?php// PHP program to find number// of subset containing// consecutive numbers // Returns count of subsets// with consecutive numbersfunction numofsubset( $arr, $n){ // Sort the array so that // elements which are // consecutive in nature // became consecutive // in the array. sort($arr); // Initialize result $count = 1; for ($i = 0; $i < $n - 1; $i++) { // Check if there is // beginning of another // subset of consecutive // number if ($arr[$i] + 1 != $arr[$i + 1]) $count++; } return $count;} // Driver Code $arr = array(100, 56, 5, 6, 102, 58, 101, 57, 7, 103, 59 ); $n = sizeof($arr); echo numofsubset($arr, $n); // This code is contributed by Anuj_67?>", "e": 5203, "s": 4409, "text": null }, { "code": "<script>// javascript program to find number of subset// containing consecutive numbers // Returns count of subsets with consecutive numbers function numofsubset(arr , n) { // Sort the array so that elements // which are consecutive in nature // became consecutive in the array. arr.sort((a,b)=>a-b); // Initialize result var count = 1; for (i = 0; i < n - 1; i++) { // Check if there is beginning // of another subset of // consecutive number if (arr[i] + 1 != arr[i + 1]) count++; } return count; } // Driven Program var arr = [ 100, 56, 5, 6, 102, 58, 101, 57, 7, 103, 59 ]; var n = arr.length; document.write(numofsubset(arr, n)); // This code contributed by Rajput-Ji</script>", "e": 6049, "s": 5203, "text": null }, { "code": null, "e": 6052, "s": 6049, "text": "3\n" }, { "code": null, "e": 6079, "s": 6052, "text": "Time Complexity : O(nlogn)" }, { "code": null, "e": 7045, "s": 6079, "text": "Count minimum number of subsets (or subsequences) with consecutive numbers | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersCount minimum number of subsets (or subsequences) with consecutive numbers | GeeksforGeeksWatch 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:000:00 / 1:43β€’Liveβ€’<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=EOw1Of_ZwPU\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 7352, "s": 7045, "text": "This article is contributed by Anuj Chauhan(anuj0503). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 7357, "s": 7352, "text": "vt_m" }, { "code": null, "e": 7367, "s": 7357, "text": "Rajput-Ji" }, { "code": null, "e": 7383, "s": 7367, "text": "amartyaghoshgfg" }, { "code": null, "e": 7400, "s": 7383, "text": "hardikkoriintern" }, { "code": null, "e": 7412, "s": 7400, "text": "subsequence" }, { "code": null, "e": 7419, "s": 7412, "text": "subset" }, { "code": null, "e": 7426, "s": 7419, "text": "Arrays" }, { "code": null, "e": 7434, "s": 7426, "text": "Sorting" }, { "code": null, "e": 7441, "s": 7434, "text": "Arrays" }, { "code": null, "e": 7449, "s": 7441, "text": "Sorting" }, { "code": null, "e": 7456, "s": 7449, "text": "subset" }, { "code": null, "e": 7554, "s": 7456, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7622, "s": 7554, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 7666, "s": 7622, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 7698, "s": 7666, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 7746, "s": 7698, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 7760, "s": 7746, "text": "Linear Search" }, { "code": null, "e": 7771, "s": 7760, "text": "Merge Sort" }, { "code": null, "e": 7793, "s": 7771, "text": "Bubble Sort Algorithm" }, { "code": null, "e": 7803, "s": 7793, "text": "QuickSort" }, { "code": null, "e": 7818, "s": 7803, "text": "Insertion Sort" } ]
How to create Donghnut chart in react using material UI and DevExpress ?
19 Jul, 2021 DevExpress: DevExpress is a package for controlling and building the user interface of the Window, Mobile, and other applications. Doughnut Charts: Doughnut charts are the modified version of Pie Charts with the area of center cut out. A donut is more concerned about the use of an area of arcs to represent the information in the most effective manner instead of Pie chart which is more focused on comparing the proportion area between the slices. Steps for creating React Application And Installing Module: Step 1: Create a React application using the following command.npx create-react-app foldername Step 1: Create a React application using the following command. npx create-react-app foldername Step 2: After creating your project folder i.e. folder name, move to it using the following command.cd foldername Step 2: After creating your project folder i.e. folder name, move to it using the following command. cd foldername Step 3: After creating the ReactJS application, install the required modules using the following command.npm i --save @devexpress/dx-react-core @devexpress/dx-react-chart npm install @material-ui/core npm i --save @devexpress/dx-react-chart-material-ui Step 3: After creating the ReactJS application, install the required modules using the following command. npm i --save @devexpress/dx-react-core @devexpress/dx-react-chart npm install @material-ui/core npm i --save @devexpress/dx-react-chart-material-ui Project Structure: It will look like the following : Project Structure Example: Now write down the following code in the App.js file. Here, the App is our default component where we have written our code. App.js import React from "react";import Paper from '@material-ui/core/Paper';import { Chart, PieSeries, Title} from '@devexpress/dx-react-chart-material-ui'; const App = () => { // Sample dataconst data = [ { argument:'Monday', value:10 }, { argument:'Tuesday', value:40 }, { argument:'Wednesday', value:10 }, { argument:'Thursday', value:20 }, { argument:'Friday', value:20 },];return ( <Paper> <Chart data={data} > <PieSeries valueField="value" argumentField="argument" innerRadius={0.6} /> <Title text="Studies per day"/> </Chart> </Paper>);} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Output Material-UI Picked React-Questions JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners JavaScript | Promises How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? Axios in React: A Guide for Beginners ReactJS Functional Components
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Jul, 2021" }, { "code": null, "e": 159, "s": 28, "text": "DevExpress: DevExpress is a package for controlling and building the user interface of the Window, Mobile, and other applications." }, { "code": null, "e": 478, "s": 159, "text": "Doughnut Charts: Doughnut charts are the modified version of Pie Charts with the area of center cut out. A donut is more concerned about the use of an area of arcs to represent the information in the most effective manner instead of Pie chart which is more focused on comparing the proportion area between the slices. " }, { "code": null, "e": 538, "s": 478, "text": "Steps for creating React Application And Installing Module:" }, { "code": null, "e": 633, "s": 538, "text": "Step 1: Create a React application using the following command.npx create-react-app foldername" }, { "code": null, "e": 697, "s": 633, "text": "Step 1: Create a React application using the following command." }, { "code": null, "e": 729, "s": 697, "text": "npx create-react-app foldername" }, { "code": null, "e": 845, "s": 731, "text": "Step 2: After creating your project folder i.e. folder name, move to it using the following command.cd foldername" }, { "code": null, "e": 946, "s": 845, "text": "Step 2: After creating your project folder i.e. folder name, move to it using the following command." }, { "code": null, "e": 960, "s": 946, "text": "cd foldername" }, { "code": null, "e": 1213, "s": 960, "text": "Step 3: After creating the ReactJS application, install the required modules using the following command.npm i --save @devexpress/dx-react-core @devexpress/dx-react-chart\nnpm install @material-ui/core\nnpm i --save @devexpress/dx-react-chart-material-ui" }, { "code": null, "e": 1319, "s": 1213, "text": "Step 3: After creating the ReactJS application, install the required modules using the following command." }, { "code": null, "e": 1467, "s": 1319, "text": "npm i --save @devexpress/dx-react-core @devexpress/dx-react-chart\nnpm install @material-ui/core\nnpm i --save @devexpress/dx-react-chart-material-ui" }, { "code": null, "e": 1520, "s": 1467, "text": "Project Structure: It will look like the following :" }, { "code": null, "e": 1538, "s": 1520, "text": "Project Structure" }, { "code": null, "e": 1672, "s": 1538, "text": "Example: Now write down the following code in the App.js file. Here, the App is our default component where we have written our code." }, { "code": null, "e": 1679, "s": 1672, "text": "App.js" }, { "code": "import React from \"react\";import Paper from '@material-ui/core/Paper';import { Chart, PieSeries, Title} from '@devexpress/dx-react-chart-material-ui'; const App = () => { // Sample dataconst data = [ { argument:'Monday', value:10 }, { argument:'Tuesday', value:40 }, { argument:'Wednesday', value:10 }, { argument:'Thursday', value:20 }, { argument:'Friday', value:20 },];return ( <Paper> <Chart data={data} > <PieSeries valueField=\"value\" argumentField=\"argument\" innerRadius={0.6} /> <Title text=\"Studies per day\"/> </Chart> </Paper>);} export default App;", "e": 2295, "s": 1679, "text": null }, { "code": null, "e": 2408, "s": 2295, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 2418, "s": 2408, "text": "npm start" }, { "code": null, "e": 2517, "s": 2418, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 2524, "s": 2517, "text": "Output" }, { "code": null, "e": 2536, "s": 2524, "text": "Material-UI" }, { "code": null, "e": 2543, "s": 2536, "text": "Picked" }, { "code": null, "e": 2559, "s": 2543, "text": "React-Questions" }, { "code": null, "e": 2570, "s": 2559, "text": "JavaScript" }, { "code": null, "e": 2578, "s": 2570, "text": "ReactJS" }, { "code": null, "e": 2595, "s": 2578, "text": "Web Technologies" }, { "code": null, "e": 2693, "s": 2595, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2754, "s": 2693, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2794, "s": 2754, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2835, "s": 2794, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2877, "s": 2835, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 2899, "s": 2877, "text": "JavaScript | Promises" }, { "code": null, "e": 2942, "s": 2899, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 2987, "s": 2942, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 3025, "s": 2987, "text": "Axios in React: A Guide for Beginners" } ]
Josephus problem | Set 1 (A O(n) Solution)
07 Jun, 2022 In computer science and mathematics, the Josephus Problem (or Josephus permutation) is a theoretical problem. Following is the problem statement: There are n people standing in a circle waiting to be executed. The counting out begins at some point in the circle and proceeds around the circle in a fixed direction. In each step, a certain number of people are skipped and the next person is executed. The elimination proceeds around the circle (which is becoming smaller and smaller as the executed people are removed), until only the last person remains, who is given freedom. Given the total number of person n and a number k which indicates that k-1 persons are skipped and the kth person is killed in a circle. The task is to choose the place in the initial circle so that you are the last one remaining and so survive.For example, if n = 5 and k = 2, then the safe position is 3. Firstly, the person at position 2 is killed, then the person at position 4 is killed, then the person at position 1 is killed. Finally, the person at position 5 is killed. So the person at position 3 survives. If n = 7 and k = 3, then the safe position is 4. The persons at positions 3, 6, 2, 7, 5, and 1 are killed in order, and the person at position 4 survives. The problem has the following recursive structure. josephus(n, k) = (josephus(n - 1, k) + k-1) % n + 1 josephus(1, k) = 1 After the first person (kth from the beginning) is killed, n-1 persons are left. So we call Josephus(n – 1, k) to get the position with n-1 persons. But the position returned by Josephus(n – 1, k) will consider the position starting from k%n + 1. So, we must make adjustments to the position returned by Josephus(n – 1, k). The following is a simple recursive implementation of the Josephus problem. The implementation simply follows the recursive structure mentioned above. Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. C++ C Java Python3 C# PHP Javascript #include <iostream>using namespace std; int josephus(int n, int k){ if (n == 1) return 1; else /* The position returned by josephus(n - 1, k) is adjusted because the recursive call josephus(n - 1, k) considers the original position k % n + 1 as position 1 */ return (josephus(n - 1, k) + k - 1) % n + 1;} // Driver Program to test above functionint main(){ int n = 14; int k = 2; cout << "The chosen place is " << josephus(n, k); return 0;} // This code is contributed by shubhamsingh10 #include <stdio.h> int josephus(int n, int k){ if (n == 1) return 1; else /* The position returned by josephus(n - 1, k) is adjusted because the recursive call josephus(n - 1, k) considers the original position k%n + 1 as position 1 */ return (josephus(n - 1, k) + k - 1) % n + 1;} // Driver Program to test above functionint main(){ int n = 14; int k = 2; printf("The chosen place is %d", josephus(n, k)); return 0;} // Java code for Josephus Problemimport java.io.*; class GFG { static int josephus(int n, int k) { if (n == 1) return 1; else /* The position returned by josephus(n - 1, k) is adjusted because the recursive call josephus(n - 1, k) considers the original position k%n + 1 as position 1 */ return (josephus(n - 1, k) + k - 1) % n + 1; } // Driver Program to test above function public static void main(String[] args) { int n = 14; int k = 2; System.out.println("The chosen place is " + josephus(n, k)); }} // This code is contributed by Prerna Saini # Python code for Josephus Problem def josephus(n, k): if (n == 1): return 1 else: # The position returned by # josephus(n - 1, k) is adjusted # because the recursive call # josephus(n - 1, k) considers # the original position # k%n + 1 as position 1 return (josephus(n - 1, k) + k-1) % n + 1 # Driver Program to test above function n = 14k = 2 print("The chosen place is ", josephus(n, k)) # This code is contributed by# Sumit Sadhakar // C# code for Josephus Problemusing System; class GFG { static int josephus(int n, int k) { if (n == 1) return 1; else /* The position returned by josephus(n - 1, k) is adjusted because the recursive call josephus(n - 1, k) considers the original position k%n + 1 as position 1 */ return (josephus(n - 1, k) + k - 1) % n + 1; } // Driver Program to test above // function public static void Main() { int n = 14; int k = 2; Console.WriteLine("The chosen " + "place is " + josephus(n, k)); }} // This code is contributed by anuj_67. <?php// PHP code for// Josephus Problem function josephus($n, $k){ if ($n == 1) return 1; else /* The position returned by josephus(n - 1, k) is adjusted because the recursive call josephus (n - 1, k) considers the original position k%n + 1 as position 1 */ return (josephus($n - 1, $k) + $k - 1) % $n + 1;} // Driver Code $n = 14; $k = 2; echo "The chosen place is ", josephus($n, $k); // This code is contributed by ajit.?> <script> // Javascript code for Josephus Problem function josephus(n, k) { if (n == 1) return 1; else /* The position returned by josephus(n - 1, k) is adjusted because the recursive call josephus(n - 1, k) considers the original position k%n + 1 as position 1 */ return (josephus(n - 1, k) + k-1) % n + 1; } let n = 14; let k = 2; document.write("The chosen " + "place is " + josephus(n, k)); </script> The chosen place is 13 Time Complexity: O(n)Auxiliary Space: O(n) Another Approach using List: The simple approach is to create a list and add all values from 1 to n to it. Create a recursive function that takes a list, start (position at which counting will start), and k ( number of people to be skipped) as an argument. If the size of the list is one i.e. only one person left then return this position. Otherwise, start counting the k person in a clockwise direction from starting position and remove the person at the kth position. Now the person at the kth position is removed and now counting will start from this position. This process continues till only one person is left. pseudo-code : Josephus( list , start , k){ if list.size = 1 return list[0] start = (start + k) % list.size list.remove( start ) return Josephus( list, start, k) } C++ Code C++ Java Python3 C# Javascript #include <bits/stdc++.h> using namespace std; void Josh(vector<int> person, int k, int index){ // Base case , when only one person is left if (person.size() == 1) { cout << person[0] << endl; return; } // find the index of first person which will die index = ((index + k) % person.size()); // remove the first person which is going to be killed person.erase(person.begin() + index); // recursive call for n-1 persons Josh(person, k, index);} int main(){ int n = 14; // specific n and k values for original // josephus problem int k = 2; k--; // (k-1)th person will be killed int index = 0; // The index where the person which will die vector<int> person; // fill the person vector for (int i = 1; i <= n; i++) { person.push_back(i); } Josh(person, k, index);} import java.util.*; class GFG{ static void Josh(List<Integer> person, int k, int index) { // Base case , when only one person is left if (person.size() == 1) { System.out.println(person.get(0)); return; } // find the index of first person which will die index = ((index + k) % person.size()); // remove the first person which is going to be killed person.remove(index); // recursive call for n-1 persons Josh(person, k, index); } // Driver code public static void main(String [] args) { int n = 14; // specific n and k values for original // josephus problem int k = 2; k--; // (k-1)th person will be killed int index = 0; // The index where the person which will die List<Integer> person = new ArrayList<>(); // fill the person vector for (int i = 1; i <= n; i++) { person.add(i); } Josh(person, k, index); }} // This code is contributed by umadevi9616 # Python code for Josephus Problemdef Josh(person, k, index): # Base case , when only one person is left if len(person) == 1: print(person[0]) return # find the index of first person which will die index = ((index+k)%len(person)) # remove the first person which is going to be killed person.pop(index) # recursive call for n-1 persons Josh(person,k,index) # Driver Program to test above functionn = 14 # specific n and k values for original josephus problemk = 2k-=1 # (k-1)th person will be killed index = 0 # fill the person vectorperson=[]for i in range(1,n+1): person.append(i) Josh(person,k,index) # This code is contributed by# Gaurav Kandel using System;using System.Collections.Generic;class GFG { static void Josh(List<int> person, int k, int index) { // Base case , when only one person is left if (person.Count == 1) { Console.WriteLine(person[0]); return; } // find the index of first person which will die index = ((index + k) % person.Count); // remove the first person which is going to be killed person.RemoveAt(index); // recursive call for n-1 persons Josh(person, k, index); } // Driver code static void Main() { int n = 14; // specific n and k values for original // josephus problem int k = 2; k--; // (k-1)th person will be killed int index = 0; // The index where the person which will die List<int> person = new List<int>(); // fill the person vector for (int i = 1; i <= n; i++) { person.Add(i); } Josh(person, k, index); }} // This code is contributed by divyesh072019. <script> function Josh( person , k , index) { // Base case , when only one person is left if (person.length == 1) { document.write(person[0]); return; } // find the index of first person which will die index = ((index + k) % person.length); // remove the first person which is going to be killed if (index > -1) { person.splice(index, 1); } // recursive call for n-1 persons Josh(person, k, index); } // Driver code var n = 14; // specific n and k values for original // josephus problem var k = 2; k--; // (k-1)th person will be killed var index = 0; // The index where the person which will die var person = []; // fill the person vector for (var i = 1; i <= n; i++) { person.push(i); } Josh(person, k, index); // This code is contributed by umadevi9616</script> 13 Time Complexity: O(n2) Example : Input: n = 5, k = 2Output: 3 Explanation :Add all values from 1 to n in the list. We will call the recursive function with start = 0 and k = 1 (0-indexing) Now the element at 1-index (person number 2) will be killed. And it is removed from the list. The new counting will begin from 1-index, the person at 1-index killed so now person at 2-index (person number 3) comes to 1-index and counting starts from here now. Now we have 4 people, counting starting from 1-index (person number 3) and the person at kth (2-index ) position will be killed. The person at 2-index (person number 4) was killed so now we have 3 people left and the person (person number 5) at 3-index shifted to 2-index. And counting starts from here. The person at the 0-index was killed and we have now two-person left in the circle. And the person at 1-index shifted to 0-index i.e. person number 3. Final counting done and the person at 1-index killed and the only person who is left is at position 3. This is a solution to the Josephus problem in C++.For n = 47 and k = 5. C++ Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; int Josephus(int, int); int Josephus(int n, int k){ k--; int arr[n]; // Makes all the 'n' people alive by // assigning them value = 1 for (int i = 0; i < n; i++) { arr[i] = 1; } int cnt = 0, cut = 0, // Cut = 0 gives the sword to 1st person. num = 1; // Loop continues till n-1 person dies. while (cnt < (n - 1)) { // Checks next (kth) alive persons. while (num <= k) { cut++; // Checks and resolves overflow // of Index. cut = cut % n; if (arr[cut] == 1) { // Updates the number of persons // alive. num++; } } // Refreshes value to 1 for next use. num = 1; // Kills the person at position of 'cut' arr[cut] = 0; // Updates the no. of killed persons. cnt++; cut++; // Checks and resolves overflow of Index. cut = cut % n; // Checks the next alive person the // sword is to be given. while (arr[cut] == 0) { cut++; // Checks and resolves overflow // of Index. cut = cut % n; } } // Output is the position of the last // man alive(Index + 1); return cut + 1;} // Driver codeint main(){ int n = 14, k = 2; cout << Josephus(n, k); return 0;} // THIS CODE IS PRESENTED BY SHISHANK RAWAT // Java code to implement the above approachimport java.io.*;class GFG { public static void main(String[] args) { int n = 14, k = 2; System.out.println(Josephus(n, k)); } public static int Josephus(int n, int k) { k--; int arr[] = new int[n]; for (int i = 0; i < n; i++) { arr[i] = 1; // Makes all the 'n' people alive by // assigning them value = 1 } int cnt = 0, cut = 0, num = 1; // Cut = 0 gives the sword to 1st person. while ( cnt < (n - 1)) // Loop continues till n-1 person dies. { while (num <= k) // Checks next (kth) alive persons. { cut++; cut = cut % n; // Checks and resolves overflow // of Index. if (arr[cut] == 1) { num++; // Updates the number of persons // alive. } } num = 1; // refreshes value to 1 for next use. arr[cut] = 0; // Kills the person at position of // 'cut' cnt++; // Updates the no. of killed persons. cut++; cut = cut % n; // Checks and resolves overflow // of Index. while (arr[cut] == 0) // Checks the next alive person the // sword is to be given. { cut++; cut = cut % n; // Checks and resolves overflow // of Index. } } return cut + 1; // Output is the position of the last // man alive(Index + 1); }} // This code is contributed by Shubham Singh def Josephus(n, k): k -= 1 arr = [0]*n for i in range(n): arr[i] = 1 # Makes all the 'n' people alive by # assigning them value = 1 cnt = 0 cut = 0 num = 1 # Cut = 0 gives the sword to 1st person. while (cnt < (n - 1)): # Loop continues till n-1 person dies. while (num <= k): # Checks next (kth) alive persons. cut += 1 cut = cut % n # Checks and resolves overflow # of Index. if (arr[cut] == 1): num+=1 # Updates the number of persons # alive. num = 1 # refreshes value to 1 for next use. arr[cut] = 0 # Kills the person at position of 'cut' cnt += 1 # Updates the no. of killed persons. cut += 1 cut = cut % n # Checks and resolves overflow of Index. while (arr[cut] == 0): # Checks the next alive person the # sword is to be given. cut += 1 cut = cut % n # Checks and resolves overflow # of Index. return cut + 1 # Output is the position of the last # man alive(Index + 1) # Driver Coden, k = 14, 2 #map (int, input().splut())print(Josephus(n, k)) # This code is contributed by ShubhamSingh // C# code to implement the above approachusing System;using System.Linq; public class GFG{ public static void Main () { int n = 14, k = 2; Console.Write(Josephus(n, k)); } public static int Josephus(int n, int k) { k--; int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = 1; // Makes all the 'n' people alive by // assigning them value = 1 } int cnt = 0, cut = 0, num = 1; // Cut = 0 gives the sword to 1st person. while ( cnt < (n - 1)) // Loop continues till n-1 person dies. { while (num <= k) // Checks next (kth) alive persons. { cut++; cut = cut % n; // Checks and resolves overflow // of Index. if (arr[cut] == 1) { num++; // Updates the number of persons // alive. } } num = 1; // refreshes value to 1 for next use. arr[cut] = 0; // Kills the person at position of 'cut' cnt++; // Updates the no. of killed persons. cut++; cut = cut % n; // Checks and resolves overflow of Index. while (arr[cut] == 0) // Checks the next alive person the // sword is to be given. { cut++; cut = cut % n; // Checks and resolves overflow // of Index. } } return cut + 1; // Output is the position of the last // man alive(Index + 1); }} // This code is contributed by Shubham Singh <script> // Javascript code to implement the above approach let n = 14, k = 2; document.write(Josephus(n, k)); function Josephus(n, k) { k--; let arr = new Array(n); for (let i = 0; i < n; i++) { // Makes all the 'n' people alive by // assigning them value = 1 arr[i] = 1; } // Cut = 0 gives the sword to 1st person. let cnt = 0, cut = 0, num = 1; // Loop continues till n-1 person dies. while (cnt < (n - 1)) { // Checks next (kth) alive persons. while (num <= k) { cut++; cut = cut % n; // Checks and resolves overflow // of Index. if (arr[cut] == 1) { // Updates the number of persons // alive. num++; } } // refreshes value to 1 for next use. num = 1; arr[cut] = 0; // Kills the person at position of 'cut' // Updates the no. of killed persons. cnt++; cut++; // Checks and resolves overflow of Index. cut = cut % n; // Checks the next alive person the // sword is to be given. while (arr[cut] == 0) { cut++; // Checks and resolves overflow // of Index. cut = cut % n; } } // Output is the position of the last // man alive(Index + 1); return cut + 1; } // This code is contributed by decode2207.</script> 13 Please visit set-2: Josephus problem | Set 2 (A Simple Solution when k = 2) Source: http://en.wikipedia.org/wiki/Josephus_problemPlease write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. jit_t vt_m Akanksha_Rai SHUBHAMSINGH10 hritikrommie sk1122 rameshtravel07 shishankrawt93774 RiteshYadav7 surindertarika1234 qwcllh9fr90rljmmxnhnev0o49esfddve93ojc2o subham348 divyesh072019 kandelgaurav7 surinderdawra388 umadevi9616 decode2207 harendrakumar123 Walmart Bit Magic Mathematical Recursion Walmart Mathematical Recursion Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Little and Big Endian Mystery Bits manipulation (Important tactics) Binary representation of a given number Add two numbers without using arithmetic operators Rotate bits of a number Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Operators in C / C++
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Jun, 2022" }, { "code": null, "e": 200, "s": 54, "text": "In computer science and mathematics, the Josephus Problem (or Josephus permutation) is a theoretical problem. Following is the problem statement:" }, { "code": null, "e": 1304, "s": 200, "text": "There are n people standing in a circle waiting to be executed. The counting out begins at some point in the circle and proceeds around the circle in a fixed direction. In each step, a certain number of people are skipped and the next person is executed. The elimination proceeds around the circle (which is becoming smaller and smaller as the executed people are removed), until only the last person remains, who is given freedom. Given the total number of person n and a number k which indicates that k-1 persons are skipped and the kth person is killed in a circle. The task is to choose the place in the initial circle so that you are the last one remaining and so survive.For example, if n = 5 and k = 2, then the safe position is 3. Firstly, the person at position 2 is killed, then the person at position 4 is killed, then the person at position 1 is killed. Finally, the person at position 5 is killed. So the person at position 3 survives. If n = 7 and k = 3, then the safe position is 4. The persons at positions 3, 6, 2, 7, 5, and 1 are killed in order, and the person at position 4 survives." }, { "code": null, "e": 1357, "s": 1304, "text": "The problem has the following recursive structure. " }, { "code": null, "e": 1432, "s": 1357, "text": " josephus(n, k) = (josephus(n - 1, k) + k-1) % n + 1\n josephus(1, k) = 1" }, { "code": null, "e": 1757, "s": 1432, "text": "After the first person (kth from the beginning) is killed, n-1 persons are left. So we call Josephus(n – 1, k) to get the position with n-1 persons. But the position returned by Josephus(n – 1, k) will consider the position starting from k%n + 1. So, we must make adjustments to the position returned by Josephus(n – 1, k). " }, { "code": null, "e": 1910, "s": 1757, "text": "The following is a simple recursive implementation of the Josephus problem. The implementation simply follows the recursive structure mentioned above. " }, { "code": null, "e": 1919, "s": 1910, "text": "Chapters" }, { "code": null, "e": 1946, "s": 1919, "text": "descriptions off, selected" }, { "code": null, "e": 1996, "s": 1946, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 2019, "s": 1996, "text": "captions off, selected" }, { "code": null, "e": 2027, "s": 2019, "text": "English" }, { "code": null, "e": 2051, "s": 2027, "text": "This is a modal window." }, { "code": null, "e": 2120, "s": 2051, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 2142, "s": 2120, "text": "End of dialog window." }, { "code": null, "e": 2146, "s": 2142, "text": "C++" }, { "code": null, "e": 2148, "s": 2146, "text": "C" }, { "code": null, "e": 2153, "s": 2148, "text": "Java" }, { "code": null, "e": 2161, "s": 2153, "text": "Python3" }, { "code": null, "e": 2164, "s": 2161, "text": "C#" }, { "code": null, "e": 2168, "s": 2164, "text": "PHP" }, { "code": null, "e": 2179, "s": 2168, "text": "Javascript" }, { "code": "#include <iostream>using namespace std; int josephus(int n, int k){ if (n == 1) return 1; else /* The position returned by josephus(n - 1, k) is adjusted because the recursive call josephus(n - 1, k) considers the original position k % n + 1 as position 1 */ return (josephus(n - 1, k) + k - 1) % n + 1;} // Driver Program to test above functionint main(){ int n = 14; int k = 2; cout << \"The chosen place is \" << josephus(n, k); return 0;} // This code is contributed by shubhamsingh10", "e": 2726, "s": 2179, "text": null }, { "code": "#include <stdio.h> int josephus(int n, int k){ if (n == 1) return 1; else /* The position returned by josephus(n - 1, k) is adjusted because the recursive call josephus(n - 1, k) considers the original position k%n + 1 as position 1 */ return (josephus(n - 1, k) + k - 1) % n + 1;} // Driver Program to test above functionint main(){ int n = 14; int k = 2; printf(\"The chosen place is %d\", josephus(n, k)); return 0;}", "e": 3213, "s": 2726, "text": null }, { "code": "// Java code for Josephus Problemimport java.io.*; class GFG { static int josephus(int n, int k) { if (n == 1) return 1; else /* The position returned by josephus(n - 1, k) is adjusted because the recursive call josephus(n - 1, k) considers the original position k%n + 1 as position 1 */ return (josephus(n - 1, k) + k - 1) % n + 1; } // Driver Program to test above function public static void main(String[] args) { int n = 14; int k = 2; System.out.println(\"The chosen place is \" + josephus(n, k)); }} // This code is contributed by Prerna Saini", "e": 3911, "s": 3213, "text": null }, { "code": "# Python code for Josephus Problem def josephus(n, k): if (n == 1): return 1 else: # The position returned by # josephus(n - 1, k) is adjusted # because the recursive call # josephus(n - 1, k) considers # the original position # k%n + 1 as position 1 return (josephus(n - 1, k) + k-1) % n + 1 # Driver Program to test above function n = 14k = 2 print(\"The chosen place is \", josephus(n, k)) # This code is contributed by# Sumit Sadhakar", "e": 4414, "s": 3911, "text": null }, { "code": "// C# code for Josephus Problemusing System; class GFG { static int josephus(int n, int k) { if (n == 1) return 1; else /* The position returned by josephus(n - 1, k) is adjusted because the recursive call josephus(n - 1, k) considers the original position k%n + 1 as position 1 */ return (josephus(n - 1, k) + k - 1) % n + 1; } // Driver Program to test above // function public static void Main() { int n = 14; int k = 2; Console.WriteLine(\"The chosen \" + \"place is \" + josephus(n, k)); }} // This code is contributed by anuj_67.", "e": 5131, "s": 4414, "text": null }, { "code": "<?php// PHP code for// Josephus Problem function josephus($n, $k){ if ($n == 1) return 1; else /* The position returned by josephus(n - 1, k) is adjusted because the recursive call josephus (n - 1, k) considers the original position k%n + 1 as position 1 */ return (josephus($n - 1, $k) + $k - 1) % $n + 1;} // Driver Code $n = 14; $k = 2; echo \"The chosen place is \", josephus($n, $k); // This code is contributed by ajit.?>", "e": 5676, "s": 5131, "text": null }, { "code": "<script> // Javascript code for Josephus Problem function josephus(n, k) { if (n == 1) return 1; else /* The position returned by josephus(n - 1, k) is adjusted because the recursive call josephus(n - 1, k) considers the original position k%n + 1 as position 1 */ return (josephus(n - 1, k) + k-1) % n + 1; } let n = 14; let k = 2; document.write(\"The chosen \" + \"place is \" + josephus(n, k)); </script>", "e": 6253, "s": 5676, "text": null }, { "code": null, "e": 6276, "s": 6253, "text": "The chosen place is 13" }, { "code": null, "e": 6319, "s": 6276, "text": "Time Complexity: O(n)Auxiliary Space: O(n)" }, { "code": null, "e": 6937, "s": 6319, "text": "Another Approach using List: The simple approach is to create a list and add all values from 1 to n to it. Create a recursive function that takes a list, start (position at which counting will start), and k ( number of people to be skipped) as an argument. If the size of the list is one i.e. only one person left then return this position. Otherwise, start counting the k person in a clockwise direction from starting position and remove the person at the kth position. Now the person at the kth position is removed and now counting will start from this position. This process continues till only one person is left." }, { "code": null, "e": 7120, "s": 6937, "text": "pseudo-code :\n\nJosephus( list , start , k){\n if list.size = 1\n return list[0]\n start = (start + k) % list.size\n list.remove( start )\n return Josephus( list, start, k)\n}" }, { "code": null, "e": 7129, "s": 7120, "text": "C++ Code" }, { "code": null, "e": 7133, "s": 7129, "text": "C++" }, { "code": null, "e": 7138, "s": 7133, "text": "Java" }, { "code": null, "e": 7146, "s": 7138, "text": "Python3" }, { "code": null, "e": 7149, "s": 7146, "text": "C#" }, { "code": null, "e": 7160, "s": 7149, "text": "Javascript" }, { "code": "#include <bits/stdc++.h> using namespace std; void Josh(vector<int> person, int k, int index){ // Base case , when only one person is left if (person.size() == 1) { cout << person[0] << endl; return; } // find the index of first person which will die index = ((index + k) % person.size()); // remove the first person which is going to be killed person.erase(person.begin() + index); // recursive call for n-1 persons Josh(person, k, index);} int main(){ int n = 14; // specific n and k values for original // josephus problem int k = 2; k--; // (k-1)th person will be killed int index = 0; // The index where the person which will die vector<int> person; // fill the person vector for (int i = 1; i <= n; i++) { person.push_back(i); } Josh(person, k, index);}", "e": 8023, "s": 7160, "text": null }, { "code": "import java.util.*; class GFG{ static void Josh(List<Integer> person, int k, int index) { // Base case , when only one person is left if (person.size() == 1) { System.out.println(person.get(0)); return; } // find the index of first person which will die index = ((index + k) % person.size()); // remove the first person which is going to be killed person.remove(index); // recursive call for n-1 persons Josh(person, k, index); } // Driver code public static void main(String [] args) { int n = 14; // specific n and k values for original // josephus problem int k = 2; k--; // (k-1)th person will be killed int index = 0; // The index where the person which will die List<Integer> person = new ArrayList<>(); // fill the person vector for (int i = 1; i <= n; i++) { person.add(i); } Josh(person, k, index); }} // This code is contributed by umadevi9616", "e": 8980, "s": 8023, "text": null }, { "code": "# Python code for Josephus Problemdef Josh(person, k, index): # Base case , when only one person is left if len(person) == 1: print(person[0]) return # find the index of first person which will die index = ((index+k)%len(person)) # remove the first person which is going to be killed person.pop(index) # recursive call for n-1 persons Josh(person,k,index) # Driver Program to test above functionn = 14 # specific n and k values for original josephus problemk = 2k-=1 # (k-1)th person will be killed index = 0 # fill the person vectorperson=[]for i in range(1,n+1): person.append(i) Josh(person,k,index) # This code is contributed by# Gaurav Kandel", "e": 9659, "s": 8980, "text": null }, { "code": "using System;using System.Collections.Generic;class GFG { static void Josh(List<int> person, int k, int index) { // Base case , when only one person is left if (person.Count == 1) { Console.WriteLine(person[0]); return; } // find the index of first person which will die index = ((index + k) % person.Count); // remove the first person which is going to be killed person.RemoveAt(index); // recursive call for n-1 persons Josh(person, k, index); } // Driver code static void Main() { int n = 14; // specific n and k values for original // josephus problem int k = 2; k--; // (k-1)th person will be killed int index = 0; // The index where the person which will die List<int> person = new List<int>(); // fill the person vector for (int i = 1; i <= n; i++) { person.Add(i); } Josh(person, k, index); }} // This code is contributed by divyesh072019.", "e": 10690, "s": 9659, "text": null }, { "code": "<script> function Josh( person , k , index) { // Base case , when only one person is left if (person.length == 1) { document.write(person[0]); return; } // find the index of first person which will die index = ((index + k) % person.length); // remove the first person which is going to be killed if (index > -1) { person.splice(index, 1); } // recursive call for n-1 persons Josh(person, k, index); } // Driver code var n = 14; // specific n and k values for original // josephus problem var k = 2; k--; // (k-1)th person will be killed var index = 0; // The index where the person which will die var person = []; // fill the person vector for (var i = 1; i <= n; i++) { person.push(i); } Josh(person, k, index); // This code is contributed by umadevi9616</script>", "e": 11661, "s": 10690, "text": null }, { "code": null, "e": 11665, "s": 11661, "text": "13\n" }, { "code": null, "e": 11688, "s": 11665, "text": "Time Complexity: O(n2)" }, { "code": null, "e": 11699, "s": 11688, "text": "Example : " }, { "code": null, "e": 11729, "s": 11699, "text": "Input: n = 5, k = 2Output: 3" }, { "code": null, "e": 11856, "s": 11729, "text": "Explanation :Add all values from 1 to n in the list. We will call the recursive function with start = 0 and k = 1 (0-indexing)" }, { "code": null, "e": 12116, "s": 11856, "text": "Now the element at 1-index (person number 2) will be killed. And it is removed from the list. The new counting will begin from 1-index, the person at 1-index killed so now person at 2-index (person number 3) comes to 1-index and counting starts from here now." }, { "code": null, "e": 12246, "s": 12116, "text": "Now we have 4 people, counting starting from 1-index (person number 3) and the person at kth (2-index ) position will be killed. " }, { "code": null, "e": 12421, "s": 12246, "text": "The person at 2-index (person number 4) was killed so now we have 3 people left and the person (person number 5) at 3-index shifted to 2-index. And counting starts from here." }, { "code": null, "e": 12572, "s": 12421, "text": "The person at the 0-index was killed and we have now two-person left in the circle. And the person at 1-index shifted to 0-index i.e. person number 3." }, { "code": null, "e": 12675, "s": 12572, "text": "Final counting done and the person at 1-index killed and the only person who is left is at position 3." }, { "code": null, "e": 12747, "s": 12675, "text": "This is a solution to the Josephus problem in C++.For n = 47 and k = 5." }, { "code": null, "e": 12751, "s": 12747, "text": "C++" }, { "code": null, "e": 12756, "s": 12751, "text": "Java" }, { "code": null, "e": 12764, "s": 12756, "text": "Python3" }, { "code": null, "e": 12767, "s": 12764, "text": "C#" }, { "code": null, "e": 12778, "s": 12767, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; int Josephus(int, int); int Josephus(int n, int k){ k--; int arr[n]; // Makes all the 'n' people alive by // assigning them value = 1 for (int i = 0; i < n; i++) { arr[i] = 1; } int cnt = 0, cut = 0, // Cut = 0 gives the sword to 1st person. num = 1; // Loop continues till n-1 person dies. while (cnt < (n - 1)) { // Checks next (kth) alive persons. while (num <= k) { cut++; // Checks and resolves overflow // of Index. cut = cut % n; if (arr[cut] == 1) { // Updates the number of persons // alive. num++; } } // Refreshes value to 1 for next use. num = 1; // Kills the person at position of 'cut' arr[cut] = 0; // Updates the no. of killed persons. cnt++; cut++; // Checks and resolves overflow of Index. cut = cut % n; // Checks the next alive person the // sword is to be given. while (arr[cut] == 0) { cut++; // Checks and resolves overflow // of Index. cut = cut % n; } } // Output is the position of the last // man alive(Index + 1); return cut + 1;} // Driver codeint main(){ int n = 14, k = 2; cout << Josephus(n, k); return 0;} // THIS CODE IS PRESENTED BY SHISHANK RAWAT", "e": 14253, "s": 12778, "text": null }, { "code": "// Java code to implement the above approachimport java.io.*;class GFG { public static void main(String[] args) { int n = 14, k = 2; System.out.println(Josephus(n, k)); } public static int Josephus(int n, int k) { k--; int arr[] = new int[n]; for (int i = 0; i < n; i++) { arr[i] = 1; // Makes all the 'n' people alive by // assigning them value = 1 } int cnt = 0, cut = 0, num = 1; // Cut = 0 gives the sword to 1st person. while ( cnt < (n - 1)) // Loop continues till n-1 person dies. { while (num <= k) // Checks next (kth) alive persons. { cut++; cut = cut % n; // Checks and resolves overflow // of Index. if (arr[cut] == 1) { num++; // Updates the number of persons // alive. } } num = 1; // refreshes value to 1 for next use. arr[cut] = 0; // Kills the person at position of // 'cut' cnt++; // Updates the no. of killed persons. cut++; cut = cut % n; // Checks and resolves overflow // of Index. while (arr[cut] == 0) // Checks the next alive person the // sword is to be given. { cut++; cut = cut % n; // Checks and resolves overflow // of Index. } } return cut + 1; // Output is the position of the last // man alive(Index + 1); }} // This code is contributed by Shubham Singh", "e": 16054, "s": 14253, "text": null }, { "code": "def Josephus(n, k): k -= 1 arr = [0]*n for i in range(n): arr[i] = 1 # Makes all the 'n' people alive by # assigning them value = 1 cnt = 0 cut = 0 num = 1 # Cut = 0 gives the sword to 1st person. while (cnt < (n - 1)): # Loop continues till n-1 person dies. while (num <= k): # Checks next (kth) alive persons. cut += 1 cut = cut % n # Checks and resolves overflow # of Index. if (arr[cut] == 1): num+=1 # Updates the number of persons # alive. num = 1 # refreshes value to 1 for next use. arr[cut] = 0 # Kills the person at position of 'cut' cnt += 1 # Updates the no. of killed persons. cut += 1 cut = cut % n # Checks and resolves overflow of Index. while (arr[cut] == 0): # Checks the next alive person the # sword is to be given. cut += 1 cut = cut % n # Checks and resolves overflow # of Index. return cut + 1 # Output is the position of the last # man alive(Index + 1) # Driver Coden, k = 14, 2 #map (int, input().splut())print(Josephus(n, k)) # This code is contributed by ShubhamSingh", "e": 17350, "s": 16054, "text": null }, { "code": "// C# code to implement the above approachusing System;using System.Linq; public class GFG{ public static void Main () { int n = 14, k = 2; Console.Write(Josephus(n, k)); } public static int Josephus(int n, int k) { k--; int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = 1; // Makes all the 'n' people alive by // assigning them value = 1 } int cnt = 0, cut = 0, num = 1; // Cut = 0 gives the sword to 1st person. while ( cnt < (n - 1)) // Loop continues till n-1 person dies. { while (num <= k) // Checks next (kth) alive persons. { cut++; cut = cut % n; // Checks and resolves overflow // of Index. if (arr[cut] == 1) { num++; // Updates the number of persons // alive. } } num = 1; // refreshes value to 1 for next use. arr[cut] = 0; // Kills the person at position of 'cut' cnt++; // Updates the no. of killed persons. cut++; cut = cut % n; // Checks and resolves overflow of Index. while (arr[cut] == 0) // Checks the next alive person the // sword is to be given. { cut++; cut = cut % n; // Checks and resolves overflow // of Index. } } return cut + 1; // Output is the position of the last // man alive(Index + 1); }} // This code is contributed by Shubham Singh", "e": 18785, "s": 17350, "text": null }, { "code": "<script> // Javascript code to implement the above approach let n = 14, k = 2; document.write(Josephus(n, k)); function Josephus(n, k) { k--; let arr = new Array(n); for (let i = 0; i < n; i++) { // Makes all the 'n' people alive by // assigning them value = 1 arr[i] = 1; } // Cut = 0 gives the sword to 1st person. let cnt = 0, cut = 0, num = 1; // Loop continues till n-1 person dies. while (cnt < (n - 1)) { // Checks next (kth) alive persons. while (num <= k) { cut++; cut = cut % n; // Checks and resolves overflow // of Index. if (arr[cut] == 1) { // Updates the number of persons // alive. num++; } } // refreshes value to 1 for next use. num = 1; arr[cut] = 0; // Kills the person at position of 'cut' // Updates the no. of killed persons. cnt++; cut++; // Checks and resolves overflow of Index. cut = cut % n; // Checks the next alive person the // sword is to be given. while (arr[cut] == 0) { cut++; // Checks and resolves overflow // of Index. cut = cut % n; } } // Output is the position of the last // man alive(Index + 1); return cut + 1; } // This code is contributed by decode2207.</script>", "e": 20373, "s": 18785, "text": null }, { "code": null, "e": 20376, "s": 20373, "text": "13" }, { "code": null, "e": 20452, "s": 20376, "text": "Please visit set-2: Josephus problem | Set 2 (A Simple Solution when k = 2)" }, { "code": null, "e": 20634, "s": 20452, "text": "Source: http://en.wikipedia.org/wiki/Josephus_problemPlease write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. " }, { "code": null, "e": 20640, "s": 20634, "text": "jit_t" }, { "code": null, "e": 20645, "s": 20640, "text": "vt_m" }, { "code": null, "e": 20658, "s": 20645, "text": "Akanksha_Rai" }, { "code": null, "e": 20673, "s": 20658, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 20686, "s": 20673, "text": "hritikrommie" }, { "code": null, "e": 20693, "s": 20686, "text": "sk1122" }, { "code": null, "e": 20708, "s": 20693, "text": "rameshtravel07" }, { "code": null, "e": 20726, "s": 20708, "text": "shishankrawt93774" }, { "code": null, "e": 20739, "s": 20726, "text": "RiteshYadav7" }, { "code": null, "e": 20758, "s": 20739, "text": "surindertarika1234" }, { "code": null, "e": 20799, "s": 20758, "text": "qwcllh9fr90rljmmxnhnev0o49esfddve93ojc2o" }, { "code": null, "e": 20809, "s": 20799, "text": "subham348" }, { "code": null, "e": 20823, "s": 20809, "text": "divyesh072019" }, { "code": null, "e": 20837, "s": 20823, "text": "kandelgaurav7" }, { "code": null, "e": 20854, "s": 20837, "text": "surinderdawra388" }, { "code": null, "e": 20866, "s": 20854, "text": "umadevi9616" }, { "code": null, "e": 20877, "s": 20866, "text": "decode2207" }, { "code": null, "e": 20894, "s": 20877, "text": "harendrakumar123" }, { "code": null, "e": 20902, "s": 20894, "text": "Walmart" }, { "code": null, "e": 20912, "s": 20902, "text": "Bit Magic" }, { "code": null, "e": 20925, "s": 20912, "text": "Mathematical" }, { "code": null, "e": 20935, "s": 20925, "text": "Recursion" }, { "code": null, "e": 20943, "s": 20935, "text": "Walmart" }, { "code": null, "e": 20956, "s": 20943, "text": "Mathematical" }, { "code": null, "e": 20966, "s": 20956, "text": "Recursion" }, { "code": null, "e": 20976, "s": 20966, "text": "Bit Magic" }, { "code": null, "e": 21074, "s": 20976, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 21104, "s": 21074, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 21142, "s": 21104, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 21182, "s": 21142, "text": "Binary representation of a given number" }, { "code": null, "e": 21233, "s": 21182, "text": "Add two numbers without using arithmetic operators" }, { "code": null, "e": 21257, "s": 21233, "text": "Rotate bits of a number" }, { "code": null, "e": 21287, "s": 21257, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 21330, "s": 21287, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 21390, "s": 21330, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 21405, "s": 21390, "text": "C++ Data Types" } ]
SAP ABAP - Nested If Statement
It is always legal to nest IF....ELSE statements, which means you can use one IF or ELSEIF statement inside another IF or ELSEIF statement. The syntax for a nested IF....ELSE statement is as follows βˆ’ IF<condition_1>. <statement block>. IF<condition_2>. <statement block>. ELSE. <statement block>. ENDIF. ELSE <statement block>. ENDIF. Report YH_SEP_15. Data: Title_1(10) TYPE C, Title_2(15) TYPE C, Title_3(10) TYPE C. Title_1 = 'ABAP'. Title_2 = 'Programming'. Title_3 = 'Tutorial'. IF Title_1 = 'ABAP'. IF Title_2 = 'Programming'. IF Title_3 = 'Tutorial'. Write 'Yes, It’s Correct'. ELSE. Write 'Sorry, It’s Wrong'. ENDIF. ENDIF. ENDIF. The above code produces the following output βˆ’ Yes, It’s Correct.
[ { "code": null, "e": 3172, "s": 3032, "text": "It is always legal to nest IF....ELSE statements, which means you can use one IF or ELSEIF statement inside another IF or ELSEIF statement." }, { "code": null, "e": 3233, "s": 3172, "text": "The syntax for a nested IF....ELSE statement is as follows βˆ’" }, { "code": null, "e": 3381, "s": 3233, "text": "IF<condition_1>. \n<statement block>. \nIF<condition_2>. \n<statement block>. \nELSE. \n<statement block>. \nENDIF. \nELSE <statement block>. \nENDIF.\n" }, { "code": null, "e": 3738, "s": 3381, "text": "Report YH_SEP_15. \n \nData: Title_1(10) TYPE C,\n Title_2(15) TYPE C,\n Title_3(10) TYPE C. \n \nTitle_1 = 'ABAP'. \nTitle_2 = 'Programming'. \nTitle_3 = 'Tutorial'.\n \nIF Title_1 = 'ABAP'.\n \nIF Title_2 = 'Programming'. \n IF Title_3 = 'Tutorial'. \n Write 'Yes, It’s Correct'.\nELSE. \nWrite 'Sorry, It’s Wrong'. \n \nENDIF.\n \nENDIF. \nENDIF." }, { "code": null, "e": 3785, "s": 3738, "text": "The above code produces the following output βˆ’" } ]
JavaScript to generate random hex codes of color
24 May, 2018 What is hex code? A hex code is a six-digit, three-byte hexadecimal number used to represent colors in HTML, CSS, SVG. The bytes represent the red, green and blue components of the color. One byte represents a number in the range 00 to FF (in hexadecimal notation), or 0 to 255 in decimal notation. This represents the least (0) to the most (255) intensity of each of the color components. Functions to be used for generating hex codes:Math.random() generates any no. between 0 and 1 including decimal.Math.random() * 16 generates no. between 0 to 16 including decimal.Math.floor() removes the decimal part. <script> // storing all letter and digit combinations // for html color code var letters = "0123456789ABCDEF"; // html color code starts with # var color = '#'; // generating 6 times as HTML color code consist // of 6 letter or digits for (var i = 0; i < 6; i++) color += letters[(Math.floor(Math.random() * 16))]; document.write(color);</script> Output: #E3B0DF Note: Output will be different for everytime the code will get executed.Reference: https://en.wikipedia.org/wiki/Web_colors#Hex_triplet javascript-math JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Hide or show elements in HTML using display property Difference Between PUT and PATCH Request How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? How to calculate the number of days between two dates in javascript? File uploading in React.js Roadmap to Learn JavaScript For Beginners
[ { "code": null, "e": 53, "s": 25, "text": "\n24 May, 2018" }, { "code": null, "e": 71, "s": 53, "text": "What is hex code?" }, { "code": null, "e": 443, "s": 71, "text": "A hex code is a six-digit, three-byte hexadecimal number used to represent colors in HTML, CSS, SVG. The bytes represent the red, green and blue components of the color. One byte represents a number in the range 00 to FF (in hexadecimal notation), or 0 to 255 in decimal notation. This represents the least (0) to the most (255) intensity of each of the color components." }, { "code": null, "e": 661, "s": 443, "text": "Functions to be used for generating hex codes:Math.random() generates any no. between 0 and 1 including decimal.Math.random() * 16 generates no. between 0 to 16 including decimal.Math.floor() removes the decimal part." }, { "code": "<script> // storing all letter and digit combinations // for html color code var letters = \"0123456789ABCDEF\"; // html color code starts with # var color = '#'; // generating 6 times as HTML color code consist // of 6 letter or digits for (var i = 0; i < 6; i++) color += letters[(Math.floor(Math.random() * 16))]; document.write(color);</script>", "e": 1044, "s": 661, "text": null }, { "code": null, "e": 1052, "s": 1044, "text": "Output:" }, { "code": null, "e": 1062, "s": 1052, "text": "#E3B0DF \n" }, { "code": null, "e": 1198, "s": 1062, "text": "Note: Output will be different for everytime the code will get executed.Reference: https://en.wikipedia.org/wiki/Web_colors#Hex_triplet" }, { "code": null, "e": 1214, "s": 1198, "text": "javascript-math" }, { "code": null, "e": 1225, "s": 1214, "text": "JavaScript" }, { "code": null, "e": 1323, "s": 1225, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1384, "s": 1323, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1456, "s": 1384, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 1496, "s": 1456, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 1549, "s": 1496, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 1590, "s": 1549, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 1642, "s": 1590, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 1688, "s": 1642, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 1757, "s": 1688, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 1784, "s": 1757, "text": "File uploading in React.js" } ]
Python | Add leading K character
11 Mar, 2022 Sometimes, during the string manipulation, we are into a problem where we need to pad or add leading K to the string as per the requirements. This problem can occur in web development. Having shorthands to solve this problem turns to be handy in many situations. Let’s discuss certain ways in which this problem can be solved.Method #1 : Using rjust() rjust function offers a single line way to perform this particular task. Hence can easily be employed to any string whose padding we need to be done. We can specify the amount of padding required. Python3 # Python3 code to demonstrate# Add leading K character# using rjust() # initializing stringtest_string = 'GFG' # printing original stringprint("The original string : " + str(test_string)) # No. of zeros requiredN = 4 # initializing KK = 'M' # using rjust()# Add leading K characterres = test_string.rjust(N + len(test_string), K) # print resultprint("The string after adding leading K : " + str(res)) The original string : GFG The string after adding leading K : MMMMGFG Method #2 : Using format() String formatting using the format function can be used to perform this task easily, we just mention the number of elements total, element needed to pad, and direction of padding, in this case left. Python3 # Python3 code to demonstrate# Add leading K character# using format() # initializing stringtest_string = 'GFG' # printing original stringprint("The original string : " + str(test_string)) # No. of zeros requiredN = 4 # initializing KK = '0' # using format()# Add leading K character# N for number of elements and '>' for leadingtemp = '{:>' + K + '7}'res = temp.format(test_string) # print resultprint("The string after adding leading K : " + str(res)) The original string : GFG The string after adding leading K : 0000GFG sumitgumber28 Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Mar, 2022" }, { "code": null, "e": 578, "s": 28, "text": "Sometimes, during the string manipulation, we are into a problem where we need to pad or add leading K to the string as per the requirements. This problem can occur in web development. Having shorthands to solve this problem turns to be handy in many situations. Let’s discuss certain ways in which this problem can be solved.Method #1 : Using rjust() rjust function offers a single line way to perform this particular task. Hence can easily be employed to any string whose padding we need to be done. We can specify the amount of padding required. " }, { "code": null, "e": 586, "s": 578, "text": "Python3" }, { "code": "# Python3 code to demonstrate# Add leading K character# using rjust() # initializing stringtest_string = 'GFG' # printing original stringprint(\"The original string : \" + str(test_string)) # No. of zeros requiredN = 4 # initializing KK = 'M' # using rjust()# Add leading K characterres = test_string.rjust(N + len(test_string), K) # print resultprint(\"The string after adding leading K : \" + str(res))", "e": 987, "s": 586, "text": null }, { "code": null, "e": 1057, "s": 987, "text": "The original string : GFG\nThe string after adding leading K : MMMMGFG" }, { "code": null, "e": 1287, "s": 1059, "text": " Method #2 : Using format() String formatting using the format function can be used to perform this task easily, we just mention the number of elements total, element needed to pad, and direction of padding, in this case left. " }, { "code": null, "e": 1295, "s": 1287, "text": "Python3" }, { "code": "# Python3 code to demonstrate# Add leading K character# using format() # initializing stringtest_string = 'GFG' # printing original stringprint(\"The original string : \" + str(test_string)) # No. of zeros requiredN = 4 # initializing KK = '0' # using format()# Add leading K character# N for number of elements and '>' for leadingtemp = '{:>' + K + '7}'res = temp.format(test_string) # print resultprint(\"The string after adding leading K : \" + str(res))", "e": 1749, "s": 1295, "text": null }, { "code": null, "e": 1819, "s": 1749, "text": "The original string : GFG\nThe string after adding leading K : 0000GFG" }, { "code": null, "e": 1835, "s": 1821, "text": "sumitgumber28" }, { "code": null, "e": 1858, "s": 1835, "text": "Python string-programs" }, { "code": null, "e": 1865, "s": 1858, "text": "Python" }, { "code": null, "e": 1881, "s": 1865, "text": "Python Programs" }, { "code": null, "e": 1979, "s": 1881, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2011, "s": 1979, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2038, "s": 2011, "text": "Python Classes and Objects" }, { "code": null, "e": 2059, "s": 2038, "text": "Python OOPs Concepts" }, { "code": null, "e": 2082, "s": 2059, "text": "Introduction To PYTHON" }, { "code": null, "e": 2113, "s": 2082, "text": "Python | os.path.join() method" }, { "code": null, "e": 2135, "s": 2113, "text": "Defaultdict in Python" }, { "code": null, "e": 2174, "s": 2135, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2212, "s": 2174, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2249, "s": 2212, "text": "Python Program for Fibonacci numbers" } ]
HTML <select> disabled Attribute
04 Jan, 2019 The disabled attribute for <select> element in HTML is used to specify that the select element is disabled. A disabled drop-down list is un-clickable and unusable. It is a boolean attribute. Syntax: <select disabled>option values...</select> Example: <!DOCTYPE html> <html> <head> <title>HTML select disabled Attribute</title> </head> <body style = "text-align:center"> <h1 style = "color: green;">GeeksforGeeks</h1> <h2>HTML select disabled Attribute</h2> <p>This select field is disabled.</p> <!--A disabled select--> <select disabled> <option value="binary">Binary Search</option> <option value="linear">Linear Search</option> <option value="interpolation">Interpolation Search</option> </select> </body> </html> Output: Supported Browsers: The browser supported by <select> disabled attribute are listed below: Apple Safari Google Chrome Firefox Opera Internet Explorer HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 53, "s": 25, "text": "\n04 Jan, 2019" }, { "code": null, "e": 244, "s": 53, "text": "The disabled attribute for <select> element in HTML is used to specify that the select element is disabled. A disabled drop-down list is un-clickable and unusable. It is a boolean attribute." }, { "code": null, "e": 252, "s": 244, "text": "Syntax:" }, { "code": null, "e": 296, "s": 252, "text": "<select disabled>option values...</select>\n" }, { "code": null, "e": 305, "s": 296, "text": "Example:" }, { "code": "<!DOCTYPE html> <html> <head> <title>HTML select disabled Attribute</title> </head> <body style = \"text-align:center\"> <h1 style = \"color: green;\">GeeksforGeeks</h1> <h2>HTML select disabled Attribute</h2> <p>This select field is disabled.</p> <!--A disabled select--> <select disabled> <option value=\"binary\">Binary Search</option> <option value=\"linear\">Linear Search</option> <option value=\"interpolation\">Interpolation Search</option> </select> </body> </html> ", "e": 882, "s": 305, "text": null }, { "code": null, "e": 890, "s": 882, "text": "Output:" }, { "code": null, "e": 981, "s": 890, "text": "Supported Browsers: The browser supported by <select> disabled attribute are listed below:" }, { "code": null, "e": 994, "s": 981, "text": "Apple Safari" }, { "code": null, "e": 1008, "s": 994, "text": "Google Chrome" }, { "code": null, "e": 1016, "s": 1008, "text": "Firefox" }, { "code": null, "e": 1022, "s": 1016, "text": "Opera" }, { "code": null, "e": 1040, "s": 1022, "text": "Internet Explorer" }, { "code": null, "e": 1056, "s": 1040, "text": "HTML-Attributes" }, { "code": null, "e": 1061, "s": 1056, "text": "HTML" }, { "code": null, "e": 1078, "s": 1061, "text": "Web Technologies" }, { "code": null, "e": 1083, "s": 1078, "text": "HTML" }, { "code": null, "e": 1181, "s": 1083, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1229, "s": 1181, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 1291, "s": 1229, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1341, "s": 1291, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 1365, "s": 1341, "text": "REST API (Introduction)" }, { "code": null, "e": 1418, "s": 1365, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 1480, "s": 1418, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1513, "s": 1480, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1574, "s": 1513, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1624, "s": 1574, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Sum of the series 1 + (1+2) + (1+2+3) + (1+2+3+4) + ...... + (1+2+3+4+...+n)
09 Sep, 2021 Given the value of n, we need to find the sum of the series where i-th term is sum of first i natural numbers.Examples : Input : n = 5 Output : 35 Explanation : (1) + (1+2) + (1+2+3) + (1+2+3+4) + (1+2+3+4+5) = 35 Input : n = 10 Output : 220 Explanation : (1) + (1+2) + (1+2+3) + .... +(1+2+3+4+.....+10) = 220 Naive Approach : Below is implementation of above series : C++ Java Python C# PHP Javascript // CPP program to find sum of given series#include <bits/stdc++.h>using namespace std; // Function to find sum of given seriesint sumOfSeries(int n){ int sum = 0; for (int i = 1 ; i <= n ; i++) for (int j = 1 ; j <= i ; j++) sum += j; return sum;} // Driver Functionint main(){ int n = 10; cout << sumOfSeries(n); return 0;} // JAVA Code For Sum of the seriesimport java.util.*; class GFG { // Function to find sum of given series static int sumOfSeries(int n) { int sum = 0; for (int i = 1 ; i <= n ; i++) for (int j = 1 ; j <= i ; j++) sum += j; return sum; } /* Driver program to test above function */ public static void main(String[] args) { int n = 10; System.out.println(sumOfSeries(n)); }} // This code is contributed by Arnav Kr. Mandal. # Python3 program to find sum of given series # Function to find sum of seriesdef sumOfSeries(n): return sum([i*(i+1)/2 for i in range(1, n + 1)]) # Driver Codeif __name__ == "__main__": n = 10 print(sumOfSeries(n)) // C# Code For Sum of the seriesusing System; class GFG { // Function to find sum of given series static int sumOfSeries(int n) { int sum = 0; for (int i = 1; i <= n; i++) for (int j = 1; j <= i; j++) sum += j; return sum; } /* Driver program to test above function */ public static void Main() { int n = 10; Console.Write(sumOfSeries(n)); }} // This code is contributed by vt_m. <?php// PHP program to find// sum of given series // Function to find// sum of given seriesfunction sumOfSeries($n){ $sum = 0; for ($i = 1 ; $i <= $n ; $i++) for ($j = 1 ; $j <= $i ; $j++) $sum += $j; return $sum;} // Driver Code$n = 10;echo(sumOfSeries($n)); // This code is contributed by Ajit.?> <script> // JavaScript Program for Sum of the series // Function to find sum of given series function sumOfSeries(n) { let sum = 0; for (let i = 1 ; i <= n ; i++) for (let j = 1 ; j <= i ; j++) sum += j; return sum; } // Driver code let n = 10; document.write(sumOfSeries(n)); </script> Output : 220 Efficient Approach :Let term of the series 1 + (1 + 2) + (1 + 2 + 3) + (1 + 2 + 3 + 4)...(1 + 2 + 3 +..n) be denoted as an an = Ξ£n1 = = Sum of n-terms of series Ξ£n1 an = Ξ£n1 = Ξ£ + Ξ£ = * + * = Below is implementation of above approach : C++ Java Python C# PHP Javascript // CPP program to find sum of given series#include <bits/stdc++.h>using namespace std; // Function to find sum of given seriesint sumOfSeries(int n){ return (n * (n + 1) * (2 * n + 4)) / 12;} // Driver Functionint main(){ int n = 10; cout << sumOfSeries(n);} // JAVA Code For Sum of the seriesimport java.util.*; class GFG { // Function to find sum of given series static int sumOfSeries(int n) { return (n * (n + 1) * (2 * n + 4)) / 12; } /* Driver program to test above function */ public static void main(String[] args) { int n = 10; System.out.println(sumOfSeries(n)); }} // This code is contributed by Arnav Kr. Mandal. # Python program to find sum of given series # Function to find sum of given seriesdef sumOfSeries(n): return (n * (n + 1) * (2 * n + 4)) / 12; # Driver functionif __name__ == '__main__': n = 10 print(sumOfSeries(n)) // C# Code For Sum of the seriesusing System; class GFG { // Function to find sum of given series static int sumOfSeries(int n) { return (n * (n + 1) * (2 * n + 4)) / 12; } /* Driver program to test above function */ public static void Main() { int n = 10; Console.Write(sumOfSeries(n)); }} // This code is contributed by vt_m. <?php// PHP program to find// sum of given series // Function to find// sum of given seriesfunction sumOfSeries($n){ return ($n * ($n + 1) * (2 * $n + 4)) / 12;} // Driver Code$n = 10;echo(sumOfSeries($n)); // This code is contributed by Ajit.?> <script> // JavaScript program For Sum of the series // Function to find sum of given series function sumOfSeries(n) { return (n * (n + 1) * (2 * n + 4)) / 12; } // Driver code let n = 10; document.write(sumOfSeries(n)); </script> Output : 220 Time Complexity: O(1)Auxiliary Space: O(1) jit_t splevel62 susmitakundugoaldanga gargr0109 series Mathematical Technical Scripter Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Sep, 2021" }, { "code": null, "e": 177, "s": 54, "text": "Given the value of n, we need to find the sum of the series where i-th term is sum of first i natural numbers.Examples : " }, { "code": null, "e": 374, "s": 177, "text": "Input : n = 5 \nOutput : 35\nExplanation :\n(1) + (1+2) + (1+2+3) + (1+2+3+4) + (1+2+3+4+5) = 35\n\nInput : n = 10\nOutput : 220\nExplanation :\n(1) + (1+2) + (1+2+3) + .... +(1+2+3+4+.....+10) = 220" }, { "code": null, "e": 437, "s": 376, "text": "Naive Approach : Below is implementation of above series : " }, { "code": null, "e": 441, "s": 437, "text": "C++" }, { "code": null, "e": 446, "s": 441, "text": "Java" }, { "code": null, "e": 453, "s": 446, "text": "Python" }, { "code": null, "e": 456, "s": 453, "text": "C#" }, { "code": null, "e": 460, "s": 456, "text": "PHP" }, { "code": null, "e": 471, "s": 460, "text": "Javascript" }, { "code": "// CPP program to find sum of given series#include <bits/stdc++.h>using namespace std; // Function to find sum of given seriesint sumOfSeries(int n){ int sum = 0; for (int i = 1 ; i <= n ; i++) for (int j = 1 ; j <= i ; j++) sum += j; return sum;} // Driver Functionint main(){ int n = 10; cout << sumOfSeries(n); return 0;}", "e": 832, "s": 471, "text": null }, { "code": "// JAVA Code For Sum of the seriesimport java.util.*; class GFG { // Function to find sum of given series static int sumOfSeries(int n) { int sum = 0; for (int i = 1 ; i <= n ; i++) for (int j = 1 ; j <= i ; j++) sum += j; return sum; } /* Driver program to test above function */ public static void main(String[] args) { int n = 10; System.out.println(sumOfSeries(n)); }} // This code is contributed by Arnav Kr. Mandal.", "e": 1360, "s": 832, "text": null }, { "code": "# Python3 program to find sum of given series # Function to find sum of seriesdef sumOfSeries(n): return sum([i*(i+1)/2 for i in range(1, n + 1)]) # Driver Codeif __name__ == \"__main__\": n = 10 print(sumOfSeries(n))", "e": 1585, "s": 1360, "text": null }, { "code": "// C# Code For Sum of the seriesusing System; class GFG { // Function to find sum of given series static int sumOfSeries(int n) { int sum = 0; for (int i = 1; i <= n; i++) for (int j = 1; j <= i; j++) sum += j; return sum; } /* Driver program to test above function */ public static void Main() { int n = 10; Console.Write(sumOfSeries(n)); }} // This code is contributed by vt_m.", "e": 2061, "s": 1585, "text": null }, { "code": "<?php// PHP program to find// sum of given series // Function to find// sum of given seriesfunction sumOfSeries($n){ $sum = 0; for ($i = 1 ; $i <= $n ; $i++) for ($j = 1 ; $j <= $i ; $j++) $sum += $j; return $sum;} // Driver Code$n = 10;echo(sumOfSeries($n)); // This code is contributed by Ajit.?>", "e": 2387, "s": 2061, "text": null }, { "code": "<script> // JavaScript Program for Sum of the series // Function to find sum of given series function sumOfSeries(n) { let sum = 0; for (let i = 1 ; i <= n ; i++) for (let j = 1 ; j <= i ; j++) sum += j; return sum; } // Driver code let n = 10; document.write(sumOfSeries(n)); </script>", "e": 2770, "s": 2387, "text": null }, { "code": null, "e": 2780, "s": 2770, "text": "Output : " }, { "code": null, "e": 2784, "s": 2780, "text": "220" }, { "code": null, "e": 2909, "s": 2784, "text": "Efficient Approach :Let term of the series 1 + (1 + 2) + (1 + 2 + 3) + (1 + 2 + 3 + 4)...(1 + 2 + 3 +..n) be denoted as an " }, { "code": null, "e": 2996, "s": 2909, "text": "an = Ξ£n1 = = \nSum of n-terms of series \nΞ£n1 an = Ξ£n1 \n= Ξ£ + Ξ£ \n= * + * \n= " }, { "code": null, "e": 3042, "s": 2996, "text": "Below is implementation of above approach : " }, { "code": null, "e": 3046, "s": 3042, "text": "C++" }, { "code": null, "e": 3051, "s": 3046, "text": "Java" }, { "code": null, "e": 3058, "s": 3051, "text": "Python" }, { "code": null, "e": 3061, "s": 3058, "text": "C#" }, { "code": null, "e": 3065, "s": 3061, "text": "PHP" }, { "code": null, "e": 3076, "s": 3065, "text": "Javascript" }, { "code": "// CPP program to find sum of given series#include <bits/stdc++.h>using namespace std; // Function to find sum of given seriesint sumOfSeries(int n){ return (n * (n + 1) * (2 * n + 4)) / 12;} // Driver Functionint main(){ int n = 10; cout << sumOfSeries(n);}", "e": 3344, "s": 3076, "text": null }, { "code": "// JAVA Code For Sum of the seriesimport java.util.*; class GFG { // Function to find sum of given series static int sumOfSeries(int n) { return (n * (n + 1) * (2 * n + 4)) / 12; } /* Driver program to test above function */ public static void main(String[] args) { int n = 10; System.out.println(sumOfSeries(n)); }} // This code is contributed by Arnav Kr. Mandal.", "e": 3791, "s": 3344, "text": null }, { "code": "# Python program to find sum of given series # Function to find sum of given seriesdef sumOfSeries(n): return (n * (n + 1) * (2 * n + 4)) / 12; # Driver functionif __name__ == '__main__': n = 10 print(sumOfSeries(n))", "e": 4021, "s": 3791, "text": null }, { "code": "// C# Code For Sum of the seriesusing System; class GFG { // Function to find sum of given series static int sumOfSeries(int n) { return (n * (n + 1) * (2 * n + 4)) / 12; } /* Driver program to test above function */ public static void Main() { int n = 10; Console.Write(sumOfSeries(n)); }} // This code is contributed by vt_m.", "e": 4405, "s": 4021, "text": null }, { "code": "<?php// PHP program to find// sum of given series // Function to find// sum of given seriesfunction sumOfSeries($n){ return ($n * ($n + 1) * (2 * $n + 4)) / 12;} // Driver Code$n = 10;echo(sumOfSeries($n)); // This code is contributed by Ajit.?>", "e": 4664, "s": 4405, "text": null }, { "code": "<script> // JavaScript program For Sum of the series // Function to find sum of given series function sumOfSeries(n) { return (n * (n + 1) * (2 * n + 4)) / 12; } // Driver code let n = 10; document.write(sumOfSeries(n)); </script>", "e": 4973, "s": 4664, "text": null }, { "code": null, "e": 4983, "s": 4973, "text": "Output : " }, { "code": null, "e": 4987, "s": 4983, "text": "220" }, { "code": null, "e": 5031, "s": 4987, "text": "Time Complexity: O(1)Auxiliary Space: O(1) " }, { "code": null, "e": 5037, "s": 5031, "text": "jit_t" }, { "code": null, "e": 5047, "s": 5037, "text": "splevel62" }, { "code": null, "e": 5069, "s": 5047, "text": "susmitakundugoaldanga" }, { "code": null, "e": 5079, "s": 5069, "text": "gargr0109" }, { "code": null, "e": 5086, "s": 5079, "text": "series" }, { "code": null, "e": 5099, "s": 5086, "text": "Mathematical" }, { "code": null, "e": 5118, "s": 5099, "text": "Technical Scripter" }, { "code": null, "e": 5131, "s": 5118, "text": "Mathematical" }, { "code": null, "e": 5138, "s": 5131, "text": "series" } ]
How to use animation on favicon image ?
31 Jan, 2020 A favicon is a special icon that appears at the top left corner near the web address bar. The file type can be of any jpg, png, gif or icon(.ico) image. The default favicon name is favicon.ico. The favicons are also commonly known as a shortcut icon, bookmark icon or website icon. They provide convenience to users for locating your web page. The favicons are included for a branded professional look with a specific logo that maintains a uniformity through all the pages of the website. The icons help the website in online branding. An animated favicon is created from an animated image. It is set through link tag. It is basically a set of images running one after the other within a specific time frame. Syntax: To add gif as favicon:<link rel="icon" href="geeksforgeeks.org/favicon.gif" type="image/gif" /> <link rel="icon" href="geeksforgeeks.org/favicon.gif" type="image/gif" /> To add normal image as favicon:<link rel="icon" href="favicon.ico" type="image/x-icon"/> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"/> <link rel="icon" href="favicon.ico" type="image/x-icon"/> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"/> Note: Animated images of type GIF will work in Firefox browser. The .ico is the standard format which works well on all browsers but many websites prefer images of type PNG. Approach: In the following example codes, the approach taken is display of progressing animation with the help of HTML canvas, javascript and mathematical geometry. An Animate Favicon button is added in the HTML page, which helps in starting the animation effect on click event. Once the drawing is done in the canvas, it is converted to a PNG image before being assigned as a favicon. Example 1: The following example code will show the implementation of circular animation on favicon image.<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <title>Circular animation on favicon</title> <link rel="shortcut icon" href="gfgFavicon.png" width=32px> <script language="javascript"> onload = function() { canvas = document.querySelector('#canvasId'), context = canvas.getContext('2d'); if (!!context) { // The start position for drawing circle C3qpi = 1.5 * Math.PI, tc = pct = 0, btn = document.querySelector('#animateBtn'), faviconLnk = document.querySelector('link[rel*="icon"]'); context.lineWidth = 3; context.strokeStyle = 'green'; // On page refresh, enable the button if (btn.disabled) btn.removeAttribute('disabled'); btn.addEventListener('click', function() { tc = setInterval(drawcircularLoader, 60); this.textContent = 'Animating'; this.style.backgroundColor = '#99999'; this.setAttribute('disabled', ''); }); } }; function drawcircularLoader() { with(context) { clearRect(0, 0, 32, 32); beginPath(); arc(8, 8, 6, C3qpi, (pct * 2 * Math.PI / 100 + C3qpi)); stroke(); } // Update favicon to PNG image faviconLnk.href = canvas.toDataURL('image/png'); if (pct === 100) { clearInterval(tc); btn.textContent = 'Animated'; btn.style.backgroundColor = 'green'; return; } pct++; } </script> <style> body { width: 450px; height: 300px; margin: 10px; text-align: center; } h1 { color: green; } #animateBtn { background-color: #1c2e46; border-radius: 2px; border: none; color: white; font-family: inherit; font-size: inherit; padding: 0px 5px; letter-spacing: 1px; cursor: pointer; } #animateBtn:focus { outline: none; } #animateBtn[disabled] { cursor: default; } .height { height: 10px; } </style></head> <body> <h1>GeeksforGeeks</h1> <b>How to use circular animation on favicon image</b> <div class="height"> </div> <br> <!-- Canvas nad button for animation --> <button id="animateBtn">Animate Favicon </button> <br> <br> <canvas id="canvasId" width=32 height=32></canvas></body> </html> <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <title>Circular animation on favicon</title> <link rel="shortcut icon" href="gfgFavicon.png" width=32px> <script language="javascript"> onload = function() { canvas = document.querySelector('#canvasId'), context = canvas.getContext('2d'); if (!!context) { // The start position for drawing circle C3qpi = 1.5 * Math.PI, tc = pct = 0, btn = document.querySelector('#animateBtn'), faviconLnk = document.querySelector('link[rel*="icon"]'); context.lineWidth = 3; context.strokeStyle = 'green'; // On page refresh, enable the button if (btn.disabled) btn.removeAttribute('disabled'); btn.addEventListener('click', function() { tc = setInterval(drawcircularLoader, 60); this.textContent = 'Animating'; this.style.backgroundColor = '#99999'; this.setAttribute('disabled', ''); }); } }; function drawcircularLoader() { with(context) { clearRect(0, 0, 32, 32); beginPath(); arc(8, 8, 6, C3qpi, (pct * 2 * Math.PI / 100 + C3qpi)); stroke(); } // Update favicon to PNG image faviconLnk.href = canvas.toDataURL('image/png'); if (pct === 100) { clearInterval(tc); btn.textContent = 'Animated'; btn.style.backgroundColor = 'green'; return; } pct++; } </script> <style> body { width: 450px; height: 300px; margin: 10px; text-align: center; } h1 { color: green; } #animateBtn { background-color: #1c2e46; border-radius: 2px; border: none; color: white; font-family: inherit; font-size: inherit; padding: 0px 5px; letter-spacing: 1px; cursor: pointer; } #animateBtn:focus { outline: none; } #animateBtn[disabled] { cursor: default; } .height { height: 10px; } </style></head> <body> <h1>GeeksforGeeks</h1> <b>How to use circular animation on favicon image</b> <div class="height"> </div> <br> <!-- Canvas nad button for animation --> <button id="animateBtn">Animate Favicon </button> <br> <br> <canvas id="canvasId" width=32 height=32></canvas></body> </html> Output: Example 2: In this example, the implementation of drawing a square which transforms the favicon into a animated image.<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <link rel="shortcut icon" href="gfgFavicon.png" width=32px> <script language="javascript"> onload = () => { var canvas = document.getElementById("canvas"); context = canvas.getContext('2d'); if (!!context) { var animateBtn = document.getElementById("animateBtn"); faviconVar = document.querySelector('link[rel*="icon"]'); // The styles used for the square which will // be animated in place of favicon let linerGradient = context.createLinearGradient(0, 0, 32, 32); linerGradient.addColorStop(0, '#8be8a7'); linerGradient.addColorStop(1, '#297d4c'); context.strokeStyle = linerGradient; context.lineWidth = 10; // On page refresh , the button is enabled if (animateBtn.disabled) animateBtn.removeAttribute('disabled'); animateBtn.addEventListener('click', function() { // Variable used for drawing incrementation n = 0, // Speed interval for animation loadingInterval = setInterval(drawSquareLoader, 80); this.textContent = 'Animating...'; this.style.backgroundColor = '#297d4c'; //Once the drawing is done, the button is again disabled this.setAttribute('disabled', ''); }); } }; // Function for drawing square in canvas in a incrementing way function drawSquareLoader() { with(context) { clearRect(0, 0, 32, 32); beginPath(); // One fourth time taken to draw if (n <= 25) { moveTo(0, 0); lineTo((32 / 25) * n, 0); } // Between second quarter of drawing else if (n > 25 && n <= 50) { moveTo(0, 0); lineTo(32, 0); moveTo(32, 0); lineTo(32, (32 / 25) * (n - 25)); } // Between third quarter of drawing else if (n > 50 && n <= 75) { moveTo(0, 0); lineTo(32, 0); moveTo(32, 0); lineTo(32, 32); moveTo(32, 32); lineTo(-((32 / 25) * (n - 75)), 32); } // Between last quarter else if (n > 75 && n <= 100) { moveTo(0, 0); lineTo(32, 0); moveTo(32, 0); lineTo(32, 32); moveTo(32, 32); lineTo(0, 32); moveTo(0, 32); lineTo(0, -((32 / 25) * (n - 100))); } //Function to draw the path stroke(); } // Assigning the drawing to favicon after // converting into PNG image faviconVar.href = canvas.toDataURL('image/png'); // After the drawing is finished if (n === 100) { clearInterval(loadingInterval); animateBtn.textContent = 'Favicon Loaded'; animateBtn.style.backgroundColor = '#bbbbbb'; return; } // Increment the variable used to keep // track of drawing intervals n++; } </script> <title>Animation on favicon image</title> <style> body { width: 450px; height: 300px; margin: 10px; text-align: center; } h1 { color: green; } html { background: #f4f6fa; } #animateBtn { background: #1c2e46; color: white; font: inherit; border: none; padding: 0px 5px; letter-spacing: 1px; cursor: pointer; border-radius: 2px; } canvas { margin: auto; display: block; } .height { height: 10px; } </style></head> <body> <h1>GeeksforGeeks</h1> <b>How to use animation on favicon image</b> <div class="height"> </div> <br> <button id="animateBtn">Animate Favicon</button> <br> <br> <canvas id="canvas" width=32 height=32></canvas> </body> </html> <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <link rel="shortcut icon" href="gfgFavicon.png" width=32px> <script language="javascript"> onload = () => { var canvas = document.getElementById("canvas"); context = canvas.getContext('2d'); if (!!context) { var animateBtn = document.getElementById("animateBtn"); faviconVar = document.querySelector('link[rel*="icon"]'); // The styles used for the square which will // be animated in place of favicon let linerGradient = context.createLinearGradient(0, 0, 32, 32); linerGradient.addColorStop(0, '#8be8a7'); linerGradient.addColorStop(1, '#297d4c'); context.strokeStyle = linerGradient; context.lineWidth = 10; // On page refresh , the button is enabled if (animateBtn.disabled) animateBtn.removeAttribute('disabled'); animateBtn.addEventListener('click', function() { // Variable used for drawing incrementation n = 0, // Speed interval for animation loadingInterval = setInterval(drawSquareLoader, 80); this.textContent = 'Animating...'; this.style.backgroundColor = '#297d4c'; //Once the drawing is done, the button is again disabled this.setAttribute('disabled', ''); }); } }; // Function for drawing square in canvas in a incrementing way function drawSquareLoader() { with(context) { clearRect(0, 0, 32, 32); beginPath(); // One fourth time taken to draw if (n <= 25) { moveTo(0, 0); lineTo((32 / 25) * n, 0); } // Between second quarter of drawing else if (n > 25 && n <= 50) { moveTo(0, 0); lineTo(32, 0); moveTo(32, 0); lineTo(32, (32 / 25) * (n - 25)); } // Between third quarter of drawing else if (n > 50 && n <= 75) { moveTo(0, 0); lineTo(32, 0); moveTo(32, 0); lineTo(32, 32); moveTo(32, 32); lineTo(-((32 / 25) * (n - 75)), 32); } // Between last quarter else if (n > 75 && n <= 100) { moveTo(0, 0); lineTo(32, 0); moveTo(32, 0); lineTo(32, 32); moveTo(32, 32); lineTo(0, 32); moveTo(0, 32); lineTo(0, -((32 / 25) * (n - 100))); } //Function to draw the path stroke(); } // Assigning the drawing to favicon after // converting into PNG image faviconVar.href = canvas.toDataURL('image/png'); // After the drawing is finished if (n === 100) { clearInterval(loadingInterval); animateBtn.textContent = 'Favicon Loaded'; animateBtn.style.backgroundColor = '#bbbbbb'; return; } // Increment the variable used to keep // track of drawing intervals n++; } </script> <title>Animation on favicon image</title> <style> body { width: 450px; height: 300px; margin: 10px; text-align: center; } h1 { color: green; } html { background: #f4f6fa; } #animateBtn { background: #1c2e46; color: white; font: inherit; border: none; padding: 0px 5px; letter-spacing: 1px; cursor: pointer; border-radius: 2px; } canvas { margin: auto; display: block; } .height { height: 10px; } </style></head> <body> <h1>GeeksforGeeks</h1> <b>How to use animation on favicon image</b> <div class="height"> </div> <br> <button id="animateBtn">Animate Favicon</button> <br> <br> <canvas id="canvas" width=32 height=32></canvas> </body> </html> Output: CSS-Misc HTML-Misc JavaScript-Misc Picked HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) CSS to put icon inside an input element in a form Design a Tribute Page using HTML & CSS Types of CSS (Cascading Style Sheet) How to Insert Form Data into Database using PHP ? Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array How to append HTML code to a div using JavaScript ? Difference Between PUT and PATCH Request
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Jan, 2020" }, { "code": null, "e": 737, "s": 28, "text": "A favicon is a special icon that appears at the top left corner near the web address bar. The file type can be of any jpg, png, gif or icon(.ico) image. The default favicon name is favicon.ico. The favicons are also commonly known as a shortcut icon, bookmark icon or website icon. They provide convenience to users for locating your web page. The favicons are included for a branded professional look with a specific logo that maintains a uniformity through all the pages of the website. The icons help the website in online branding. An animated favicon is created from an animated image. It is set through link tag. It is basically a set of images running one after the other within a specific time frame." }, { "code": null, "e": 745, "s": 737, "text": "Syntax:" }, { "code": null, "e": 841, "s": 745, "text": "To add gif as favicon:<link rel=\"icon\" href=\"geeksforgeeks.org/favicon.gif\" type=\"image/gif\" />" }, { "code": null, "e": 915, "s": 841, "text": "<link rel=\"icon\" href=\"geeksforgeeks.org/favicon.gif\" type=\"image/gif\" />" }, { "code": null, "e": 1071, "s": 915, "text": "To add normal image as favicon:<link rel=\"icon\" href=\"favicon.ico\" type=\"image/x-icon\"/>\n<link rel=\"shortcut icon\" href=\"favicon.ico\" type=\"image/x-icon\"/>" }, { "code": null, "e": 1196, "s": 1071, "text": "<link rel=\"icon\" href=\"favicon.ico\" type=\"image/x-icon\"/>\n<link rel=\"shortcut icon\" href=\"favicon.ico\" type=\"image/x-icon\"/>" }, { "code": null, "e": 1370, "s": 1196, "text": "Note: Animated images of type GIF will work in Firefox browser. The .ico is the standard format which works well on all browsers but many websites prefer images of type PNG." }, { "code": null, "e": 1756, "s": 1370, "text": "Approach: In the following example codes, the approach taken is display of progressing animation with the help of HTML canvas, javascript and mathematical geometry. An Animate Favicon button is added in the HTML page, which helps in starting the animation effect on click event. Once the drawing is done in the canvas, it is converted to a PNG image before being assigned as a favicon." }, { "code": null, "e": 4679, "s": 1756, "text": "Example 1: The following example code will show the implementation of circular animation on favicon image.<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <title>Circular animation on favicon</title> <link rel=\"shortcut icon\" href=\"gfgFavicon.png\" width=32px> <script language=\"javascript\"> onload = function() { canvas = document.querySelector('#canvasId'), context = canvas.getContext('2d'); if (!!context) { // The start position for drawing circle C3qpi = 1.5 * Math.PI, tc = pct = 0, btn = document.querySelector('#animateBtn'), faviconLnk = document.querySelector('link[rel*=\"icon\"]'); context.lineWidth = 3; context.strokeStyle = 'green'; // On page refresh, enable the button if (btn.disabled) btn.removeAttribute('disabled'); btn.addEventListener('click', function() { tc = setInterval(drawcircularLoader, 60); this.textContent = 'Animating'; this.style.backgroundColor = '#99999'; this.setAttribute('disabled', ''); }); } }; function drawcircularLoader() { with(context) { clearRect(0, 0, 32, 32); beginPath(); arc(8, 8, 6, C3qpi, (pct * 2 * Math.PI / 100 + C3qpi)); stroke(); } // Update favicon to PNG image faviconLnk.href = canvas.toDataURL('image/png'); if (pct === 100) { clearInterval(tc); btn.textContent = 'Animated'; btn.style.backgroundColor = 'green'; return; } pct++; } </script> <style> body { width: 450px; height: 300px; margin: 10px; text-align: center; } h1 { color: green; } #animateBtn { background-color: #1c2e46; border-radius: 2px; border: none; color: white; font-family: inherit; font-size: inherit; padding: 0px 5px; letter-spacing: 1px; cursor: pointer; } #animateBtn:focus { outline: none; } #animateBtn[disabled] { cursor: default; } .height { height: 10px; } </style></head> <body> <h1>GeeksforGeeks</h1> <b>How to use circular animation on favicon image</b> <div class=\"height\"> </div> <br> <!-- Canvas nad button for animation --> <button id=\"animateBtn\">Animate Favicon </button> <br> <br> <canvas id=\"canvasId\" width=32 height=32></canvas></body> </html>" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <title>Circular animation on favicon</title> <link rel=\"shortcut icon\" href=\"gfgFavicon.png\" width=32px> <script language=\"javascript\"> onload = function() { canvas = document.querySelector('#canvasId'), context = canvas.getContext('2d'); if (!!context) { // The start position for drawing circle C3qpi = 1.5 * Math.PI, tc = pct = 0, btn = document.querySelector('#animateBtn'), faviconLnk = document.querySelector('link[rel*=\"icon\"]'); context.lineWidth = 3; context.strokeStyle = 'green'; // On page refresh, enable the button if (btn.disabled) btn.removeAttribute('disabled'); btn.addEventListener('click', function() { tc = setInterval(drawcircularLoader, 60); this.textContent = 'Animating'; this.style.backgroundColor = '#99999'; this.setAttribute('disabled', ''); }); } }; function drawcircularLoader() { with(context) { clearRect(0, 0, 32, 32); beginPath(); arc(8, 8, 6, C3qpi, (pct * 2 * Math.PI / 100 + C3qpi)); stroke(); } // Update favicon to PNG image faviconLnk.href = canvas.toDataURL('image/png'); if (pct === 100) { clearInterval(tc); btn.textContent = 'Animated'; btn.style.backgroundColor = 'green'; return; } pct++; } </script> <style> body { width: 450px; height: 300px; margin: 10px; text-align: center; } h1 { color: green; } #animateBtn { background-color: #1c2e46; border-radius: 2px; border: none; color: white; font-family: inherit; font-size: inherit; padding: 0px 5px; letter-spacing: 1px; cursor: pointer; } #animateBtn:focus { outline: none; } #animateBtn[disabled] { cursor: default; } .height { height: 10px; } </style></head> <body> <h1>GeeksforGeeks</h1> <b>How to use circular animation on favicon image</b> <div class=\"height\"> </div> <br> <!-- Canvas nad button for animation --> <button id=\"animateBtn\">Animate Favicon </button> <br> <br> <canvas id=\"canvasId\" width=32 height=32></canvas></body> </html>", "e": 7496, "s": 4679, "text": null }, { "code": null, "e": 7504, "s": 7496, "text": "Output:" }, { "code": null, "e": 12594, "s": 7504, "text": "Example 2: In this example, the implementation of drawing a square which transforms the favicon into a animated image.<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <link rel=\"shortcut icon\" href=\"gfgFavicon.png\" width=32px> <script language=\"javascript\"> onload = () => { var canvas = document.getElementById(\"canvas\"); context = canvas.getContext('2d'); if (!!context) { var animateBtn = document.getElementById(\"animateBtn\"); faviconVar = document.querySelector('link[rel*=\"icon\"]'); // The styles used for the square which will // be animated in place of favicon let linerGradient = context.createLinearGradient(0, 0, 32, 32); linerGradient.addColorStop(0, '#8be8a7'); linerGradient.addColorStop(1, '#297d4c'); context.strokeStyle = linerGradient; context.lineWidth = 10; // On page refresh , the button is enabled if (animateBtn.disabled) animateBtn.removeAttribute('disabled'); animateBtn.addEventListener('click', function() { // Variable used for drawing incrementation n = 0, // Speed interval for animation loadingInterval = setInterval(drawSquareLoader, 80); this.textContent = 'Animating...'; this.style.backgroundColor = '#297d4c'; //Once the drawing is done, the button is again disabled this.setAttribute('disabled', ''); }); } }; // Function for drawing square in canvas in a incrementing way function drawSquareLoader() { with(context) { clearRect(0, 0, 32, 32); beginPath(); // One fourth time taken to draw if (n <= 25) { moveTo(0, 0); lineTo((32 / 25) * n, 0); } // Between second quarter of drawing else if (n > 25 && n <= 50) { moveTo(0, 0); lineTo(32, 0); moveTo(32, 0); lineTo(32, (32 / 25) * (n - 25)); } // Between third quarter of drawing else if (n > 50 && n <= 75) { moveTo(0, 0); lineTo(32, 0); moveTo(32, 0); lineTo(32, 32); moveTo(32, 32); lineTo(-((32 / 25) * (n - 75)), 32); } // Between last quarter else if (n > 75 && n <= 100) { moveTo(0, 0); lineTo(32, 0); moveTo(32, 0); lineTo(32, 32); moveTo(32, 32); lineTo(0, 32); moveTo(0, 32); lineTo(0, -((32 / 25) * (n - 100))); } //Function to draw the path stroke(); } // Assigning the drawing to favicon after // converting into PNG image faviconVar.href = canvas.toDataURL('image/png'); // After the drawing is finished if (n === 100) { clearInterval(loadingInterval); animateBtn.textContent = 'Favicon Loaded'; animateBtn.style.backgroundColor = '#bbbbbb'; return; } // Increment the variable used to keep // track of drawing intervals n++; } </script> <title>Animation on favicon image</title> <style> body { width: 450px; height: 300px; margin: 10px; text-align: center; } h1 { color: green; } html { background: #f4f6fa; } #animateBtn { background: #1c2e46; color: white; font: inherit; border: none; padding: 0px 5px; letter-spacing: 1px; cursor: pointer; border-radius: 2px; } canvas { margin: auto; display: block; } .height { height: 10px; } </style></head> <body> <h1>GeeksforGeeks</h1> <b>How to use animation on favicon image</b> <div class=\"height\"> </div> <br> <button id=\"animateBtn\">Animate Favicon</button> <br> <br> <canvas id=\"canvas\" width=32 height=32></canvas> </body> </html>" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <link rel=\"shortcut icon\" href=\"gfgFavicon.png\" width=32px> <script language=\"javascript\"> onload = () => { var canvas = document.getElementById(\"canvas\"); context = canvas.getContext('2d'); if (!!context) { var animateBtn = document.getElementById(\"animateBtn\"); faviconVar = document.querySelector('link[rel*=\"icon\"]'); // The styles used for the square which will // be animated in place of favicon let linerGradient = context.createLinearGradient(0, 0, 32, 32); linerGradient.addColorStop(0, '#8be8a7'); linerGradient.addColorStop(1, '#297d4c'); context.strokeStyle = linerGradient; context.lineWidth = 10; // On page refresh , the button is enabled if (animateBtn.disabled) animateBtn.removeAttribute('disabled'); animateBtn.addEventListener('click', function() { // Variable used for drawing incrementation n = 0, // Speed interval for animation loadingInterval = setInterval(drawSquareLoader, 80); this.textContent = 'Animating...'; this.style.backgroundColor = '#297d4c'; //Once the drawing is done, the button is again disabled this.setAttribute('disabled', ''); }); } }; // Function for drawing square in canvas in a incrementing way function drawSquareLoader() { with(context) { clearRect(0, 0, 32, 32); beginPath(); // One fourth time taken to draw if (n <= 25) { moveTo(0, 0); lineTo((32 / 25) * n, 0); } // Between second quarter of drawing else if (n > 25 && n <= 50) { moveTo(0, 0); lineTo(32, 0); moveTo(32, 0); lineTo(32, (32 / 25) * (n - 25)); } // Between third quarter of drawing else if (n > 50 && n <= 75) { moveTo(0, 0); lineTo(32, 0); moveTo(32, 0); lineTo(32, 32); moveTo(32, 32); lineTo(-((32 / 25) * (n - 75)), 32); } // Between last quarter else if (n > 75 && n <= 100) { moveTo(0, 0); lineTo(32, 0); moveTo(32, 0); lineTo(32, 32); moveTo(32, 32); lineTo(0, 32); moveTo(0, 32); lineTo(0, -((32 / 25) * (n - 100))); } //Function to draw the path stroke(); } // Assigning the drawing to favicon after // converting into PNG image faviconVar.href = canvas.toDataURL('image/png'); // After the drawing is finished if (n === 100) { clearInterval(loadingInterval); animateBtn.textContent = 'Favicon Loaded'; animateBtn.style.backgroundColor = '#bbbbbb'; return; } // Increment the variable used to keep // track of drawing intervals n++; } </script> <title>Animation on favicon image</title> <style> body { width: 450px; height: 300px; margin: 10px; text-align: center; } h1 { color: green; } html { background: #f4f6fa; } #animateBtn { background: #1c2e46; color: white; font: inherit; border: none; padding: 0px 5px; letter-spacing: 1px; cursor: pointer; border-radius: 2px; } canvas { margin: auto; display: block; } .height { height: 10px; } </style></head> <body> <h1>GeeksforGeeks</h1> <b>How to use animation on favicon image</b> <div class=\"height\"> </div> <br> <button id=\"animateBtn\">Animate Favicon</button> <br> <br> <canvas id=\"canvas\" width=32 height=32></canvas> </body> </html>", "e": 17566, "s": 12594, "text": null }, { "code": null, "e": 17574, "s": 17566, "text": "Output:" }, { "code": null, "e": 17583, "s": 17574, "text": "CSS-Misc" }, { "code": null, "e": 17593, "s": 17583, "text": "HTML-Misc" }, { "code": null, "e": 17609, "s": 17593, "text": "JavaScript-Misc" }, { "code": null, "e": 17616, "s": 17609, "text": "Picked" }, { "code": null, "e": 17621, "s": 17616, "text": "HTML" }, { "code": null, "e": 17632, "s": 17621, "text": "JavaScript" }, { "code": null, "e": 17649, "s": 17632, "text": "Web Technologies" }, { "code": null, "e": 17676, "s": 17649, "text": "Web technologies Questions" }, { "code": null, "e": 17681, "s": 17676, "text": "HTML" }, { "code": null, "e": 17779, "s": 17681, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 17803, "s": 17779, "text": "REST API (Introduction)" }, { "code": null, "e": 17853, "s": 17803, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 17892, "s": 17853, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 17929, "s": 17892, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 17979, "s": 17929, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 18040, "s": 17979, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 18112, "s": 18040, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 18152, "s": 18112, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 18204, "s": 18152, "text": "How to append HTML code to a div using JavaScript ?" } ]
BigDecimal setScale() method in Java with Examples
17 Jun, 2019 The java.math.BigDecimal.setScale() is used to set the scale of BigDecimal. This method performs an operation upon the current BigDecimal by which this method is called. There are three overloads of setScale() method available in Java which is listed below: setScale(int newScale) setScale(int newScale, int roundingMode) setScale(int newScale, RoundingMode roundingMode) Note: The setScale(int newScale, int roundingMode) is deprecated since Java 9. This call is typically used to increase the scale when it is guaranteed that there exists a BigDecimal of the specified scale and the correct value. The call can also be used to reduce the scale if the user knows that the BigDecimal has sufficiently many zeros at the end of its fractional part to allow for the rescaling without changing its value.Syntax: public BigDecimal setScale(int newScale) Parameters: This method accepts a parameter newScale which is used to set the scale of this BigDecimal.Return value: This method returns a BigDecimal whose scale is of the specified value.Exception: If the specified scaling operation would require rounding then Arithmetic Exception is thrown.Note: Since BigDecimal objects are immutable, calls of this method do not result in the original object being modified, setScale returns an object with the proper scale. The returned object may or may not be newly allocated. Below programs is used to illustrate the setScale() method of BigDecimal. // Java program to demonstrate// setScale() method of BigDecimal import java.math.BigDecimal; public class GFG { public static void main(String[] args) { // BigDecimal object to store the result BigDecimal res; // For user input // Use Scanner or BufferedReader // Object of String created // Holds the value String input1 = "31452678569.25"; // Convert the string input to BigDecimal BigDecimal a = new BigDecimal(input1); // Scale for BigDecimal int newScale = 4; // Using setScale() method res = a.setScale(newScale); // Display the result in BigDecimal System.out.println(res); }} 31452678569.2500 This method is used to calculate a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal’s unscaled value by the appropriate power of ten to maintain its overall value. If the scale is reduced by the operation then unscaled value must be divided (rather than multiplied). The specified rounding mode is applied to the division.Syntax: public BigDecimal setScale(int newScale, int roundingMode) Parameters: This method accepts two parameter newScale which is used to set the scale of this BigDecimal and roundingMode to set the rounding value of result.Return value: This method returns a BigDecimal whose scale is of the specified value.Exception: The method throws Arithmetic Exception if roundingMode is UNNECESSARY and the specified scaling operation would require rounding. This method also throws IllegalArgumentException if roundingMode does not represent a valid rounding mode. Below programs is used to illustrate the setScale() method of BigDecimal.Example 1: // Java program to demonstrate// setScale() method of BigDecimal import java.math.BigDecimal; public class GFG { public static void main(String[] args) { // BigDecimal object to store the result BigDecimal res; // For user input // Use Scanner or BufferedReader // Object of String created // Holds the value String input1 = "31452678569.24"; // Convert the string input to BigDecimal BigDecimal a = new BigDecimal(input1); // Scale for BigDecimal int newScale = -1; try { // Using setScale() method res = a.setScale(newScale, 1); // Display the result in BigDecimal System.out.println(res); } catch (Exception e) { // Print Exception System.out.println(e); } }} 3.145267856E+10 Example 2: Program showing Exceptions thrown by this method. // Java program to demonstrate// setScale() method of BigDecimal import java.math.BigDecimal; public class GFG { public static void main(String[] args) { // BigDecimal object to store the result BigDecimal res; // For user input // Use Scanner or BufferedReader // Object of String created // Holds the value String input1 = "31452678569.24"; // Convert the string input to BigDecimal BigDecimal a = new BigDecimal(input1); // Scale for BigDecimal int newScale = -1; try { // Using setScale() method res = a.setScale(newScale, 7); // Display the result in BigDecimal System.out.println(res); } catch (Exception e) { // Print Exception System.out.println(e); } try { // Using setScale() method res = a.setScale(newScale, 10); // Display the result in BigDecimal System.out.println(res); } catch (Exception e) { // Print Exception System.out.println(e); } }} java.lang.ArithmeticException: Rounding necessary java.lang.IllegalArgumentException: Invalid rounding mode This method is used to calculate a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal’s unscaled value by the appropriate power of ten to maintain its overall value. If the scale is reduced by the operation then unscaled value must be divided (rather than multiplied). The specified rounding mode is applied to the division.Syntax: public BigDecimal setScale(int newScale, RoundingMode roundingMode) Parameters: This method accepts two parameter newScale which is used to set the scale of this BigDecimal and roundingMode of type RoundingMode that tells which rounding mode to apply.Return value: This method returns a BigDecimal whose scale is of the specified value.Exception: The method throws Arithmetic Exception if roundingMode is UNNECESSARY and the specified scaling operation would require rounding. Below programs is used to illustrate the setScale() method of BigDecimal.Example 1: // Java program to demonstrate// setScale() method of BigDecimal import java.math.*; public class GFG { public static void main(String[] args) { // BigDecimal object to store the result BigDecimal res; // For user input // Use Scanner or BufferedReader // Object of String created // Holds the value String input1 = "31452678569.24"; // Convert the string input to BigDecimal BigDecimal a = new BigDecimal(input1); // Scale for BigDecimal int newScale = 1; try { // Using setScale() method // Using RoundingMode.CEILING res = a.setScale(newScale, RoundingMode.CEILING); // Display the result in BigDecimal System.out.println(res); } catch (Exception e) { // Print Exception System.out.println(e); } }} 31452678569.3 Example 2: Program showing Exceptions thrown by this method. // Java program to demonstrate// setScale() method of BigDecimal import java.math.*; public class GFG { public static void main(String[] args) { // BigDecimal object to store the result BigDecimal res; // For user input // Use Scanner or BufferedReader // Object of String created // Holds the value String input1 = "31452678569.24"; // Convert the string input to BigDecimal BigDecimal a = new BigDecimal(input1); // Scale for BigDecimal int newScale = -1; try { // Using setScale() method // Using RoundingMode.UNNECESSARY res = a.setScale(newScale, RoundingMode.UNNECESSARY); // Display the result in BigDecimal System.out.println(res); } catch (Exception e) { // Print Exception System.out.println(e); } }} java.lang.ArithmeticException: Rounding necessary References: https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/math/BigDecimal.html#setScale(int) Java-BigDecimal Java-Functions Java-math-package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples Stream In Java ArrayList in Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jun, 2019" }, { "code": null, "e": 198, "s": 28, "text": "The java.math.BigDecimal.setScale() is used to set the scale of BigDecimal. This method performs an operation upon the current BigDecimal by which this method is called." }, { "code": null, "e": 286, "s": 198, "text": "There are three overloads of setScale() method available in Java which is listed below:" }, { "code": null, "e": 309, "s": 286, "text": "setScale(int newScale)" }, { "code": null, "e": 350, "s": 309, "text": "setScale(int newScale, int roundingMode)" }, { "code": null, "e": 400, "s": 350, "text": "setScale(int newScale, RoundingMode roundingMode)" }, { "code": null, "e": 479, "s": 400, "text": "Note: The setScale(int newScale, int roundingMode) is deprecated since Java 9." }, { "code": null, "e": 836, "s": 479, "text": "This call is typically used to increase the scale when it is guaranteed that there exists a BigDecimal of the specified scale and the correct value. The call can also be used to reduce the scale if the user knows that the BigDecimal has sufficiently many zeros at the end of its fractional part to allow for the rescaling without changing its value.Syntax:" }, { "code": null, "e": 878, "s": 836, "text": "public BigDecimal setScale(int newScale)\n" }, { "code": null, "e": 1396, "s": 878, "text": "Parameters: This method accepts a parameter newScale which is used to set the scale of this BigDecimal.Return value: This method returns a BigDecimal whose scale is of the specified value.Exception: If the specified scaling operation would require rounding then Arithmetic Exception is thrown.Note: Since BigDecimal objects are immutable, calls of this method do not result in the original object being modified, setScale returns an object with the proper scale. The returned object may or may not be newly allocated." }, { "code": null, "e": 1470, "s": 1396, "text": "Below programs is used to illustrate the setScale() method of BigDecimal." }, { "code": "// Java program to demonstrate// setScale() method of BigDecimal import java.math.BigDecimal; public class GFG { public static void main(String[] args) { // BigDecimal object to store the result BigDecimal res; // For user input // Use Scanner or BufferedReader // Object of String created // Holds the value String input1 = \"31452678569.25\"; // Convert the string input to BigDecimal BigDecimal a = new BigDecimal(input1); // Scale for BigDecimal int newScale = 4; // Using setScale() method res = a.setScale(newScale); // Display the result in BigDecimal System.out.println(res); }}", "e": 2205, "s": 1470, "text": null }, { "code": null, "e": 2223, "s": 2205, "text": "31452678569.2500\n" }, { "code": null, "e": 2633, "s": 2223, "text": "This method is used to calculate a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal’s unscaled value by the appropriate power of ten to maintain its overall value. If the scale is reduced by the operation then unscaled value must be divided (rather than multiplied). The specified rounding mode is applied to the division.Syntax:" }, { "code": null, "e": 2693, "s": 2633, "text": "public BigDecimal setScale(int newScale, int roundingMode)\n" }, { "code": null, "e": 3184, "s": 2693, "text": "Parameters: This method accepts two parameter newScale which is used to set the scale of this BigDecimal and roundingMode to set the rounding value of result.Return value: This method returns a BigDecimal whose scale is of the specified value.Exception: The method throws Arithmetic Exception if roundingMode is UNNECESSARY and the specified scaling operation would require rounding. This method also throws IllegalArgumentException if roundingMode does not represent a valid rounding mode." }, { "code": null, "e": 3268, "s": 3184, "text": "Below programs is used to illustrate the setScale() method of BigDecimal.Example 1:" }, { "code": "// Java program to demonstrate// setScale() method of BigDecimal import java.math.BigDecimal; public class GFG { public static void main(String[] args) { // BigDecimal object to store the result BigDecimal res; // For user input // Use Scanner or BufferedReader // Object of String created // Holds the value String input1 = \"31452678569.24\"; // Convert the string input to BigDecimal BigDecimal a = new BigDecimal(input1); // Scale for BigDecimal int newScale = -1; try { // Using setScale() method res = a.setScale(newScale, 1); // Display the result in BigDecimal System.out.println(res); } catch (Exception e) { // Print Exception System.out.println(e); } }}", "e": 4149, "s": 3268, "text": null }, { "code": null, "e": 4166, "s": 4149, "text": "3.145267856E+10\n" }, { "code": null, "e": 4227, "s": 4166, "text": "Example 2: Program showing Exceptions thrown by this method." }, { "code": "// Java program to demonstrate// setScale() method of BigDecimal import java.math.BigDecimal; public class GFG { public static void main(String[] args) { // BigDecimal object to store the result BigDecimal res; // For user input // Use Scanner or BufferedReader // Object of String created // Holds the value String input1 = \"31452678569.24\"; // Convert the string input to BigDecimal BigDecimal a = new BigDecimal(input1); // Scale for BigDecimal int newScale = -1; try { // Using setScale() method res = a.setScale(newScale, 7); // Display the result in BigDecimal System.out.println(res); } catch (Exception e) { // Print Exception System.out.println(e); } try { // Using setScale() method res = a.setScale(newScale, 10); // Display the result in BigDecimal System.out.println(res); } catch (Exception e) { // Print Exception System.out.println(e); } }}", "e": 5406, "s": 4227, "text": null }, { "code": null, "e": 5515, "s": 5406, "text": "java.lang.ArithmeticException: Rounding necessary\njava.lang.IllegalArgumentException: Invalid rounding mode\n" }, { "code": null, "e": 5925, "s": 5515, "text": "This method is used to calculate a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal’s unscaled value by the appropriate power of ten to maintain its overall value. If the scale is reduced by the operation then unscaled value must be divided (rather than multiplied). The specified rounding mode is applied to the division.Syntax:" }, { "code": null, "e": 5994, "s": 5925, "text": "public BigDecimal setScale(int newScale, RoundingMode roundingMode)\n" }, { "code": null, "e": 6403, "s": 5994, "text": "Parameters: This method accepts two parameter newScale which is used to set the scale of this BigDecimal and roundingMode of type RoundingMode that tells which rounding mode to apply.Return value: This method returns a BigDecimal whose scale is of the specified value.Exception: The method throws Arithmetic Exception if roundingMode is UNNECESSARY and the specified scaling operation would require rounding." }, { "code": null, "e": 6487, "s": 6403, "text": "Below programs is used to illustrate the setScale() method of BigDecimal.Example 1:" }, { "code": "// Java program to demonstrate// setScale() method of BigDecimal import java.math.*; public class GFG { public static void main(String[] args) { // BigDecimal object to store the result BigDecimal res; // For user input // Use Scanner or BufferedReader // Object of String created // Holds the value String input1 = \"31452678569.24\"; // Convert the string input to BigDecimal BigDecimal a = new BigDecimal(input1); // Scale for BigDecimal int newScale = 1; try { // Using setScale() method // Using RoundingMode.CEILING res = a.setScale(newScale, RoundingMode.CEILING); // Display the result in BigDecimal System.out.println(res); } catch (Exception e) { // Print Exception System.out.println(e); } }}", "e": 7420, "s": 6487, "text": null }, { "code": null, "e": 7435, "s": 7420, "text": "31452678569.3\n" }, { "code": null, "e": 7496, "s": 7435, "text": "Example 2: Program showing Exceptions thrown by this method." }, { "code": "// Java program to demonstrate// setScale() method of BigDecimal import java.math.*; public class GFG { public static void main(String[] args) { // BigDecimal object to store the result BigDecimal res; // For user input // Use Scanner or BufferedReader // Object of String created // Holds the value String input1 = \"31452678569.24\"; // Convert the string input to BigDecimal BigDecimal a = new BigDecimal(input1); // Scale for BigDecimal int newScale = -1; try { // Using setScale() method // Using RoundingMode.UNNECESSARY res = a.setScale(newScale, RoundingMode.UNNECESSARY); // Display the result in BigDecimal System.out.println(res); } catch (Exception e) { // Print Exception System.out.println(e); } }}", "e": 8438, "s": 7496, "text": null }, { "code": null, "e": 8489, "s": 8438, "text": "java.lang.ArithmeticException: Rounding necessary\n" }, { "code": null, "e": 8602, "s": 8489, "text": "References: https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/math/BigDecimal.html#setScale(int)" }, { "code": null, "e": 8618, "s": 8602, "text": "Java-BigDecimal" }, { "code": null, "e": 8633, "s": 8618, "text": "Java-Functions" }, { "code": null, "e": 8651, "s": 8633, "text": "Java-math-package" }, { "code": null, "e": 8656, "s": 8651, "text": "Java" }, { "code": null, "e": 8661, "s": 8656, "text": "Java" }, { "code": null, "e": 8759, "s": 8661, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8810, "s": 8759, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 8841, "s": 8810, "text": "How to iterate any Map in Java" }, { "code": null, "e": 8860, "s": 8841, "text": "Interfaces in Java" }, { "code": null, "e": 8890, "s": 8860, "text": "HashMap in Java with Examples" }, { "code": null, "e": 8905, "s": 8890, "text": "Stream In Java" }, { "code": null, "e": 8923, "s": 8905, "text": "ArrayList in Java" }, { "code": null, "e": 8943, "s": 8923, "text": "Collections in Java" }, { "code": null, "e": 8967, "s": 8943, "text": "Singleton Class in Java" }, { "code": null, "e": 8999, "s": 8967, "text": "Multidimensional Arrays in Java" } ]
Python – Web App To Send Push Notification To Your Phone
05 Oct, 2021 In this article, we will discuss two apps and how they can be configured using python to send notifications. Pushbullet, a prominent Python package, which connects multiple devices using python code. In this article, we will discuss how to send messages or notifications through it. Using our computer and python code, we will send some messages to the pushbullet app installed on a mobile device, which has the same login id, as the one on the computer. For this first, we’ll need to create an account on Pushbullet.com and sign in to it, from computer and phone both. Set up a Pushbullet account on your PC and PhoneFor PCGo to Pushbullet.comCreate an account For PCGo to Pushbullet.comCreate an account Go to Pushbullet.com Create an account For PhoneInstall the Pushbullet app on your phone.Log in using the same email address that you used to log in to your PC. Install the Pushbullet app on your phone. Log in using the same email address that you used to log in to your PC. Now let us move to the python code part and understand how each requirement has to be planned to realize the functionality. Install the following modules listed below # Used for sending the Push notifications. pip install pushbullet.py==0.9.1 # Used for the interface at the output window. pip install pywebio Import all the required modules Go to Pushbullet and obtain the access token. Get your Access Token and use the PushBullet method to create an instance by providing the Access Token in the PushBullet function. Syntax: PushBullet(access_token) Use the push_note function to send data and text inside the function. push_note will take two arguments i.e. data and text. the first argument will work as a Heading in the notification where 2nd argument is a text. Syntax: pb.push_note(data, text) Below is the complete implementation. Python3 # Import the following modulesfrom pushbullet import PushBulletfrom pywebio.input import *from pywebio.output import *from pywebio.session import *import time # Get the access token from Pushbullet.comaccess_token = "Your Access Token" # Taking input from the userdata = input('Title') # Taking large text input from the usertext = textarea( "Text", rows=3, placeholder="Write something...", required=True) # Get the instance using access tokenpb = PushBullet(access_token) # Send the data by passing the main title# and text to be sendpush = pb.push_note(data, text) # Put a success message after sending# the notificationput_success("Message sent successfully...") # Sleep for 3 secondstime.sleep(3) # Clear the screenclear() # Give the pop at lasttoast("Thanks for using it :)") # hold the session until the whole work finisheshold() There is one more way to do the same, discussed below. In this method, a predefined message is sent as a notification. For this, first import the required modules and get your Access Token. Syntax: TOKEN = 'Your Access Token' Then Make a dictionary with all the information you wish to send in the body. Syntax: msg = {β€œtype”: β€œnote”, β€œtitle”: title, β€œbody”: body} Now, to send the posts request, use the posts method specified in the requests module. Push the Pushbullet along the entire path. Now use json.dumps to dump all the data into a data variable. Now pass the dictionary to the header variable, which includes the sender’s authorization, your access token, and content-types, which is application/json in this case. Syntax: requests.post(β€˜url’, data=json.dumps(msg), headers={β€˜Authorization’: β€˜Bearer β€˜ + TOKEN, Content-Type’: β€˜application/json’}) Now look at the response status code; if it’s 200, we’ve had an error; otherwise, our message will have been sent properly. Given below is the complete implementation. Program: Python3 # Import the following modulesimport requestsimport json # Function to send Push Notification def pushbullet_noti(title, body): TOKEN = 'Your Access Token' # Pass your Access Token here # Make a dictionary that includes, title and body msg = {"type": "note", "title": title, "body": body} # Sent a posts request resp = requests.post('https://api.pushbullet.com/v2/pushes', data=json.dumps(msg), headers={'Authorization': 'Bearer ' + TOKEN, 'Content-Type': 'application/json'}) if resp.status_code != 200: # Check if fort message send with the help of status code raise Exception('Error', resp.status_code) else: print('Message sent') pushbullet_noti("Hey", "How you doing?") Output: In this part we will be dealing with posting messages from python script that will appear in slack. For this, we need to make use of webhooks. You can deliver automatic messages from one app to another using webhooks. When you create an Incoming Webhook, you’ll be given a unique URL to which you may send a JSON payload including the message text and some parameters. Create a Slack Workspace here and create your own app. go to Browse Slack Select Apps A new window will appear. From there select App Directory Now select Build Again a new window will open up, select create an app Select from scratch Set app name and workspace Then create app Select Incoming Webhooks Turn activate incoming webhooks on and add new webhook to workspace select a bot and give it allow access Copy the webhook URL as this will be used later Now that we’ve created the app and obtained the webhook URL, it’s time to start coding. We first have to import all the required modules. Now, get your webhook URL and save it to the variable. In a variable, save the message and title you want to send. Now it’s time to make all the slack data we want to send. It consists of your username and in the Attachment section we have: The color you want to choose. Fields consist of the following things:Title of our message.The message we want to send.Short means, display message should be of sort type or long type. Title of our message. The message we want to send. Short means, display message should be of sort type or long type. Now with the use of the sys module, we will get the size of the slack data and store it in a variable. Now for headers, we will define the Content-Type and Content-Length. Use the post method of requests module to post all, the data after dumping it using the dumps function of json module. At last, check whether the response is valid or not with the use of a status code. Program: Sending notifications via slack Python3 # Import the following modulesimport jsonimport sysimport requestsimport base64 if __name__ == '__main__': # Webhooks URL url = "https://hooks.slack.com/services/xxxyyyzzz" # Message you wanna send message = ( "Hi there!, GeeksforGeeks is the Best Learning Platform\ for Computer Science Students") # Title title = (f"GeeksforGeeks Bot :satellite:") # All slack data slack_data = { "username": "Testing", "attachments": [ { "color": "#FF0000", "fields": [ { "title": title, "value": message, "short": "false", } ] } ] } # Size of the slack data byte_length = str(sys.getsizeof(slack_data)) headers = {'Content-Type': "application/json", 'Content-Length': byte_length} # Posting requests after dumping the slack data response = requests.post(url, data=json.dumps(slack_data), headers=headers) # Post request is valid or not! if response.status_code != 200: raise Exception(response.status_code, response.text) Output: arorakashish0911 sweetyty Python-projects python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Oct, 2021" }, { "code": null, "e": 137, "s": 28, "text": "In this article, we will discuss two apps and how they can be configured using python to send notifications." }, { "code": null, "e": 598, "s": 137, "text": "Pushbullet, a prominent Python package, which connects multiple devices using python code. In this article, we will discuss how to send messages or notifications through it. Using our computer and python code, we will send some messages to the pushbullet app installed on a mobile device, which has the same login id, as the one on the computer. For this first, we’ll need to create an account on Pushbullet.com and sign in to it, from computer and phone both." }, { "code": null, "e": 690, "s": 598, "text": "Set up a Pushbullet account on your PC and PhoneFor PCGo to Pushbullet.comCreate an account" }, { "code": null, "e": 734, "s": 690, "text": "For PCGo to Pushbullet.comCreate an account" }, { "code": null, "e": 755, "s": 734, "text": "Go to Pushbullet.com" }, { "code": null, "e": 773, "s": 755, "text": "Create an account" }, { "code": null, "e": 895, "s": 773, "text": "For PhoneInstall the Pushbullet app on your phone.Log in using the same email address that you used to log in to your PC." }, { "code": null, "e": 937, "s": 895, "text": "Install the Pushbullet app on your phone." }, { "code": null, "e": 1009, "s": 937, "text": "Log in using the same email address that you used to log in to your PC." }, { "code": null, "e": 1134, "s": 1009, "text": "Now let us move to the python code part and understand how each requirement has to be planned to realize the functionality. " }, { "code": null, "e": 1177, "s": 1134, "text": "Install the following modules listed below" }, { "code": null, "e": 1323, "s": 1177, "text": "# Used for sending the Push notifications.\npip install pushbullet.py==0.9.1\n\n# Used for the interface at the output window. \npip install pywebio " }, { "code": null, "e": 1355, "s": 1323, "text": "Import all the required modules" }, { "code": null, "e": 1401, "s": 1355, "text": "Go to Pushbullet and obtain the access token." }, { "code": null, "e": 1533, "s": 1401, "text": "Get your Access Token and use the PushBullet method to create an instance by providing the Access Token in the PushBullet function." }, { "code": null, "e": 1541, "s": 1533, "text": "Syntax:" }, { "code": null, "e": 1566, "s": 1541, "text": "PushBullet(access_token)" }, { "code": null, "e": 1782, "s": 1566, "text": "Use the push_note function to send data and text inside the function. push_note will take two arguments i.e. data and text. the first argument will work as a Heading in the notification where 2nd argument is a text." }, { "code": null, "e": 1790, "s": 1782, "text": "Syntax:" }, { "code": null, "e": 1815, "s": 1790, "text": "pb.push_note(data, text)" }, { "code": null, "e": 1853, "s": 1815, "text": "Below is the complete implementation." }, { "code": null, "e": 1861, "s": 1853, "text": "Python3" }, { "code": "# Import the following modulesfrom pushbullet import PushBulletfrom pywebio.input import *from pywebio.output import *from pywebio.session import *import time # Get the access token from Pushbullet.comaccess_token = \"Your Access Token\" # Taking input from the userdata = input('Title') # Taking large text input from the usertext = textarea( \"Text\", rows=3, placeholder=\"Write something...\", required=True) # Get the instance using access tokenpb = PushBullet(access_token) # Send the data by passing the main title# and text to be sendpush = pb.push_note(data, text) # Put a success message after sending# the notificationput_success(\"Message sent successfully...\") # Sleep for 3 secondstime.sleep(3) # Clear the screenclear() # Give the pop at lasttoast(\"Thanks for using it :)\") # hold the session until the whole work finisheshold()", "e": 2701, "s": 1861, "text": null }, { "code": null, "e": 2820, "s": 2701, "text": "There is one more way to do the same, discussed below. In this method, a predefined message is sent as a notification." }, { "code": null, "e": 2891, "s": 2820, "text": "For this, first import the required modules and get your Access Token." }, { "code": null, "e": 2899, "s": 2891, "text": "Syntax:" }, { "code": null, "e": 2927, "s": 2899, "text": "TOKEN = 'Your Access Token'" }, { "code": null, "e": 3005, "s": 2927, "text": "Then Make a dictionary with all the information you wish to send in the body." }, { "code": null, "e": 3013, "s": 3005, "text": "Syntax:" }, { "code": null, "e": 3066, "s": 3013, "text": "msg = {β€œtype”: β€œnote”, β€œtitle”: title, β€œbody”: body}" }, { "code": null, "e": 3258, "s": 3066, "text": "Now, to send the posts request, use the posts method specified in the requests module. Push the Pushbullet along the entire path. Now use json.dumps to dump all the data into a data variable." }, { "code": null, "e": 3427, "s": 3258, "text": "Now pass the dictionary to the header variable, which includes the sender’s authorization, your access token, and content-types, which is application/json in this case." }, { "code": null, "e": 3435, "s": 3427, "text": "Syntax:" }, { "code": null, "e": 3559, "s": 3435, "text": "requests.post(β€˜url’, data=json.dumps(msg), headers={β€˜Authorization’: β€˜Bearer β€˜ + TOKEN, Content-Type’: β€˜application/json’})" }, { "code": null, "e": 3683, "s": 3559, "text": "Now look at the response status code; if it’s 200, we’ve had an error; otherwise, our message will have been sent properly." }, { "code": null, "e": 3727, "s": 3683, "text": "Given below is the complete implementation." }, { "code": null, "e": 3737, "s": 3727, "text": "Program: " }, { "code": null, "e": 3745, "s": 3737, "text": "Python3" }, { "code": "# Import the following modulesimport requestsimport json # Function to send Push Notification def pushbullet_noti(title, body): TOKEN = 'Your Access Token' # Pass your Access Token here # Make a dictionary that includes, title and body msg = {\"type\": \"note\", \"title\": title, \"body\": body} # Sent a posts request resp = requests.post('https://api.pushbullet.com/v2/pushes', data=json.dumps(msg), headers={'Authorization': 'Bearer ' + TOKEN, 'Content-Type': 'application/json'}) if resp.status_code != 200: # Check if fort message send with the help of status code raise Exception('Error', resp.status_code) else: print('Message sent') pushbullet_noti(\"Hey\", \"How you doing?\")", "e": 4541, "s": 3745, "text": null }, { "code": null, "e": 4549, "s": 4541, "text": "Output:" }, { "code": null, "e": 4918, "s": 4549, "text": "In this part we will be dealing with posting messages from python script that will appear in slack. For this, we need to make use of webhooks. You can deliver automatic messages from one app to another using webhooks. When you create an Incoming Webhook, you’ll be given a unique URL to which you may send a JSON payload including the message text and some parameters." }, { "code": null, "e": 4973, "s": 4918, "text": "Create a Slack Workspace here and create your own app." }, { "code": null, "e": 4992, "s": 4973, "text": "go to Browse Slack" }, { "code": null, "e": 5004, "s": 4992, "text": "Select Apps" }, { "code": null, "e": 5062, "s": 5004, "text": "A new window will appear. From there select App Directory" }, { "code": null, "e": 5079, "s": 5062, "text": "Now select Build" }, { "code": null, "e": 5133, "s": 5079, "text": "Again a new window will open up, select create an app" }, { "code": null, "e": 5153, "s": 5133, "text": "Select from scratch" }, { "code": null, "e": 5180, "s": 5153, "text": "Set app name and workspace" }, { "code": null, "e": 5196, "s": 5180, "text": "Then create app" }, { "code": null, "e": 5221, "s": 5196, "text": "Select Incoming Webhooks" }, { "code": null, "e": 5289, "s": 5221, "text": "Turn activate incoming webhooks on and add new webhook to workspace" }, { "code": null, "e": 5327, "s": 5289, "text": "select a bot and give it allow access" }, { "code": null, "e": 5375, "s": 5327, "text": "Copy the webhook URL as this will be used later" }, { "code": null, "e": 5463, "s": 5375, "text": "Now that we’ve created the app and obtained the webhook URL, it’s time to start coding." }, { "code": null, "e": 5628, "s": 5463, "text": "We first have to import all the required modules. Now, get your webhook URL and save it to the variable. In a variable, save the message and title you want to send." }, { "code": null, "e": 5754, "s": 5628, "text": "Now it’s time to make all the slack data we want to send. It consists of your username and in the Attachment section we have:" }, { "code": null, "e": 5784, "s": 5754, "text": "The color you want to choose." }, { "code": null, "e": 5938, "s": 5784, "text": "Fields consist of the following things:Title of our message.The message we want to send.Short means, display message should be of sort type or long type." }, { "code": null, "e": 5960, "s": 5938, "text": "Title of our message." }, { "code": null, "e": 5989, "s": 5960, "text": "The message we want to send." }, { "code": null, "e": 6055, "s": 5989, "text": "Short means, display message should be of sort type or long type." }, { "code": null, "e": 6429, "s": 6055, "text": "Now with the use of the sys module, we will get the size of the slack data and store it in a variable. Now for headers, we will define the Content-Type and Content-Length. Use the post method of requests module to post all, the data after dumping it using the dumps function of json module. At last, check whether the response is valid or not with the use of a status code." }, { "code": null, "e": 6470, "s": 6429, "text": "Program: Sending notifications via slack" }, { "code": null, "e": 6478, "s": 6470, "text": "Python3" }, { "code": "# Import the following modulesimport jsonimport sysimport requestsimport base64 if __name__ == '__main__': # Webhooks URL url = \"https://hooks.slack.com/services/xxxyyyzzz\" # Message you wanna send message = ( \"Hi there!, GeeksforGeeks is the Best Learning Platform\\ for Computer Science Students\") # Title title = (f\"GeeksforGeeks Bot :satellite:\") # All slack data slack_data = { \"username\": \"Testing\", \"attachments\": [ { \"color\": \"#FF0000\", \"fields\": [ { \"title\": title, \"value\": message, \"short\": \"false\", } ] } ] } # Size of the slack data byte_length = str(sys.getsizeof(slack_data)) headers = {'Content-Type': \"application/json\", 'Content-Length': byte_length} # Posting requests after dumping the slack data response = requests.post(url, data=json.dumps(slack_data), headers=headers) # Post request is valid or not! if response.status_code != 200: raise Exception(response.status_code, response.text)", "e": 7697, "s": 6478, "text": null }, { "code": null, "e": 7706, "s": 7697, "text": "Output: " }, { "code": null, "e": 7725, "s": 7708, "text": "arorakashish0911" }, { "code": null, "e": 7734, "s": 7725, "text": "sweetyty" }, { "code": null, "e": 7750, "s": 7734, "text": "Python-projects" }, { "code": null, "e": 7765, "s": 7750, "text": "python-utility" }, { "code": null, "e": 7772, "s": 7765, "text": "Python" }, { "code": null, "e": 7870, "s": 7772, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7902, "s": 7870, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 7929, "s": 7902, "text": "Python Classes and Objects" }, { "code": null, "e": 7950, "s": 7929, "text": "Python OOPs Concepts" }, { "code": null, "e": 7973, "s": 7950, "text": "Introduction To PYTHON" }, { "code": null, "e": 8029, "s": 7973, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 8060, "s": 8029, "text": "Python | os.path.join() method" }, { "code": null, "e": 8102, "s": 8060, "text": "Check if element exists in list in Python" }, { "code": null, "e": 8144, "s": 8102, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 8183, "s": 8144, "text": "Python | Get unique values from a list" } ]
How to set full-screen iframe with height 100% in JavaScript ?
31 Oct, 2019 Given an HTML document containing an <iframe> element and the task is to change the height of the <iframe> element to 100% with the help of JavaScript. There are two methods to change the height of the iframe which are discussed below: Method 1: This method uses id attribute of iframe with height property to change the height of <iframe> element. JavaScript code is written within the <script> tag. <html> <head> <title> How to change the height of an iframe to 100% with JavaScript? </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <h3> How to change the height of a <iframe id="iframe" width="100%" height="40%" src="https://www.youtube.com/embed/hjGD08xfg9c" frameborder="0" allowfullscreen> </iframe> to 100% with JavaScript? </h3> <br><br> <button onclick="changeHeight()"> Click to change </button> <script> // JavaScript code to change the // height to 100% of <iframe> function changeHeight() { var x = document.getElementById('iframe'); x.style.height = "100%"; } </script></body> </html> Output: Before clicking the button: After clicking the button: Method 2: This method uses the id attribute of the iframe with window.innerHeight property to change the height of <iframe> element. JavaScript code is written within the <script> tag. <html> <head> <title> How to change the height of an iframe to 100% with JavaScript? </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <h3> How to change the height of a <iframe id="iframe" width="100%" src= "https://www.youtube.com/embed/hjGD08xfg9c" frameborder="0" ></iframe> to 100% with JavaScript? </h3> <br><br> <button onclick="changeHeight()"> Click to change </button> <script> // JavaScript code to change the // height to 100% of <iframe> function changeHeight() { var x = document.getElementById('iframe'); x.style.height = window.innerHeight; } </script></body> </html> Output: Before clicking the button: After clicking the button: JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array How to append HTML code to a div using JavaScript ? Difference Between PUT and PATCH Request Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Oct, 2019" }, { "code": null, "e": 264, "s": 28, "text": "Given an HTML document containing an <iframe> element and the task is to change the height of the <iframe> element to 100% with the help of JavaScript. There are two methods to change the height of the iframe which are discussed below:" }, { "code": null, "e": 429, "s": 264, "text": "Method 1: This method uses id attribute of iframe with height property to change the height of <iframe> element. JavaScript code is written within the <script> tag." }, { "code": "<html> <head> <title> How to change the height of an iframe to 100% with JavaScript? </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h3> How to change the height of a <iframe id=\"iframe\" width=\"100%\" height=\"40%\" src=\"https://www.youtube.com/embed/hjGD08xfg9c\" frameborder=\"0\" allowfullscreen> </iframe> to 100% with JavaScript? </h3> <br><br> <button onclick=\"changeHeight()\"> Click to change </button> <script> // JavaScript code to change the // height to 100% of <iframe> function changeHeight() { var x = document.getElementById('iframe'); x.style.height = \"100%\"; } </script></body> </html>", "e": 1247, "s": 429, "text": null }, { "code": null, "e": 1255, "s": 1247, "text": "Output:" }, { "code": null, "e": 1283, "s": 1255, "text": "Before clicking the button:" }, { "code": null, "e": 1310, "s": 1283, "text": "After clicking the button:" }, { "code": null, "e": 1495, "s": 1310, "text": "Method 2: This method uses the id attribute of the iframe with window.innerHeight property to change the height of <iframe> element. JavaScript code is written within the <script> tag." }, { "code": "<html> <head> <title> How to change the height of an iframe to 100% with JavaScript? </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h3> How to change the height of a <iframe id=\"iframe\" width=\"100%\" src= \"https://www.youtube.com/embed/hjGD08xfg9c\" frameborder=\"0\" ></iframe> to 100% with JavaScript? </h3> <br><br> <button onclick=\"changeHeight()\"> Click to change </button> <script> // JavaScript code to change the // height to 100% of <iframe> function changeHeight() { var x = document.getElementById('iframe'); x.style.height = window.innerHeight; } </script></body> </html>", "e": 2300, "s": 1495, "text": null }, { "code": null, "e": 2308, "s": 2300, "text": "Output:" }, { "code": null, "e": 2336, "s": 2308, "text": "Before clicking the button:" }, { "code": null, "e": 2363, "s": 2336, "text": "After clicking the button:" }, { "code": null, "e": 2379, "s": 2363, "text": "JavaScript-Misc" }, { "code": null, "e": 2386, "s": 2379, "text": "Picked" }, { "code": null, "e": 2397, "s": 2386, "text": "JavaScript" }, { "code": null, "e": 2414, "s": 2397, "text": "Web Technologies" }, { "code": null, "e": 2441, "s": 2414, "text": "Web technologies Questions" }, { "code": null, "e": 2539, "s": 2441, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2600, "s": 2539, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2672, "s": 2600, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2712, "s": 2672, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2764, "s": 2712, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 2805, "s": 2764, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2838, "s": 2805, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2899, "s": 2838, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2949, "s": 2899, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2992, "s": 2949, "text": "How to fetch data from an API in ReactJS ?" } ]
Simple Chat Room using Python
19 Feb, 2022 This article demonstrates – How to set up a simple Chat Room server and allow multiple clients to connect to it using a client-side script. The code uses the concept of sockets and threading. Sockets can be thought of as endpoints in a communication channel that is bi-directional and establishes communication between a server and one or more clients. Here, we set up a socket on each end and allow a client to interact with other clients via the server. The socket on the server side associates itself with some hardware port on the server-side. Any client that has a socket associated with the same port can communicate with the server socket. A thread is a sub-process that runs a set of commands individually of any other thread. So, every time a user connects to the server, a separate thread is created for that user, and communication from the server to the client takes place along individual threads based on socket objects created for the sake of the identity of each client. We will require two scripts to establish this chat room. One to keep the serving running, and another that every client should run in order to connect to the server. The server-side script will attempt to establish a socket and bind it to an IP address and port specified by the user (windows users might have to make an exception for the specified port number in their firewall settings, or can rather use a port that is already open). The script will then stay open and receive connection requests and will append respective socket objects to a list to keep track of active connections. Every time a user connects, a separate thread will be created for that user. In each thread, the server awaits a message and sends that message to other users currently on the chat. If the server encounters an error while trying to receive a message from a particular thread, it will exit that thread. This server can be set up on a local area network by choosing any on the computer to be a server node, and using that computer’s private IP address as the server IP address. For example, if a local area network has a set of private IP addresses assigned ranging from 192.168.1.2 to 192.168.1.100, then any computer from these 99 nodes can act as a server, and the remaining nodes may connect to the server node by using the server’s private IP address. Care must be taken to choose a port that is currently not in usage. For example, port 22 is the default for ssh, and port 80 is the default for HTTP protocols. So these two ports preferably, shouldn’t be used or reconfigured to make them free for usage. However, if the server is meant to be accessible beyond a local network, the public IP address would be required for usage. This would require port forwarding in cases where a node from a local network (node that isn’t the router) wishes to host the server. In this case, we would require any requests that come to the public IP addresses to be re-routed towards our private IP address in our local network, and would hence require port forwarding. For more reading on port forwarding: linkTo run the script, simply download it from the GitHub link specified at the bottom of the post, and save it at a convenient location on your computer. /* Both the server and client script can then be run from the Command prompt (in Windows) or from bash Terminal (Linux users) by simply typing "python chat_server.py " or "python client.py ". For example, */ python chat_server.py 192.168.55.13 8081 python client.py 192.168.55.13 8081 Below is the Server side script that must be run at all times to keep the chatroom running. Python3 # Python program to implement server side of chat room.import socketimport selectimport sys'''Replace "thread" with "_thread" for python 3'''from thread import * """The first argument AF_INET is the address domain of thesocket. This is used when we have an Internet Domain withany two hosts The second argument is the type of socket.SOCK_STREAM means that data or characters are read ina continuous flow."""server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # checks whether sufficient arguments have been providedif len(sys.argv) != 3: print ("Correct usage: script, IP address, port number") exit() # takes the first argument from command prompt as IP addressIP_address = str(sys.argv[1]) # takes second argument from command prompt as port numberPort = int(sys.argv[2]) """binds the server to an entered IP address and at thespecified port number.The client must be aware of these parameters"""server.bind((IP_address, Port)) """listens for 100 active connections. This number can beincreased as per convenience."""server.listen(100) list_of_clients = [] def clientthread(conn, addr): # sends a message to the client whose user object is conn conn.send("Welcome to this chatroom!") while True: try: message = conn.recv(2048) if message: """prints the message and address of the user who just sent the message on the server terminal""" print ("<" + addr[0] + "> " + message) # Calls broadcast function to send message to all message_to_send = "<" + addr[0] + "> " + message broadcast(message_to_send, conn) else: """message may have no content if the connection is broken, in this case we remove the connection""" remove(conn) except: continue """Using the below function, we broadcast the message to allclients who's object is not the same as the one sendingthe message """def broadcast(message, connection): for clients in list_of_clients: if clients!=connection: try: clients.send(message) except: clients.close() # if the link is broken, we remove the client remove(clients) """The following function simply removes the objectfrom the list that was created at the beginning ofthe program"""def remove(connection): if connection in list_of_clients: list_of_clients.remove(connection) while True: """Accepts a connection request and stores two parameters, conn which is a socket object for that user, and addr which contains the IP address of the client that just connected""" conn, addr = server.accept() """Maintains a list of clients for ease of broadcasting a message to all available people in the chatroom""" list_of_clients.append(conn) # prints the address of the user that just connected print (addr[0] + " connected") # creates and individual thread for every user # that connects start_new_thread(clientthread,(conn,addr)) conn.close()server.close() The client-side script will simply attempt to access the server socket created at the specified IP address and port. Once it connects, it will continuously check as to whether the input comes from the server or from the client, and accordingly redirects output. If the input is from the server, it displays the message on the terminal. If the input is from the user, it sends the message that the user enters to the server for it to be broadcasted to other users.This is the client-side script, that each user must use in order to connect to the server. Python3 # Python program to implement client side of chat room.import socketimport selectimport sys server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)if len(sys.argv) != 3: print ("Correct usage: script, IP address, port number") exit()IP_address = str(sys.argv[1])Port = int(sys.argv[2])server.connect((IP_address, Port)) while True: # maintains a list of possible input streams sockets_list = [sys.stdin, server] """ There are two possible input situations. Either the user wants to give manual input to send to other people, or the server is sending a message to be printed on the screen. Select returns from sockets_list, the stream that is reader for input. So for example, if the server wants to send a message, then the if condition will hold true below.If the user wants to send a message, the else condition will evaluate as true""" read_sockets,write_socket, error_socket = select.select(sockets_list,[],[]) for socks in read_sockets: if socks == server: message = socks.recv(2048) print (message) else: message = sys.stdin.readline() server.send(message) sys.stdout.write("<You>") sys.stdout.write(message) sys.stdout.flush()server.close() Output: In the picture given below, a server has been initialized on the left side of the terminal and a client script on the right side of the terminal. (Splitting of terminal done using tmux, β€˜sudo apt-get install tmux’). For initialization purposes, you can see that whenever a message is sent by a user, the message along with IP address is shown on the server-side. The below picture has a basic conversation between two people on the same server. Multiple clients can connect to the server in the same way! Link to download script: linkThis article is contributed by Deepak Srivatsav. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. pall58183 3uus57khclp777r0o7kfeoll3qw0ozg3wpchiceo Computer Networks Project Python Technical Scripter Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GSM in Wireless Communication Differences between IPv4 and IPv6 Secure Socket Layer (SSL) Wireless Application Protocol Mobile Internet Protocol (or Mobile IP) SDE SHEET - A Complete Guide for SDE Preparation Implementing Web Scraping in Python with BeautifulSoup Working with zip files in Python XML parsing in Python Python | Simple GUI calculator using Tkinter
[ { "code": null, "e": 54, "s": 26, "text": "\n19 Feb, 2022" }, { "code": null, "e": 248, "s": 54, "text": "This article demonstrates – How to set up a simple Chat Room server and allow multiple clients to connect to it using a client-side script. The code uses the concept of sockets and threading. " }, { "code": null, "e": 705, "s": 248, "text": "Sockets can be thought of as endpoints in a communication channel that is bi-directional and establishes communication between a server and one or more clients. Here, we set up a socket on each end and allow a client to interact with other clients via the server. The socket on the server side associates itself with some hardware port on the server-side. Any client that has a socket associated with the same port can communicate with the server socket. " }, { "code": null, "e": 1213, "s": 705, "text": "A thread is a sub-process that runs a set of commands individually of any other thread. So, every time a user connects to the server, a separate thread is created for that user, and communication from the server to the client takes place along individual threads based on socket objects created for the sake of the identity of each client. We will require two scripts to establish this chat room. One to keep the serving running, and another that every client should run in order to connect to the server. " }, { "code": null, "e": 1940, "s": 1213, "text": "The server-side script will attempt to establish a socket and bind it to an IP address and port specified by the user (windows users might have to make an exception for the specified port number in their firewall settings, or can rather use a port that is already open). The script will then stay open and receive connection requests and will append respective socket objects to a list to keep track of active connections. Every time a user connects, a separate thread will be created for that user. In each thread, the server awaits a message and sends that message to other users currently on the chat. If the server encounters an error while trying to receive a message from a particular thread, it will exit that thread. " }, { "code": null, "e": 3289, "s": 1940, "text": "This server can be set up on a local area network by choosing any on the computer to be a server node, and using that computer’s private IP address as the server IP address. For example, if a local area network has a set of private IP addresses assigned ranging from 192.168.1.2 to 192.168.1.100, then any computer from these 99 nodes can act as a server, and the remaining nodes may connect to the server node by using the server’s private IP address. Care must be taken to choose a port that is currently not in usage. For example, port 22 is the default for ssh, and port 80 is the default for HTTP protocols. So these two ports preferably, shouldn’t be used or reconfigured to make them free for usage. However, if the server is meant to be accessible beyond a local network, the public IP address would be required for usage. This would require port forwarding in cases where a node from a local network (node that isn’t the router) wishes to host the server. In this case, we would require any requests that come to the public IP addresses to be re-routed towards our private IP address in our local network, and would hence require port forwarding. For more reading on port forwarding: linkTo run the script, simply download it from the GitHub link specified at the bottom of the post, and save it at a convenient location on your computer. " }, { "code": null, "e": 3591, "s": 3289, "text": "/* Both the server and client script can then be run\n from the Command prompt (in Windows) or from bash \n Terminal (Linux users) by simply typing \n \"python chat_server.py \" or \"python client.py \". \n For example, */\npython chat_server.py 192.168.55.13 8081\npython client.py 192.168.55.13 8081" }, { "code": null, "e": 3683, "s": 3591, "text": "Below is the Server side script that must be run at all times to keep the chatroom running." }, { "code": null, "e": 3691, "s": 3683, "text": "Python3" }, { "code": "# Python program to implement server side of chat room.import socketimport selectimport sys'''Replace \"thread\" with \"_thread\" for python 3'''from thread import * \"\"\"The first argument AF_INET is the address domain of thesocket. This is used when we have an Internet Domain withany two hosts The second argument is the type of socket.SOCK_STREAM means that data or characters are read ina continuous flow.\"\"\"server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # checks whether sufficient arguments have been providedif len(sys.argv) != 3: print (\"Correct usage: script, IP address, port number\") exit() # takes the first argument from command prompt as IP addressIP_address = str(sys.argv[1]) # takes second argument from command prompt as port numberPort = int(sys.argv[2]) \"\"\"binds the server to an entered IP address and at thespecified port number.The client must be aware of these parameters\"\"\"server.bind((IP_address, Port)) \"\"\"listens for 100 active connections. This number can beincreased as per convenience.\"\"\"server.listen(100) list_of_clients = [] def clientthread(conn, addr): # sends a message to the client whose user object is conn conn.send(\"Welcome to this chatroom!\") while True: try: message = conn.recv(2048) if message: \"\"\"prints the message and address of the user who just sent the message on the server terminal\"\"\" print (\"<\" + addr[0] + \"> \" + message) # Calls broadcast function to send message to all message_to_send = \"<\" + addr[0] + \"> \" + message broadcast(message_to_send, conn) else: \"\"\"message may have no content if the connection is broken, in this case we remove the connection\"\"\" remove(conn) except: continue \"\"\"Using the below function, we broadcast the message to allclients who's object is not the same as the one sendingthe message \"\"\"def broadcast(message, connection): for clients in list_of_clients: if clients!=connection: try: clients.send(message) except: clients.close() # if the link is broken, we remove the client remove(clients) \"\"\"The following function simply removes the objectfrom the list that was created at the beginning ofthe program\"\"\"def remove(connection): if connection in list_of_clients: list_of_clients.remove(connection) while True: \"\"\"Accepts a connection request and stores two parameters, conn which is a socket object for that user, and addr which contains the IP address of the client that just connected\"\"\" conn, addr = server.accept() \"\"\"Maintains a list of clients for ease of broadcasting a message to all available people in the chatroom\"\"\" list_of_clients.append(conn) # prints the address of the user that just connected print (addr[0] + \" connected\") # creates and individual thread for every user # that connects start_new_thread(clientthread,(conn,addr)) conn.close()server.close()", "e": 6967, "s": 3691, "text": null }, { "code": null, "e": 7522, "s": 6967, "text": "The client-side script will simply attempt to access the server socket created at the specified IP address and port. Once it connects, it will continuously check as to whether the input comes from the server or from the client, and accordingly redirects output. If the input is from the server, it displays the message on the terminal. If the input is from the user, it sends the message that the user enters to the server for it to be broadcasted to other users.This is the client-side script, that each user must use in order to connect to the server. " }, { "code": null, "e": 7530, "s": 7522, "text": "Python3" }, { "code": "# Python program to implement client side of chat room.import socketimport selectimport sys server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)if len(sys.argv) != 3: print (\"Correct usage: script, IP address, port number\") exit()IP_address = str(sys.argv[1])Port = int(sys.argv[2])server.connect((IP_address, Port)) while True: # maintains a list of possible input streams sockets_list = [sys.stdin, server] \"\"\" There are two possible input situations. Either the user wants to give manual input to send to other people, or the server is sending a message to be printed on the screen. Select returns from sockets_list, the stream that is reader for input. So for example, if the server wants to send a message, then the if condition will hold true below.If the user wants to send a message, the else condition will evaluate as true\"\"\" read_sockets,write_socket, error_socket = select.select(sockets_list,[],[]) for socks in read_sockets: if socks == server: message = socks.recv(2048) print (message) else: message = sys.stdin.readline() server.send(message) sys.stdout.write(\"<You>\") sys.stdout.write(message) sys.stdout.flush()server.close()", "e": 8817, "s": 7530, "text": null }, { "code": null, "e": 8826, "s": 8817, "text": "Output: " }, { "code": null, "e": 9191, "s": 8826, "text": "In the picture given below, a server has been initialized on the left side of the terminal and a client script on the right side of the terminal. (Splitting of terminal done using tmux, β€˜sudo apt-get install tmux’). For initialization purposes, you can see that whenever a message is sent by a user, the message along with IP address is shown on the server-side. " }, { "code": null, "e": 9335, "s": 9191, "text": "The below picture has a basic conversation between two people on the same server. Multiple clients can connect to the server in the same way! " }, { "code": null, "e": 9793, "s": 9335, "text": "Link to download script: linkThis article is contributed by Deepak Srivatsav. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 9803, "s": 9793, "text": "pall58183" }, { "code": null, "e": 9844, "s": 9803, "text": "3uus57khclp777r0o7kfeoll3qw0ozg3wpchiceo" }, { "code": null, "e": 9862, "s": 9844, "text": "Computer Networks" }, { "code": null, "e": 9870, "s": 9862, "text": "Project" }, { "code": null, "e": 9877, "s": 9870, "text": "Python" }, { "code": null, "e": 9896, "s": 9877, "text": "Technical Scripter" }, { "code": null, "e": 9914, "s": 9896, "text": "Computer Networks" }, { "code": null, "e": 10012, "s": 9914, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10042, "s": 10012, "text": "GSM in Wireless Communication" }, { "code": null, "e": 10076, "s": 10042, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 10102, "s": 10076, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 10132, "s": 10102, "text": "Wireless Application Protocol" }, { "code": null, "e": 10172, "s": 10132, "text": "Mobile Internet Protocol (or Mobile IP)" }, { "code": null, "e": 10221, "s": 10172, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 10276, "s": 10221, "text": "Implementing Web Scraping in Python with BeautifulSoup" }, { "code": null, "e": 10309, "s": 10276, "text": "Working with zip files in Python" }, { "code": null, "e": 10331, "s": 10309, "text": "XML parsing in Python" } ]
Python String islower() method
12 Aug, 2021 Python String islower() method checks if all characters in the string are lowercase. This method returns True if all alphabets in a string are lowercase alphabets. If the string contains at least one uppercase alphabet, it returns False. Syntax: string.islower() Parameters: None Returns: True: If all the letters in the string are in lower case and False: If even one of them is in upper case. Python3 # Python3 code to demonstrate# working of islower() # initializing stringislow_str = "geeksforgeeks"not_islow = "Geeksforgeeks" # checking which string is# completely lowerprint ("Is geeksforgeeks full lower ? : " + str(islow_str.islower()))print ("Is Geeksforgeeks full lower ? : " + str(not_islow.islower())) Output: Is geeksforgeeks full lower ? : True Is Geeksforgeeks full lower ? : False This function can be used in many ways and has many practical applications. One such application is checking for lower cases, checking proper nouns, checking for correctness of sentences that requires all lower cases. Demonstrated below is a small example showing the application of islower() method. Python3 # Python3 code to demonstrate# application of islower() method # checking for proper nouns.# nouns which start with capital letter test_str = "Geeksforgeeks is most rated Computer \ Science portal and is highly recommended" # splitting stringlist_str = test_str.split() count = 0 # counting lower casesfor i in list_str: if (i.islower()): count = count + 1 # printing proper nouns countprint ("Number of proper nouns in this sentence is : " + str(len(list_str)-count)) Output: Number of proper nouns in this sentence is : 3 shubham_singh AmiyaRanjanRout python-string Python-string-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n12 Aug, 2021" }, { "code": null, "e": 292, "s": 54, "text": "Python String islower() method checks if all characters in the string are lowercase. This method returns True if all alphabets in a string are lowercase alphabets. If the string contains at least one uppercase alphabet, it returns False." }, { "code": null, "e": 301, "s": 292, "text": "Syntax: " }, { "code": null, "e": 318, "s": 301, "text": "string.islower()" }, { "code": null, "e": 331, "s": 318, "text": "Parameters: " }, { "code": null, "e": 336, "s": 331, "text": "None" }, { "code": null, "e": 346, "s": 336, "text": "Returns: " }, { "code": null, "e": 407, "s": 346, "text": "True: If all the letters in the string are in lower case and" }, { "code": null, "e": 452, "s": 407, "text": "False: If even one of them is in upper case." }, { "code": null, "e": 460, "s": 452, "text": "Python3" }, { "code": "# Python3 code to demonstrate# working of islower() # initializing stringislow_str = \"geeksforgeeks\"not_islow = \"Geeksforgeeks\" # checking which string is# completely lowerprint (\"Is geeksforgeeks full lower ? : \" + str(islow_str.islower()))print (\"Is Geeksforgeeks full lower ? : \" + str(not_islow.islower()))", "e": 771, "s": 460, "text": null }, { "code": null, "e": 780, "s": 771, "text": "Output: " }, { "code": null, "e": 855, "s": 780, "text": "Is geeksforgeeks full lower ? : True\nIs Geeksforgeeks full lower ? : False" }, { "code": null, "e": 1156, "s": 855, "text": "This function can be used in many ways and has many practical applications. One such application is checking for lower cases, checking proper nouns, checking for correctness of sentences that requires all lower cases. Demonstrated below is a small example showing the application of islower() method." }, { "code": null, "e": 1164, "s": 1156, "text": "Python3" }, { "code": "# Python3 code to demonstrate# application of islower() method # checking for proper nouns.# nouns which start with capital letter test_str = \"Geeksforgeeks is most rated Computer \\ Science portal and is highly recommended\" # splitting stringlist_str = test_str.split() count = 0 # counting lower casesfor i in list_str: if (i.islower()): count = count + 1 # printing proper nouns countprint (\"Number of proper nouns in this sentence is : \" + str(len(list_str)-count))", "e": 1681, "s": 1164, "text": null }, { "code": null, "e": 1690, "s": 1681, "text": "Output: " }, { "code": null, "e": 1737, "s": 1690, "text": "Number of proper nouns in this sentence is : 3" }, { "code": null, "e": 1751, "s": 1737, "text": "shubham_singh" }, { "code": null, "e": 1767, "s": 1751, "text": "AmiyaRanjanRout" }, { "code": null, "e": 1781, "s": 1767, "text": "python-string" }, { "code": null, "e": 1805, "s": 1781, "text": "Python-string-functions" }, { "code": null, "e": 1812, "s": 1805, "text": "Python" } ]
Changing Column Width Based on Screen Size using CSS
To change column width based on screen size, the code is as follows βˆ’ Live Demo <!DOCTYPE html> <html> <head> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .sample { width: 50%; background-color: lightblue; height: 200px; font-size: 18px; } @media only screen and (max-width: 700px) { body { margin: 0; padding: 0; } .sample { width: 100%; } } </style> </head> <body> <h1>Changing column width based on screen size</h1> <div class="sample">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Quod, maiores!</div> <h3>Resize the browser window to 700px and below to see the above div width change to 100%</h3> </body> </html> The above code will produce the following output βˆ’ On resizing the browser window to 700 px βˆ’
[ { "code": null, "e": 1257, "s": 1187, "text": "To change column width based on screen size, the code is as follows βˆ’" }, { "code": null, "e": 1268, "s": 1257, "text": " Live Demo" }, { "code": null, "e": 1897, "s": 1268, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\nbody {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n}\n.sample {\n width: 50%;\n background-color: lightblue;\n height: 200px;\n font-size: 18px;\n}\n@media only screen and (max-width: 700px) {\n body {\n margin: 0;\n padding: 0;\n }\n .sample {\n width: 100%;\n }\n}\n</style>\n</head>\n<body>\n<h1>Changing column width based on screen size</h1>\n<div class=\"sample\">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Quod, maiores!</div>\n<h3>Resize the browser window to 700px and below to see the above div width change to 100%</h3>\n</body>\n</html>" }, { "code": null, "e": 1948, "s": 1897, "text": "The above code will produce the following output βˆ’" }, { "code": null, "e": 1991, "s": 1948, "text": "On resizing the browser window to 700 px βˆ’" } ]
Statistical Functions in Excel With Examples
07 Oct, 2021 To begin with, statistical function in Excel let’s first understand what is statistics and why we need it? So, statistics is a branch of sciences that can give a property to a sample. It deals with collecting, organizing, analyzing, and presenting the data. One of the great mathematicians Karl Pearson, also the father of modern statistics quoted that, β€œstatistics is the grammar of science”. We used statistics in every industry, including business, marketing, governance, engineering, health, etc. So in short statistics a quantitative tool to understand the world in a better way. For example, the government studies the demography of his/her country before making any policy and the demography can only study with the help of statistics. We can take another example for making a movie or any campaign it is very important to understand your audience and there too we used statistics as our tool. In Excel, we have a range of statical functions, we can perform basic mead, median mode to more complex statistical distribution, and probability test. In order to understand statistical Functions we will divide them into two sets: Basic statistical FunctionIntermediate Statistical Function. Basic statistical Function Intermediate Statistical Function. Excel is the best tool to apply statistical functions. As discussed above we first discuss the basic statistical function, and then we will study intermediate statistical function. Throughout the article, we will take data and by using it we will understand the statistical function. So, let’s take random data of a book store that sells textbooks for classes 11th and 12th. Example of statistical function. These are some most common and useful functions. These include the COUNT function, COUNTA function, COUNTBLANK function, COUNTIFS function. Let’s discuss one by one: The COUNT function is used to count the number of cells containing a number. Always remember one thing that it will only count the number. Formula for COUNT function = COUNT(value1, [value2], ...) Example of statistical function. Thus, there are 7 textbooks that have a discount out of 9 books. This function will count everything, it will count the number of the cell containing any kind of information, including numbers, error values, empty text. Formula for COUNTA function = COUNT(value1, [value2], ...) Example of statistical function. So, there are a total of 9 subjects that being sold in the store COUNTBLANK function, as the term, suggest it will only count blank or empty cells. Formula for COUNTBlANK function = COUNTBLANK(range) Example of statistical function. There are 2 subjects that don’t have any discount. COUNTIFS function is the most used function in Excel. The function will work on one or more than one condition in a given range and counts the cell that meets the condition. Formula for COUNTIFS function = COUNTIFS (range1, criteria1, [range2], [criteria2], ...) Let’s discuss some intermediate statistical functions in Excel. These functions used more often by the analyst. It includes functions like AVERAGE function, MEDIAN function, MODE function, STANDARD DEVIATION function, VARIANCE function, QUARTILES function, CORRELATION function. The AVERAGE function is one of the most used intermediate functions. The function will return the arithmetic mean or an average of the cell in a given range. Formula for AVERAGE function = AVERAGE(number1, [number2], ...) Example of statistical function. So the average total revenue is Rs.144326.6667 The function will return the arithmetic mean or an average of the cell in a given range that meets the given criteria. Formula for AVERAGEIF function = AVERAGEIF(range, criteria, [average_range]) The MEDIAN function will return the central value of the data. Its syntax is similar to the AVERAGE function. Formula for MEDIAN function = MEDIAN(number1, [number2], ...) Example of statistical function. Thus, the median quantity sold is 300. The MODE function will return the most frequent value of the cell in a given range. Formula for MODE function = MODE.SNGL(number1,[number2],...) Example of statistical function. Thus, the most frequent or repetitive cost is Rs. 250. This function helps us to determine how much observed value deviated or varied from the average. This function is one of the useful functions in Excel. Formula for STANDARD DEVIATION function = STDEV.P(number1,[number2],...) Example of statistical function. Thus, Standard Deviation of total revenue =296917.8172 To understand the VARIANCE function, we first need to know what is variance? Basically, Variance will determine the degree of variation in your data set. The more data is spread it means the more is variance. Formula for VARIANCE function = VAR(number1, [number2], ...) Example of statistical function. So, the variance of Revenue= 97955766832 Quartile divides the data into 4 parts just like the median which divides the data into two equal parts. So, the Excel QUARTILES function returns the quartiles of the dataset. It can return the minimum value, first quartile, second quartile, third quartile, and max value. Let’s see the syntax : Formula for QUARTILES function = QUARTILE (array, quart) Example of statistical function. So, the first quartile = 14137.5 CORRELATION function, help to find the relationship between the two variables, this function mostly used by the analyst to study the data. The range of the CORRELATION coefficient lies between -1 to +1. Formula for CORRELATION function = CORREL(array1, array2) Example of statistical function. So, the correlation coefficient between discount and revenue of store = 0.802428894. Since it is a positive number, thus we can conclude discount is positively related to revenue. The MAX function will return the largest numeric value within a given set of data or an array. Formula for MAX function = MAX (number1, [number2], ...) The maximum quantity of textbooks is Physics,620 in numbers. The MIN function will return the smallest numeric value within a given set of data or an array. Formula for MAX function = MAX (number1, [number2], ...) The minimum number of the book available in the store =150(Sociology) The LARGE function is similar to the MAX function but the only difference is it returns the nth largest value within a given set of data or an array. Formula for LARGE function = LARGE (array, k) Let’s find the most expensive textbook using a large function, where k = 1 Example of statistical function. The most expensive textbook is Rs. 420. The SMALL function is similar to the MIN function, but the only difference is it return nth smallest value within a given set of data or an array. Formula for SMALL function = SMALL (array, k) Similarly, using the SMALL function we can find the second least expensive book. Example of statistical function. Thus, Rs. 120 is the least cost price. So these are some statistical functions of Excel. We have learned some of the most simple functions like COUNT functions to complex ones like the CORRELATION function. So far we learn, we understand how much these functions are useful for analyzing any data. You can explore more functions and learn more things of your own. sagartomar9927 Excel-functions Picked Excel Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Oct, 2021" }, { "code": null, "e": 423, "s": 28, "text": "To begin with, statistical function in Excel let’s first understand what is statistics and why we need it? So, statistics is a branch of sciences that can give a property to a sample. It deals with collecting, organizing, analyzing, and presenting the data. One of the great mathematicians Karl Pearson, also the father of modern statistics quoted that, β€œstatistics is the grammar of science”. " }, { "code": null, "e": 931, "s": 423, "text": "We used statistics in every industry, including business, marketing, governance, engineering, health, etc. So in short statistics a quantitative tool to understand the world in a better way. For example, the government studies the demography of his/her country before making any policy and the demography can only study with the help of statistics. We can take another example for making a movie or any campaign it is very important to understand your audience and there too we used statistics as our tool." }, { "code": null, "e": 1163, "s": 931, "text": "In Excel, we have a range of statical functions, we can perform basic mead, median mode to more complex statistical distribution, and probability test. In order to understand statistical Functions we will divide them into two sets:" }, { "code": null, "e": 1224, "s": 1163, "text": "Basic statistical FunctionIntermediate Statistical Function." }, { "code": null, "e": 1251, "s": 1224, "text": "Basic statistical Function" }, { "code": null, "e": 1286, "s": 1251, "text": "Intermediate Statistical Function." }, { "code": null, "e": 1570, "s": 1286, "text": "Excel is the best tool to apply statistical functions. As discussed above we first discuss the basic statistical function, and then we will study intermediate statistical function. Throughout the article, we will take data and by using it we will understand the statistical function." }, { "code": null, "e": 1662, "s": 1570, "text": "So, let’s take random data of a book store that sells textbooks for classes 11th and 12th. " }, { "code": null, "e": 1695, "s": 1662, "text": "Example of statistical function." }, { "code": null, "e": 1861, "s": 1695, "text": "These are some most common and useful functions. These include the COUNT function, COUNTA function, COUNTBLANK function, COUNTIFS function. Let’s discuss one by one:" }, { "code": null, "e": 2001, "s": 1861, "text": "The COUNT function is used to count the number of cells containing a number. Always remember one thing that it will only count the number. " }, { "code": null, "e": 2059, "s": 2001, "text": "Formula for COUNT function = COUNT(value1, [value2], ...)" }, { "code": null, "e": 2092, "s": 2059, "text": "Example of statistical function." }, { "code": null, "e": 2157, "s": 2092, "text": "Thus, there are 7 textbooks that have a discount out of 9 books." }, { "code": null, "e": 2312, "s": 2157, "text": "This function will count everything, it will count the number of the cell containing any kind of information, including numbers, error values, empty text." }, { "code": null, "e": 2371, "s": 2312, "text": "Formula for COUNTA function = COUNT(value1, [value2], ...)" }, { "code": null, "e": 2404, "s": 2371, "text": "Example of statistical function." }, { "code": null, "e": 2469, "s": 2404, "text": "So, there are a total of 9 subjects that being sold in the store" }, { "code": null, "e": 2553, "s": 2469, "text": "COUNTBLANK function, as the term, suggest it will only count blank or empty cells. " }, { "code": null, "e": 2605, "s": 2553, "text": "Formula for COUNTBlANK function = COUNTBLANK(range)" }, { "code": null, "e": 2638, "s": 2605, "text": "Example of statistical function." }, { "code": null, "e": 2689, "s": 2638, "text": "There are 2 subjects that don’t have any discount." }, { "code": null, "e": 2863, "s": 2689, "text": "COUNTIFS function is the most used function in Excel. The function will work on one or more than one condition in a given range and counts the cell that meets the condition." }, { "code": null, "e": 2952, "s": 2863, "text": "Formula for COUNTIFS function = COUNTIFS (range1, criteria1, [range2], [criteria2], ...)" }, { "code": null, "e": 3232, "s": 2952, "text": "Let’s discuss some intermediate statistical functions in Excel. These functions used more often by the analyst. It includes functions like AVERAGE function, MEDIAN function, MODE function, STANDARD DEVIATION function, VARIANCE function, QUARTILES function, CORRELATION function." }, { "code": null, "e": 3390, "s": 3232, "text": "The AVERAGE function is one of the most used intermediate functions. The function will return the arithmetic mean or an average of the cell in a given range." }, { "code": null, "e": 3454, "s": 3390, "text": "Formula for AVERAGE function = AVERAGE(number1, [number2], ...)" }, { "code": null, "e": 3487, "s": 3454, "text": "Example of statistical function." }, { "code": null, "e": 3535, "s": 3487, "text": "So the average total revenue is Rs.144326.6667" }, { "code": null, "e": 3654, "s": 3535, "text": "The function will return the arithmetic mean or an average of the cell in a given range that meets the given criteria." }, { "code": null, "e": 3731, "s": 3654, "text": "Formula for AVERAGEIF function = AVERAGEIF(range, criteria, [average_range])" }, { "code": null, "e": 3841, "s": 3731, "text": "The MEDIAN function will return the central value of the data. Its syntax is similar to the AVERAGE function." }, { "code": null, "e": 3903, "s": 3841, "text": "Formula for MEDIAN function = MEDIAN(number1, [number2], ...)" }, { "code": null, "e": 3936, "s": 3903, "text": "Example of statistical function." }, { "code": null, "e": 3975, "s": 3936, "text": "Thus, the median quantity sold is 300." }, { "code": null, "e": 4060, "s": 3975, "text": " The MODE function will return the most frequent value of the cell in a given range." }, { "code": null, "e": 4122, "s": 4060, "text": " Formula for MODE function = MODE.SNGL(number1,[number2],...)" }, { "code": null, "e": 4155, "s": 4122, "text": "Example of statistical function." }, { "code": null, "e": 4211, "s": 4155, "text": "Thus, the most frequent or repetitive cost is Rs. 250." }, { "code": null, "e": 4363, "s": 4211, "text": "This function helps us to determine how much observed value deviated or varied from the average. This function is one of the useful functions in Excel." }, { "code": null, "e": 4436, "s": 4363, "text": "Formula for STANDARD DEVIATION function = STDEV.P(number1,[number2],...)" }, { "code": null, "e": 4469, "s": 4436, "text": "Example of statistical function." }, { "code": null, "e": 4524, "s": 4469, "text": "Thus, Standard Deviation of total revenue =296917.8172" }, { "code": null, "e": 4735, "s": 4524, "text": "To understand the VARIANCE function, we first need to know what is variance? Basically, Variance will determine the degree of variation in your data set. The more data is spread it means the more is variance. " }, { "code": null, "e": 4796, "s": 4735, "text": "Formula for VARIANCE function = VAR(number1, [number2], ...)" }, { "code": null, "e": 4829, "s": 4796, "text": "Example of statistical function." }, { "code": null, "e": 4870, "s": 4829, "text": "So, the variance of Revenue= 97955766832" }, { "code": null, "e": 5166, "s": 4870, "text": "Quartile divides the data into 4 parts just like the median which divides the data into two equal parts. So, the Excel QUARTILES function returns the quartiles of the dataset. It can return the minimum value, first quartile, second quartile, third quartile, and max value. Let’s see the syntax :" }, { "code": null, "e": 5223, "s": 5166, "text": "Formula for QUARTILES function = QUARTILE (array, quart)" }, { "code": null, "e": 5256, "s": 5223, "text": "Example of statistical function." }, { "code": null, "e": 5289, "s": 5256, "text": "So, the first quartile = 14137.5" }, { "code": null, "e": 5492, "s": 5289, "text": "CORRELATION function, help to find the relationship between the two variables, this function mostly used by the analyst to study the data. The range of the CORRELATION coefficient lies between -1 to +1." }, { "code": null, "e": 5551, "s": 5492, "text": "Formula for CORRELATION function = CORREL(array1, array2)" }, { "code": null, "e": 5584, "s": 5551, "text": "Example of statistical function." }, { "code": null, "e": 5764, "s": 5584, "text": "So, the correlation coefficient between discount and revenue of store = 0.802428894. Since it is a positive number, thus we can conclude discount is positively related to revenue." }, { "code": null, "e": 5859, "s": 5764, "text": "The MAX function will return the largest numeric value within a given set of data or an array." }, { "code": null, "e": 5917, "s": 5859, "text": "Formula for MAX function = MAX (number1, [number2], ...)" }, { "code": null, "e": 5978, "s": 5917, "text": "The maximum quantity of textbooks is Physics,620 in numbers." }, { "code": null, "e": 6074, "s": 5978, "text": "The MIN function will return the smallest numeric value within a given set of data or an array." }, { "code": null, "e": 6132, "s": 6074, "text": "Formula for MAX function = MAX (number1, [number2], ...)" }, { "code": null, "e": 6202, "s": 6132, "text": "The minimum number of the book available in the store =150(Sociology)" }, { "code": null, "e": 6352, "s": 6202, "text": "The LARGE function is similar to the MAX function but the only difference is it returns the nth largest value within a given set of data or an array." }, { "code": null, "e": 6399, "s": 6352, "text": "Formula for LARGE function = LARGE (array, k)" }, { "code": null, "e": 6474, "s": 6399, "text": "Let’s find the most expensive textbook using a large function, where k = 1" }, { "code": null, "e": 6507, "s": 6474, "text": "Example of statistical function." }, { "code": null, "e": 6547, "s": 6507, "text": "The most expensive textbook is Rs. 420." }, { "code": null, "e": 6694, "s": 6547, "text": "The SMALL function is similar to the MIN function, but the only difference is it return nth smallest value within a given set of data or an array." }, { "code": null, "e": 6741, "s": 6694, "text": "Formula for SMALL function = SMALL (array, k)" }, { "code": null, "e": 6822, "s": 6741, "text": "Similarly, using the SMALL function we can find the second least expensive book." }, { "code": null, "e": 6855, "s": 6822, "text": "Example of statistical function." }, { "code": null, "e": 6894, "s": 6855, "text": "Thus, Rs. 120 is the least cost price." }, { "code": null, "e": 7219, "s": 6894, "text": "So these are some statistical functions of Excel. We have learned some of the most simple functions like COUNT functions to complex ones like the CORRELATION function. So far we learn, we understand how much these functions are useful for analyzing any data. You can explore more functions and learn more things of your own." }, { "code": null, "e": 7234, "s": 7219, "text": "sagartomar9927" }, { "code": null, "e": 7250, "s": 7234, "text": "Excel-functions" }, { "code": null, "e": 7257, "s": 7250, "text": "Picked" }, { "code": null, "e": 7263, "s": 7257, "text": "Excel" } ]
Flutter – Loading Progress Indicator Button
30 Nov, 2021 In this article, we will learn about the Loading Progress Indicator Button in Flutter. Progress Indicator informs customers and users who are using the app about the ongoing Process such as loading an app, submitting a form, or uploading a document online. As the loading gets completed successfully we get a success status. Let’s implement Loading Progress Indicator Button – Follow the below s6es to implement Loading Progress Indicator Button in Flutter: Step 1: Created a new project and then we had created a stateful widget. We had created a stateful widget because our app is not static and every time we build or run the app new activity will take place. Dart import 'package:flutter/material.dart'; void main() { runApp(const MyApp());} class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.green, ), home: const MyHomePage(), ); }} class MyHomePage extends StatefulWidget { const MyHomePage({ Key? key, }) : super(key: key); @override State<MyHomePage> createState() => _MyHomePageState();} Step 2: In this step, we have created an Appbar with background color as green and text as white in color. Then we had initialized a variable of the bool type. Dart class _MyHomePageState extends State<MyHomePage> { bool isLoading = false; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.green, title: const Text('GeeksforGeeks',style: TextStyle(color: Colors.white),), centerTitle: true, ), Step3 – In the body of our app we had created an elevated button. The elevated button is inside the container and we have given padding, width and height to our elevated button. We had also given color property to our button as well. Now as we click on this button we will see that the value of isLoading becomes true. In the button text β€œLoading...”appear with circularprogressindicator and with the help of future.delayed that loading will get stopped after 3 seconds and then the value of isLoading will be turned to false. We had used main axis alignment to center, to keep our loading button in center. As loading gets completed in 3 seconds we will see the text β€œSubmit” got displayed on the screen. Dart body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Container( padding: const EdgeInsets.only(left: 10, right: 10), width: MediaQuery.of(context).size.width, height: 60, child: ElevatedButton( style: ElevatedButton.styleFrom( primary: Colors.green ), onPressed: () { setState(() { isLoading = true; }); Future.delayed(const Duration(seconds: 3), (){ setState(() { isLoading = false; }); } ); }, child: isLoading? Row( mainAxisAlignment: MainAxisAlignment.center, // ignore: prefer_const_literals_to_create_immutables children: [ const Text('Loading...', style: TextStyle(fontSize: 20),), const SizedBox(width: 10,), const CircularProgressIndicator(color: Colors.white,), ], ) : const Text('Submit'), ) ) ], ), ), ); }} Full source code: Dart import 'package:flutter/material.dart'; void main() { runApp(const MyApp());} class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.green, ), home: const MyHomePage(), ); }} class MyHomePage extends StatefulWidget { const MyHomePage({ Key? key, }) : super(key: key); @override State<MyHomePage> createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { bool isLoading = false; @override Widget build(BuildContext context) { return Scaffold( // created an Appbar with GeeksforGeeks written on it. appBar: AppBar( backgroundColor: Colors.green, title: const Text('GeeksforGeeks',style: TextStyle(color: Colors.white),), centerTitle: true, ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Container( padding: const EdgeInsets.only(left: 10, right: 10), width: MediaQuery.of(context).size.width, height: 60, // elevated button created and given style // and decoration properties child: ElevatedButton( style: ElevatedButton.styleFrom( primary: Colors.green ), onPressed: () { setState(() { isLoading = true; }); // we had used future delayed to stop loading after // 3 seconds and show text "submit" on the screen. Future.delayed(const Duration(seconds: 3), (){ setState(() { isLoading = false; }); } ); }, child: isLoading? Row( mainAxisAlignment: MainAxisAlignment.center, // as elevated button gets clicked we will see text"Loading..." // on the screen with circular progress indicator white in color. //as loading gets stopped "Submit" will be displayed children: const [ Text('Loading...', style: TextStyle(fontSize: 20),), SizedBox(width: 10,), CircularProgressIndicator(color: Colors.white,), ], ) : const Text('Submit'), ) ) ], ), ), ); }} Output: Flutter Flutter UI-components Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Nov, 2021" }, { "code": null, "e": 115, "s": 28, "text": "In this article, we will learn about the Loading Progress Indicator Button in Flutter." }, { "code": null, "e": 353, "s": 115, "text": "Progress Indicator informs customers and users who are using the app about the ongoing Process such as loading an app, submitting a form, or uploading a document online. As the loading gets completed successfully we get a success status." }, { "code": null, "e": 407, "s": 353, "text": "Let’s implement Loading Progress Indicator Button – " }, { "code": null, "e": 488, "s": 407, "text": "Follow the below s6es to implement Loading Progress Indicator Button in Flutter:" }, { "code": null, "e": 693, "s": 488, "text": "Step 1: Created a new project and then we had created a stateful widget. We had created a stateful widget because our app is not static and every time we build or run the app new activity will take place." }, { "code": null, "e": 698, "s": 693, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() { runApp(const MyApp());} class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.green, ), home: const MyHomePage(), ); }} class MyHomePage extends StatefulWidget { const MyHomePage({ Key? key, }) : super(key: key); @override State<MyHomePage> createState() => _MyHomePageState();}", "e": 1287, "s": 698, "text": null }, { "code": null, "e": 1447, "s": 1287, "text": "Step 2: In this step, we have created an Appbar with background color as green and text as white in color. Then we had initialized a variable of the bool type." }, { "code": null, "e": 1452, "s": 1447, "text": "Dart" }, { "code": "class _MyHomePageState extends State<MyHomePage> { bool isLoading = false; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.green, title: const Text('GeeksforGeeks',style: TextStyle(color: Colors.white),), centerTitle: true, ),", "e": 1774, "s": 1452, "text": null }, { "code": null, "e": 2482, "s": 1774, "text": "Step3 – In the body of our app we had created an elevated button. The elevated button is inside the container and we have given padding, width and height to our elevated button. We had also given color property to our button as well. Now as we click on this button we will see that the value of isLoading becomes true. In the button text β€œLoading...”appear with circularprogressindicator and with the help of future.delayed that loading will get stopped after 3 seconds and then the value of isLoading will be turned to false. We had used main axis alignment to center, to keep our loading button in center. As loading gets completed in 3 seconds we will see the text β€œSubmit” got displayed on the screen." }, { "code": null, "e": 2487, "s": 2482, "text": "Dart" }, { "code": "body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Container( padding: const EdgeInsets.only(left: 10, right: 10), width: MediaQuery.of(context).size.width, height: 60, child: ElevatedButton( style: ElevatedButton.styleFrom( primary: Colors.green ), onPressed: () { setState(() { isLoading = true; }); Future.delayed(const Duration(seconds: 3), (){ setState(() { isLoading = false; }); } ); }, child: isLoading? Row( mainAxisAlignment: MainAxisAlignment.center, // ignore: prefer_const_literals_to_create_immutables children: [ const Text('Loading...', style: TextStyle(fontSize: 20),), const SizedBox(width: 10,), const CircularProgressIndicator(color: Colors.white,), ], ) : const Text('Submit'), ) ) ], ), ), ); }}", "e": 3754, "s": 2487, "text": null }, { "code": null, "e": 3772, "s": 3754, "text": "Full source code:" }, { "code": null, "e": 3777, "s": 3772, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() { runApp(const MyApp());} class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.green, ), home: const MyHomePage(), ); }} class MyHomePage extends StatefulWidget { const MyHomePage({ Key? key, }) : super(key: key); @override State<MyHomePage> createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { bool isLoading = false; @override Widget build(BuildContext context) { return Scaffold( // created an Appbar with GeeksforGeeks written on it. appBar: AppBar( backgroundColor: Colors.green, title: const Text('GeeksforGeeks',style: TextStyle(color: Colors.white),), centerTitle: true, ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Container( padding: const EdgeInsets.only(left: 10, right: 10), width: MediaQuery.of(context).size.width, height: 60, // elevated button created and given style // and decoration properties child: ElevatedButton( style: ElevatedButton.styleFrom( primary: Colors.green ), onPressed: () { setState(() { isLoading = true; }); // we had used future delayed to stop loading after // 3 seconds and show text \"submit\" on the screen. Future.delayed(const Duration(seconds: 3), (){ setState(() { isLoading = false; }); } ); }, child: isLoading? Row( mainAxisAlignment: MainAxisAlignment.center, // as elevated button gets clicked we will see text\"Loading...\" // on the screen with circular progress indicator white in color. //as loading gets stopped \"Submit\" will be displayed children: const [ Text('Loading...', style: TextStyle(fontSize: 20),), SizedBox(width: 10,), CircularProgressIndicator(color: Colors.white,), ], ) : const Text('Submit'), ) ) ], ), ), ); }}", "e": 6406, "s": 3777, "text": null }, { "code": null, "e": 6414, "s": 6406, "text": "Output:" }, { "code": null, "e": 6422, "s": 6414, "text": "Flutter" }, { "code": null, "e": 6444, "s": 6422, "text": "Flutter UI-components" }, { "code": null, "e": 6449, "s": 6444, "text": "Dart" }, { "code": null, "e": 6457, "s": 6449, "text": "Flutter" } ]
Tailwind CSS Grid Template Columns
23 Mar, 2022 This class accepts more than one value in tailwind CSS all the properties are covered as in class form. It is the alternative of CSS grid-template-columns property in CSS. It is used to set the number of columns and size of the columns of the grid, here we will do the same but for fast development of front-end. The number of columns is set by the number of values given to this class. Grid Template Columns: grid-cols-1: Each row concedes only one column. grid-cols-2: Each row concedes only two columns. grid-cols-3: Each row concedes only three columns. grid-cols-4: Each row concedes only four columns. grid-cols-5: Each row concedes only five columns. grid-cols-6: Each row concedes six columns. grid-cols-7: Each row concedes seven-columns. grid-cols-8: Each row concedes eight columns. grid-cols-9: Each row concedes nine columns. grid-cols-10: Each row concedes ten columns. grid-cols-11: Each row concedes eleven columns. grid-cols-12: Each row concedes twelve columns. grid-cols-none: Does not follow the grid-column property. Syntax: <element class="grid grid-cols-number"> Contents... </element> Example: HTML <!DOCTYPE html> <html> <head> <title>Tailwind grid-cols Class</title> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS grid-cols Class</b> <div id="main" class="grid grid-cols-3 gap-1 justify-evenly"> <div class="bg-green-700 w-26 h-12">1</div> <div class="bg-green-500 w-26 h-12">2</div> <div class="bg-green-300 w-26 h-12">3</div> <div class="bg-green-700 w-26 h-12">4</div> <div class="bg-green-500 w-26 h-12">5</div> <div class="bg-green-300 w-26 h-12">6</div> </div> </body> </html> Output: Tailwind CSS Tailwind-Grid CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Mar, 2022" }, { "code": null, "e": 416, "s": 28, "text": "This class accepts more than one value in tailwind CSS all the properties are covered as in class form. It is the alternative of CSS grid-template-columns property in CSS. It is used to set the number of columns and size of the columns of the grid, here we will do the same but for fast development of front-end. The number of columns is set by the number of values given to this class. " }, { "code": null, "e": 439, "s": 416, "text": "Grid Template Columns:" }, { "code": null, "e": 487, "s": 439, "text": "grid-cols-1: Each row concedes only one column." }, { "code": null, "e": 537, "s": 487, "text": "grid-cols-2: Each row concedes only two columns." }, { "code": null, "e": 589, "s": 537, "text": "grid-cols-3: Each row concedes only three columns." }, { "code": null, "e": 640, "s": 589, "text": "grid-cols-4: Each row concedes only four columns." }, { "code": null, "e": 691, "s": 640, "text": "grid-cols-5: Each row concedes only five columns." }, { "code": null, "e": 736, "s": 691, "text": "grid-cols-6: Each row concedes six columns." }, { "code": null, "e": 782, "s": 736, "text": "grid-cols-7: Each row concedes seven-columns." }, { "code": null, "e": 828, "s": 782, "text": "grid-cols-8: Each row concedes eight columns." }, { "code": null, "e": 873, "s": 828, "text": "grid-cols-9: Each row concedes nine columns." }, { "code": null, "e": 918, "s": 873, "text": "grid-cols-10: Each row concedes ten columns." }, { "code": null, "e": 966, "s": 918, "text": "grid-cols-11: Each row concedes eleven columns." }, { "code": null, "e": 1014, "s": 966, "text": "grid-cols-12: Each row concedes twelve columns." }, { "code": null, "e": 1072, "s": 1014, "text": "grid-cols-none: Does not follow the grid-column property." }, { "code": null, "e": 1080, "s": 1072, "text": "Syntax:" }, { "code": null, "e": 1143, "s": 1080, "text": "<element class=\"grid grid-cols-number\"> Contents... </element>" }, { "code": null, "e": 1152, "s": 1143, "text": "Example:" }, { "code": null, "e": 1157, "s": 1152, "text": "HTML" }, { "code": "<!DOCTYPE html> <html> <head> <title>Tailwind grid-cols Class</title> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS grid-cols Class</b> <div id=\"main\" class=\"grid grid-cols-3 gap-1 justify-evenly\"> <div class=\"bg-green-700 w-26 h-12\">1</div> <div class=\"bg-green-500 w-26 h-12\">2</div> <div class=\"bg-green-300 w-26 h-12\">3</div> <div class=\"bg-green-700 w-26 h-12\">4</div> <div class=\"bg-green-500 w-26 h-12\">5</div> <div class=\"bg-green-300 w-26 h-12\">6</div> </div> </body> </html>", "e": 1905, "s": 1157, "text": null }, { "code": null, "e": 1913, "s": 1905, "text": "Output:" }, { "code": null, "e": 1926, "s": 1913, "text": "Tailwind CSS" }, { "code": null, "e": 1940, "s": 1926, "text": "Tailwind-Grid" }, { "code": null, "e": 1944, "s": 1940, "text": "CSS" }, { "code": null, "e": 1961, "s": 1944, "text": "Web Technologies" }, { "code": null, "e": 2059, "s": 1961, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2107, "s": 2059, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 2169, "s": 2107, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2219, "s": 2169, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2277, "s": 2219, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 2327, "s": 2277, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 2360, "s": 2327, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2422, "s": 2360, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2483, "s": 2422, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2533, "s": 2483, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Getting Data From Microsoft Exchange Server in Java - GeeksforGeeks
04 Dec, 2020 In the software industry, many programs require information that you need to fetch from some kind of previously existing business software. In other words, you will probably come across the need to integrate with software from Microsoft, Salesforce, SAP, and other software giants. And, although it might seem intimidating, you can do it! Let me show you how. The most common way of integrating with all types of software is to use their API. The big software companies provide them exactly to make integration possible. Let’s use Microsoft Exchange as an example. Different operations that you can perform using Exchange’s API in Java are: Read e-mails.Send e-mails.Get information from the appointments on a calendar.Insert a new appointment.Edit an existing appointment.Get information from the task list.Insert a new task.Edit an existing task.Read from a public folder.Write into a public folder. Read e-mails. Send e-mails. Get information from the appointments on a calendar. Insert a new appointment. Edit an existing appointment. Get information from the task list. Insert a new task. Edit an existing task. Read from a public folder. Write into a public folder. The most traditional way to integrate with Exchange from Java used to be the Exchange Web Services (EWS). EWS SDK is a SOAP-based API.It launched as a part of Microsoft Exchange 2007.It is not easy to use, but the real problem is that, back in July 2018, Microsoft declared they would no longer do any feature updates. EWS SDK is a SOAP-based API. It launched as a part of Microsoft Exchange 2007. It is not easy to use, but the real problem is that, back in July 2018, Microsoft declared they would no longer do any feature updates. Microsoft Graph Moreover, from Oct 13, 2020, onwards, Microsoft expects everyone using Exchange Web Services for Office 365 integration to switch to Microsoft Graph. Also, on Oct 13, 2020, support for Basic Authentication in Exchange Web Services (EWS) will stop. Microsoft wants everything moved over to OAuth and Microsoft Graph. Microsoft Graph was launched back in 2015 with Office 365. It delegates calls to several Office 365 Cloud services via a single endpoint. Within Microsoft Graph, you have two options: Microsoft Graph data connect.Microsoft Graph API. Microsoft Graph data connect. Microsoft Graph API. Microsoft is precise about what you can and cannot do with their API, so it is best to check it out beforehand. You should look into Microsoft Graph data connect if (and only if) you want to work with Big data or need granular consent. If that is not the case, you want the regular API, which is the most common option. Two versions of Microsoft Graph REST API currently exist – version 1.0 and beta. You can check the beta version, but for any serious development, you should, naturally, keep to the production version 1.0. For that version, make sure you read the documentation and learn the Java SDK. There are two ways in which we can connect to an API: Microsoft Graph API.Integration Platform. Microsoft Graph API. Integration Platform. Microsoft API When you get to the part of actually using the API, you should start by getting: Microsoft Account: It can be a company or school account. To get an Application ID.Register your Application: Register your application using:The Microsoft Application Registration Portal.The Azure Active Directory Management Portal.Application ID: Once you have registered, an application ID will be created for your app and displayed on your new app’s properties page. Microsoft Account: It can be a company or school account. To get an Application ID. Register your Application: Register your application using:The Microsoft Application Registration Portal.The Azure Active Directory Management Portal. The Microsoft Application Registration Portal. The Azure Active Directory Management Portal. Application ID: Once you have registered, an application ID will be created for your app and displayed on your new app’s properties page. You should use The Azure Active Directory Management Portal for enterprise-class applications.NOTE: Microsoft Graph changes all the time. Take a look at the changelog to get an idea of the changes that have already happened (since Dec 2015). If you want to work with it, make sure to check which is the current production version of the API. Integration Platform You can think of the integration platform as a thin layer you can put between you and the API.You write your code for the integration platform, which is *much* simpler.Then it is the integration of the platform’s job to translate and β€œspeak” with the API. Unlike the API, you need to pay to use an integration platform, but you usually can start with a free trial.Example: Connect Bridge Platform You can think of the integration platform as a thin layer you can put between you and the API. You write your code for the integration platform, which is *much* simpler. Then it is the integration of the platform’s job to translate and β€œspeak” with the API. Unlike the API, you need to pay to use an integration platform, but you usually can start with a free trial. Example: Connect Bridge Platform Connect Bridge Platform: The good thing about this specific integration platform is that it ensures forward and backward compatibility. This means that you build your Java code with Connect Bridge, and then admins can upgrade to a new Exchange version, Microsoft can launch new versions of the API. And you won’t have to worry about any of that. How Integration Platform Works Connect Bridge translates SQL statements into API calls.What you put on your code is standard SQL. You write the normal SELECT, UPDATE, INSERT and DELETE statements.It works as if you are getting data to and from a relational database using JDBC.You can even use stored procedures. Connect Bridge translates SQL statements into API calls. What you put on your code is standard SQL. You write the normal SELECT, UPDATE, INSERT and DELETE statements. It works as if you are getting data to and from a relational database using JDBC. You can even use stored procedures. Note: It is all just a layer of abstraction. You are accessing the API, in fact, not Microsoft Exchange’s database. Problems With Integration Platform The problem with some integration platforms is that they only work in a specific environment, but in the particular case of Connect Bridge, that is not an issue because you can run it on: An Azure-built SaaS platform. On-premises/self-hosted (on your own virtual machines or cloud servers). In this section, we will see how we can use Connect Bridge Management Studio to integrate our Application to the API. Approach Assuming the Exchange and SharePoint instances already exist, these are the preparation steps you need to follow: 1. Have your target system login information at hand (in this case, Exchange and SharePoint). 2. Install Connect Bridge. 3. Run Connect Bridge Management Studio. Add an account for SharePoint (Accounts – Add account). For adding the account, you should select the connector CBSharePointConnector and use the credentials from point 1. Add an account for Exchange (Accounts – Add account). For adding the account, you should select the connector MGEXPlugin2010 and use the credentials from point 1. For each account, make sure you test the connection so that you know everything is OK with the credentials and parameters you used. 4. Open the New Query option and then the Connection Browser. Find the Exchange connector and expand it until you see the DefaultConnection. Right-click the DefaultConnection and choose the option Get Connection string. You will need it to pass it on to the script, so copy the JDBC connection string. 5. Open the New Query option and then the Connection Browser. Find the SharePoint connector and expand it until you see the DefaultConnection. Right-click the DefaultConnection and choose the option Get Connection string. You will need it to pass it on to the script, so copy the JDBC connection string. Example: In the below example, we have discussed a java code to integrate Microsoft Exchange and SharePoint. Java // Java Program to demonstrate// integration of Exchange and// SharePoint import java.sql.Connection;import java.sql.DriverManager;import java.sql.Statement;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException; class Program { public static void main(String[] args) throws SQLException, ClassNotFoundException { Class.forName("com.cnsconnect.mgw.jdbc.MgDriver"); // STEP 1:Create a JDBC connection // for each target server you get // the data for the connection string // from Connect Bridge String exchangeConnectionString = "jdbc:MgDriver:IMPL=CORBA;ENC=UTF8;" + "HOST=123.456.789.000;PORT=8087;" + "UID=demouser;PWD='password';" + "ACC=accountExchange;"; String sharepointConnectionString = "jdbc:MgDriver : IMPL = CORBA; ENC = UTF8;" + "HOST = 123.456.789.000; PORT = 8087;" + "UID=demouser; PWD = 'password';" + "ACC = accountSharePoint;"; Connection exchangeConn = DriverManager.getConnection( exchangeConnectionString); Connection sharepointConn = DriverManager.getConnection( sharepointConnectionString); Statement exchangeSt = exchangeConn.createStatement(); System.out.println("Connecting to Exchange..."); // STEP 2: Provide an appropriate // object like a ResultSet + // STEP 3: Fill the object with data // from the source server ResultSet exchangeRs = exchangeSt.executeQuery( "SELECT * FROM [Appointment]"); // Create a new statement for // inserting PreparedStatement // using JDBC sharepointSt = sharepointConn.prepareStatement( "INSERT INTO [Calendar] " + "([Title],[Description], [Location]," + "[StartTime], [EndTime]) " + "VALUES ( ?, ?, ?, ?, ?)"); // STEP 4: Manipulate the data or // apply a workflow rule (or both) // in this sample: check if the // appointment is private, // if not, insert it into SharePoint while (exchangeRs.next()) { Boolean isPrivate = exchangeRs.getBoolean("IsPrivate"); if (isPrivate != null & amp; & isPrivate) { System.out.println( "Skipping '" + exchangeRs.getString("Subject") + "'"); continue; } // Fill these parameters with values // for the SharePoint account sharepointSt.setString( 1, exchangeRs.getString("Subject")); sharepointSt.setString( 2, exchangeRs.getString("Body")); sharepointSt.setString( 3, exchangeRs.getString("Location")); sharepointSt.setTimestamp( 4, exchangeRs.getTimestamp("StartDate")); sharepointSt.setTimestamp( 5, exchangeRs.getTimestamp("EndDate")); System.out.println( "Inserting '" + exchangeRs.getString("Subject") + "'"); // STEP 5: Insert data into // the target server sharepointSt.execute(); } // STEP 6: Clean up and // lose the connections exchangeRs.close(); exchangeSt.close(); sharepointSt.close(); exchangeConn.close(); sharepointConn.close(); }} Output: JDBC Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n04 Dec, 2020" }, { "code": null, "e": 25585, "s": 25225, "text": "In the software industry, many programs require information that you need to fetch from some kind of previously existing business software. In other words, you will probably come across the need to integrate with software from Microsoft, Salesforce, SAP, and other software giants. And, although it might seem intimidating, you can do it! Let me show you how." }, { "code": null, "e": 25867, "s": 25585, "text": "The most common way of integrating with all types of software is to use their API. The big software companies provide them exactly to make integration possible. Let’s use Microsoft Exchange as an example. Different operations that you can perform using Exchange’s API in Java are: " }, { "code": null, "e": 26128, "s": 25867, "text": "Read e-mails.Send e-mails.Get information from the appointments on a calendar.Insert a new appointment.Edit an existing appointment.Get information from the task list.Insert a new task.Edit an existing task.Read from a public folder.Write into a public folder." }, { "code": null, "e": 26142, "s": 26128, "text": "Read e-mails." }, { "code": null, "e": 26156, "s": 26142, "text": "Send e-mails." }, { "code": null, "e": 26209, "s": 26156, "text": "Get information from the appointments on a calendar." }, { "code": null, "e": 26235, "s": 26209, "text": "Insert a new appointment." }, { "code": null, "e": 26265, "s": 26235, "text": "Edit an existing appointment." }, { "code": null, "e": 26301, "s": 26265, "text": "Get information from the task list." }, { "code": null, "e": 26320, "s": 26301, "text": "Insert a new task." }, { "code": null, "e": 26343, "s": 26320, "text": "Edit an existing task." }, { "code": null, "e": 26370, "s": 26343, "text": "Read from a public folder." }, { "code": null, "e": 26398, "s": 26370, "text": "Write into a public folder." }, { "code": null, "e": 26505, "s": 26398, "text": "The most traditional way to integrate with Exchange from Java used to be the Exchange Web Services (EWS). " }, { "code": null, "e": 26718, "s": 26505, "text": "EWS SDK is a SOAP-based API.It launched as a part of Microsoft Exchange 2007.It is not easy to use, but the real problem is that, back in July 2018, Microsoft declared they would no longer do any feature updates." }, { "code": null, "e": 26747, "s": 26718, "text": "EWS SDK is a SOAP-based API." }, { "code": null, "e": 26797, "s": 26747, "text": "It launched as a part of Microsoft Exchange 2007." }, { "code": null, "e": 26933, "s": 26797, "text": "It is not easy to use, but the real problem is that, back in July 2018, Microsoft declared they would no longer do any feature updates." }, { "code": null, "e": 26949, "s": 26933, "text": "Microsoft Graph" }, { "code": null, "e": 27198, "s": 26949, "text": "Moreover, from Oct 13, 2020, onwards, Microsoft expects everyone using Exchange Web Services for Office 365 integration to switch to Microsoft Graph. Also, on Oct 13, 2020, support for Basic Authentication in Exchange Web Services (EWS) will stop. " }, { "code": null, "e": 27451, "s": 27198, "text": "Microsoft wants everything moved over to OAuth and Microsoft Graph. Microsoft Graph was launched back in 2015 with Office 365. It delegates calls to several Office 365 Cloud services via a single endpoint. Within Microsoft Graph, you have two options: " }, { "code": null, "e": 27501, "s": 27451, "text": "Microsoft Graph data connect.Microsoft Graph API." }, { "code": null, "e": 27531, "s": 27501, "text": "Microsoft Graph data connect." }, { "code": null, "e": 27552, "s": 27531, "text": "Microsoft Graph API." }, { "code": null, "e": 27873, "s": 27552, "text": "Microsoft is precise about what you can and cannot do with their API, so it is best to check it out beforehand. You should look into Microsoft Graph data connect if (and only if) you want to work with Big data or need granular consent. If that is not the case, you want the regular API, which is the most common option. " }, { "code": null, "e": 28158, "s": 27873, "text": "Two versions of Microsoft Graph REST API currently exist – version 1.0 and beta. You can check the beta version, but for any serious development, you should, naturally, keep to the production version 1.0. For that version, make sure you read the documentation and learn the Java SDK. " }, { "code": null, "e": 28213, "s": 28158, "text": "There are two ways in which we can connect to an API: " }, { "code": null, "e": 28255, "s": 28213, "text": "Microsoft Graph API.Integration Platform." }, { "code": null, "e": 28276, "s": 28255, "text": "Microsoft Graph API." }, { "code": null, "e": 28298, "s": 28276, "text": "Integration Platform." }, { "code": null, "e": 28312, "s": 28298, "text": "Microsoft API" }, { "code": null, "e": 28393, "s": 28312, "text": "When you get to the part of actually using the API, you should start by getting:" }, { "code": null, "e": 28764, "s": 28393, "text": "Microsoft Account: It can be a company or school account. To get an Application ID.Register your Application: Register your application using:The Microsoft Application Registration Portal.The Azure Active Directory Management Portal.Application ID: Once you have registered, an application ID will be created for your app and displayed on your new app’s properties page." }, { "code": null, "e": 28848, "s": 28764, "text": "Microsoft Account: It can be a company or school account. To get an Application ID." }, { "code": null, "e": 28999, "s": 28848, "text": "Register your Application: Register your application using:The Microsoft Application Registration Portal.The Azure Active Directory Management Portal." }, { "code": null, "e": 29046, "s": 28999, "text": "The Microsoft Application Registration Portal." }, { "code": null, "e": 29092, "s": 29046, "text": "The Azure Active Directory Management Portal." }, { "code": null, "e": 29230, "s": 29092, "text": "Application ID: Once you have registered, an application ID will be created for your app and displayed on your new app’s properties page." }, { "code": null, "e": 29572, "s": 29230, "text": "You should use The Azure Active Directory Management Portal for enterprise-class applications.NOTE: Microsoft Graph changes all the time. Take a look at the changelog to get an idea of the changes that have already happened (since Dec 2015). If you want to work with it, make sure to check which is the current production version of the API." }, { "code": null, "e": 29593, "s": 29572, "text": "Integration Platform" }, { "code": null, "e": 29990, "s": 29593, "text": "You can think of the integration platform as a thin layer you can put between you and the API.You write your code for the integration platform, which is *much* simpler.Then it is the integration of the platform’s job to translate and β€œspeak” with the API. Unlike the API, you need to pay to use an integration platform, but you usually can start with a free trial.Example: Connect Bridge Platform" }, { "code": null, "e": 30085, "s": 29990, "text": "You can think of the integration platform as a thin layer you can put between you and the API." }, { "code": null, "e": 30160, "s": 30085, "text": "You write your code for the integration platform, which is *much* simpler." }, { "code": null, "e": 30357, "s": 30160, "text": "Then it is the integration of the platform’s job to translate and β€œspeak” with the API. Unlike the API, you need to pay to use an integration platform, but you usually can start with a free trial." }, { "code": null, "e": 30390, "s": 30357, "text": "Example: Connect Bridge Platform" }, { "code": null, "e": 30737, "s": 30390, "text": "Connect Bridge Platform: The good thing about this specific integration platform is that it ensures forward and backward compatibility. This means that you build your Java code with Connect Bridge, and then admins can upgrade to a new Exchange version, Microsoft can launch new versions of the API. And you won’t have to worry about any of that. " }, { "code": null, "e": 30768, "s": 30737, "text": "How Integration Platform Works" }, { "code": null, "e": 31050, "s": 30768, "text": "Connect Bridge translates SQL statements into API calls.What you put on your code is standard SQL. You write the normal SELECT, UPDATE, INSERT and DELETE statements.It works as if you are getting data to and from a relational database using JDBC.You can even use stored procedures." }, { "code": null, "e": 31107, "s": 31050, "text": "Connect Bridge translates SQL statements into API calls." }, { "code": null, "e": 31217, "s": 31107, "text": "What you put on your code is standard SQL. You write the normal SELECT, UPDATE, INSERT and DELETE statements." }, { "code": null, "e": 31299, "s": 31217, "text": "It works as if you are getting data to and from a relational database using JDBC." }, { "code": null, "e": 31335, "s": 31299, "text": "You can even use stored procedures." }, { "code": null, "e": 31451, "s": 31335, "text": "Note: It is all just a layer of abstraction. You are accessing the API, in fact, not Microsoft Exchange’s database." }, { "code": null, "e": 31486, "s": 31451, "text": "Problems With Integration Platform" }, { "code": null, "e": 31674, "s": 31486, "text": "The problem with some integration platforms is that they only work in a specific environment, but in the particular case of Connect Bridge, that is not an issue because you can run it on:" }, { "code": null, "e": 31704, "s": 31674, "text": "An Azure-built SaaS platform." }, { "code": null, "e": 31777, "s": 31704, "text": "On-premises/self-hosted (on your own virtual machines or cloud servers)." }, { "code": null, "e": 31895, "s": 31777, "text": "In this section, we will see how we can use Connect Bridge Management Studio to integrate our Application to the API." }, { "code": null, "e": 31904, "s": 31895, "text": "Approach" }, { "code": null, "e": 32018, "s": 31904, "text": "Assuming the Exchange and SharePoint instances already exist, these are the preparation steps you need to follow:" }, { "code": null, "e": 32112, "s": 32018, "text": "1. Have your target system login information at hand (in this case, Exchange and SharePoint)." }, { "code": null, "e": 32139, "s": 32112, "text": "2. Install Connect Bridge." }, { "code": null, "e": 32180, "s": 32139, "text": "3. Run Connect Bridge Management Studio." }, { "code": null, "e": 32352, "s": 32180, "text": "Add an account for SharePoint (Accounts – Add account). For adding the account, you should select the connector CBSharePointConnector and use the credentials from point 1." }, { "code": null, "e": 32516, "s": 32352, "text": "Add an account for Exchange (Accounts – Add account). For adding the account, you should select the connector MGEXPlugin2010 and use the credentials from point 1." }, { "code": null, "e": 32648, "s": 32516, "text": "For each account, make sure you test the connection so that you know everything is OK with the credentials and parameters you used." }, { "code": null, "e": 32950, "s": 32648, "text": "4. Open the New Query option and then the Connection Browser. Find the Exchange connector and expand it until you see the DefaultConnection. Right-click the DefaultConnection and choose the option Get Connection string. You will need it to pass it on to the script, so copy the JDBC connection string." }, { "code": null, "e": 33254, "s": 32950, "text": "5. Open the New Query option and then the Connection Browser. Find the SharePoint connector and expand it until you see the DefaultConnection. Right-click the DefaultConnection and choose the option Get Connection string. You will need it to pass it on to the script, so copy the JDBC connection string." }, { "code": null, "e": 33363, "s": 33254, "text": "Example: In the below example, we have discussed a java code to integrate Microsoft Exchange and SharePoint." }, { "code": null, "e": 33368, "s": 33363, "text": "Java" }, { "code": "// Java Program to demonstrate// integration of Exchange and// SharePoint import java.sql.Connection;import java.sql.DriverManager;import java.sql.Statement;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException; class Program { public static void main(String[] args) throws SQLException, ClassNotFoundException { Class.forName(\"com.cnsconnect.mgw.jdbc.MgDriver\"); // STEP 1:Create a JDBC connection // for each target server you get // the data for the connection string // from Connect Bridge String exchangeConnectionString = \"jdbc:MgDriver:IMPL=CORBA;ENC=UTF8;\" + \"HOST=123.456.789.000;PORT=8087;\" + \"UID=demouser;PWD='password';\" + \"ACC=accountExchange;\"; String sharepointConnectionString = \"jdbc:MgDriver : IMPL = CORBA; ENC = UTF8;\" + \"HOST = 123.456.789.000; PORT = 8087;\" + \"UID=demouser; PWD = 'password';\" + \"ACC = accountSharePoint;\"; Connection exchangeConn = DriverManager.getConnection( exchangeConnectionString); Connection sharepointConn = DriverManager.getConnection( sharepointConnectionString); Statement exchangeSt = exchangeConn.createStatement(); System.out.println(\"Connecting to Exchange...\"); // STEP 2: Provide an appropriate // object like a ResultSet + // STEP 3: Fill the object with data // from the source server ResultSet exchangeRs = exchangeSt.executeQuery( \"SELECT * FROM [Appointment]\"); // Create a new statement for // inserting PreparedStatement // using JDBC sharepointSt = sharepointConn.prepareStatement( \"INSERT INTO [Calendar] \" + \"([Title],[Description], [Location],\" + \"[StartTime], [EndTime]) \" + \"VALUES ( ?, ?, ?, ?, ?)\"); // STEP 4: Manipulate the data or // apply a workflow rule (or both) // in this sample: check if the // appointment is private, // if not, insert it into SharePoint while (exchangeRs.next()) { Boolean isPrivate = exchangeRs.getBoolean(\"IsPrivate\"); if (isPrivate != null & amp; & isPrivate) { System.out.println( \"Skipping '\" + exchangeRs.getString(\"Subject\") + \"'\"); continue; } // Fill these parameters with values // for the SharePoint account sharepointSt.setString( 1, exchangeRs.getString(\"Subject\")); sharepointSt.setString( 2, exchangeRs.getString(\"Body\")); sharepointSt.setString( 3, exchangeRs.getString(\"Location\")); sharepointSt.setTimestamp( 4, exchangeRs.getTimestamp(\"StartDate\")); sharepointSt.setTimestamp( 5, exchangeRs.getTimestamp(\"EndDate\")); System.out.println( \"Inserting '\" + exchangeRs.getString(\"Subject\") + \"'\"); // STEP 5: Insert data into // the target server sharepointSt.execute(); } // STEP 6: Clean up and // lose the connections exchangeRs.close(); exchangeSt.close(); sharepointSt.close(); exchangeConn.close(); sharepointConn.close(); }}", "e": 36906, "s": 33368, "text": null }, { "code": null, "e": 36914, "s": 36906, "text": "Output:" }, { "code": null, "e": 36919, "s": 36914, "text": "JDBC" }, { "code": null, "e": 36924, "s": 36919, "text": "Java" }, { "code": null, "e": 36929, "s": 36924, "text": "Java" }, { "code": null, "e": 37027, "s": 36929, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37042, "s": 37027, "text": "Stream In Java" }, { "code": null, "e": 37063, "s": 37042, "text": "Constructors in Java" }, { "code": null, "e": 37082, "s": 37063, "text": "Exceptions in Java" }, { "code": null, "e": 37112, "s": 37082, "text": "Functional Interfaces in Java" }, { "code": null, "e": 37158, "s": 37112, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 37175, "s": 37158, "text": "Generics in Java" }, { "code": null, "e": 37196, "s": 37175, "text": "Introduction to Java" }, { "code": null, "e": 37239, "s": 37196, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 37275, "s": 37239, "text": "Internal Working of HashMap in Java" } ]
C# | Dictionary.Count Property - GeeksforGeeks
01 Feb, 2019 This property is used to get the number of key/value pairs contained in the Dictionary. Syntax: public int Count { get; } Return Value : The number of key/value pairs contained in the Dictionary. Below are the programs to illustrate the use of above-discussed property: Example 1: // C# code to count the number of // key/value pairs in Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary of // strings, with string keys. Dictionary<string, string> myDict = new Dictionary<string, string>(); // Adding key/value pairs in myDict myDict.Add("Australia", "Canberra"); myDict.Add("Belgium", "Brussels"); myDict.Add("Netherlands", "Amsterdam"); myDict.Add("China", "Beijing"); myDict.Add("Russia", "Moscow"); myDict.Add("India", "New Delhi"); // To get count of key/value // pairs in myDict Console.WriteLine("Total key/value pairs"+ " in myDict are : " + myDict.Count); }} Total key/value pairs in myDict are : 6 Example 2: // C# code to count the number of // key/value pairs in Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary of // strings, with string keys. Dictionary<int, string> myDict = new Dictionary<int, string>(); // Adding key/value pairs in myDict myDict.Add(1, "C"); myDict.Add(2, "C++"); myDict.Add(3, "Java"); myDict.Add(4, "Python"); myDict.Add(5, "C#"); myDict.Add(6, "HTML"); // To get count of key/value pairs in myDict Console.WriteLine("Total key/value pairs"+ " in myDict are : " + myDict.Count); }} Total key/value pairs in myDict are : 6 Note: Retrieving the value of this property is an O(1) operation. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.count?view=netframework-4.7.2#System_Collections_Generic_Dictionary_2_Count CSharp Dictionary Class CSharp-Generic-Namespace C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Top 50 C# Interview Questions & Answers Switch Statement in C# Convert String to Character Array in C# C# | How to insert an element in an Array? Linked List Implementation in C#
[ { "code": null, "e": 25547, "s": 25519, "text": "\n01 Feb, 2019" }, { "code": null, "e": 25635, "s": 25547, "text": "This property is used to get the number of key/value pairs contained in the Dictionary." }, { "code": null, "e": 25643, "s": 25635, "text": "Syntax:" }, { "code": null, "e": 25670, "s": 25643, "text": "public int Count { get; }\n" }, { "code": null, "e": 25744, "s": 25670, "text": "Return Value : The number of key/value pairs contained in the Dictionary." }, { "code": null, "e": 25818, "s": 25744, "text": "Below are the programs to illustrate the use of above-discussed property:" }, { "code": null, "e": 25829, "s": 25818, "text": "Example 1:" }, { "code": "// C# code to count the number of // key/value pairs in Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary of // strings, with string keys. Dictionary<string, string> myDict = new Dictionary<string, string>(); // Adding key/value pairs in myDict myDict.Add(\"Australia\", \"Canberra\"); myDict.Add(\"Belgium\", \"Brussels\"); myDict.Add(\"Netherlands\", \"Amsterdam\"); myDict.Add(\"China\", \"Beijing\"); myDict.Add(\"Russia\", \"Moscow\"); myDict.Add(\"India\", \"New Delhi\"); // To get count of key/value // pairs in myDict Console.WriteLine(\"Total key/value pairs\"+ \" in myDict are : \" + myDict.Count); }}", "e": 26641, "s": 25829, "text": null }, { "code": null, "e": 26682, "s": 26641, "text": "Total key/value pairs in myDict are : 6\n" }, { "code": null, "e": 26693, "s": 26682, "text": "Example 2:" }, { "code": "// C# code to count the number of // key/value pairs in Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary of // strings, with string keys. Dictionary<int, string> myDict = new Dictionary<int, string>(); // Adding key/value pairs in myDict myDict.Add(1, \"C\"); myDict.Add(2, \"C++\"); myDict.Add(3, \"Java\"); myDict.Add(4, \"Python\"); myDict.Add(5, \"C#\"); myDict.Add(6, \"HTML\"); // To get count of key/value pairs in myDict Console.WriteLine(\"Total key/value pairs\"+ \" in myDict are : \" + myDict.Count); }}", "e": 27413, "s": 26693, "text": null }, { "code": null, "e": 27454, "s": 27413, "text": "Total key/value pairs in myDict are : 6\n" }, { "code": null, "e": 27520, "s": 27454, "text": "Note: Retrieving the value of this property is an O(1) operation." }, { "code": null, "e": 27531, "s": 27520, "text": "Reference:" }, { "code": null, "e": 27691, "s": 27531, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.count?view=netframework-4.7.2#System_Collections_Generic_Dictionary_2_Count" }, { "code": null, "e": 27715, "s": 27691, "text": "CSharp Dictionary Class" }, { "code": null, "e": 27740, "s": 27715, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 27743, "s": 27740, "text": "C#" }, { "code": null, "e": 27841, "s": 27743, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27864, "s": 27841, "text": "Extension Method in C#" }, { "code": null, "e": 27892, "s": 27864, "text": "HashSet in C# with Examples" }, { "code": null, "e": 27909, "s": 27892, "text": "C# | Inheritance" }, { "code": null, "e": 27931, "s": 27909, "text": "Partial Classes in C#" }, { "code": null, "e": 27960, "s": 27931, "text": "C# | Generics - Introduction" }, { "code": null, "e": 28000, "s": 27960, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 28023, "s": 28000, "text": "Switch Statement in C#" }, { "code": null, "e": 28063, "s": 28023, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 28106, "s": 28063, "text": "C# | How to insert an element in an Array?" } ]
Angular PrimeNG Rating Component - GeeksforGeeks
26 Aug, 2021 Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Rating component in Angular PrimeNG. Let’s learn about the properties, events & styling along with their syntaxes that will be used in the code. Rating component: It is used to represents the rating given by the user. Properties: stars: It indicates the number of stars to be shown. It is of number datatype, the default value is 5. cancel: It shows a cancel icon that resets all the stars values. It is of the boolean data type, the default value is true. disabled: When it is set to be true, the rating should be disabled. It is of the boolean data type, the default value is false. readonly: We cannot change the value of the component. It is of the boolean data type, the default value is false. iconOnClass: It is used to set the class of the β€˜on’ icon. It is of string data type, the default value is pi pi-star. iconOffClass: It is used to set the class of the β€˜off’ icon. It is of string data type, the default value is pi pi-star. iconCancelClass: It is used to set the class of the β€˜cancel’ icon. It is of string data type, the default value is pi pi-ban. iconOnStyle: It is used to set the inline style of the β€˜on’ icon. It is of object data type, the default value is null. iconOffStyle: It is used to set the inline style of the β€˜off’ icon. It is of object data type, the default value is null. iconCancelStyle: It is used to set the inline style of the β€˜cancel’ icon. It is of object data type, the default value is null. Events: onRate: It is a callback that is fired on rate change. onCancel: It is a callback that is fired when the value is removed. Styling: p-rating: It is a container element. p-rating-star: It is a star element. p-rating-star-on: It shows the selected star element. p-rating-cancel: It shows the cancel icon. Creating Angular application & module installation: Step 1: Create an Angular application using the following command. ng new appname Step 2: After creating your project folder i.e. appname, move to it using the following command. cd appname Step 3: Install PrimeNG in your given directory. npm install primeng --save npm install primeicons --save Project Structure: It will look like the following: Example 1: This is the basic example that shows how to use the Rating component. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG Rating component</h5><p-rating [cancel]="false"></p-rating> app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent {} app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { FormsModule } from "@angular/forms";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { RatingModule } from "primeng/rating"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, RatingModule, FormsModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} Output: Example 2: In this example, we will know how to use the cancel property in the Rating component. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG Rating component</h5> <p-rating cancel='true'></p-rating> app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent {} app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { FormsModule } from "@angular/forms";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { RatingModule } from "primeng/rating"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, RatingModule, FormsModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} Output: Example 3: In this example, we will know how to use the readOnly property in the Rating component. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG Rating component</h5><p-rating readonly="true" cancel="true"></p-rating> app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent {} app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { FormsModule } from "@angular/forms";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { RatingModule } from "primeng/rating"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, RatingModule, FormsModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} Output: Reference: https://primefaces.org/primeng/showcase/#/rating Angular-PrimeNG AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? Angular PrimeNG Messages Component Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 26354, "s": 26326, "text": "\n26 Aug, 2021" }, { "code": null, "e": 26745, "s": 26354, "text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Rating component in Angular PrimeNG. Let’s learn about the properties, events & styling along with their syntaxes that will be used in the code. " }, { "code": null, "e": 26818, "s": 26745, "text": "Rating component: It is used to represents the rating given by the user." }, { "code": null, "e": 26830, "s": 26818, "text": "Properties:" }, { "code": null, "e": 26933, "s": 26830, "text": "stars: It indicates the number of stars to be shown. It is of number datatype, the default value is 5." }, { "code": null, "e": 27057, "s": 26933, "text": "cancel: It shows a cancel icon that resets all the stars values. It is of the boolean data type, the default value is true." }, { "code": null, "e": 27185, "s": 27057, "text": "disabled: When it is set to be true, the rating should be disabled. It is of the boolean data type, the default value is false." }, { "code": null, "e": 27300, "s": 27185, "text": "readonly: We cannot change the value of the component. It is of the boolean data type, the default value is false." }, { "code": null, "e": 27419, "s": 27300, "text": "iconOnClass: It is used to set the class of the β€˜on’ icon. It is of string data type, the default value is pi pi-star." }, { "code": null, "e": 27540, "s": 27419, "text": "iconOffClass: It is used to set the class of the β€˜off’ icon. It is of string data type, the default value is pi pi-star." }, { "code": null, "e": 27666, "s": 27540, "text": "iconCancelClass: It is used to set the class of the β€˜cancel’ icon. It is of string data type, the default value is pi pi-ban." }, { "code": null, "e": 27786, "s": 27666, "text": "iconOnStyle: It is used to set the inline style of the β€˜on’ icon. It is of object data type, the default value is null." }, { "code": null, "e": 27908, "s": 27786, "text": "iconOffStyle: It is used to set the inline style of the β€˜off’ icon. It is of object data type, the default value is null." }, { "code": null, "e": 28036, "s": 27908, "text": "iconCancelStyle: It is used to set the inline style of the β€˜cancel’ icon. It is of object data type, the default value is null." }, { "code": null, "e": 28044, "s": 28036, "text": "Events:" }, { "code": null, "e": 28099, "s": 28044, "text": "onRate: It is a callback that is fired on rate change." }, { "code": null, "e": 28167, "s": 28099, "text": "onCancel: It is a callback that is fired when the value is removed." }, { "code": null, "e": 28178, "s": 28169, "text": "Styling:" }, { "code": null, "e": 28215, "s": 28178, "text": "p-rating: It is a container element." }, { "code": null, "e": 28252, "s": 28215, "text": "p-rating-star: It is a star element." }, { "code": null, "e": 28306, "s": 28252, "text": "p-rating-star-on: It shows the selected star element." }, { "code": null, "e": 28349, "s": 28306, "text": "p-rating-cancel: It shows the cancel icon." }, { "code": null, "e": 28401, "s": 28349, "text": "Creating Angular application & module installation:" }, { "code": null, "e": 28468, "s": 28401, "text": "Step 1: Create an Angular application using the following command." }, { "code": null, "e": 28483, "s": 28468, "text": "ng new appname" }, { "code": null, "e": 28580, "s": 28483, "text": "Step 2: After creating your project folder i.e. appname, move to it using the following command." }, { "code": null, "e": 28591, "s": 28580, "text": "cd appname" }, { "code": null, "e": 28640, "s": 28591, "text": "Step 3: Install PrimeNG in your given directory." }, { "code": null, "e": 28697, "s": 28640, "text": "npm install primeng --save\nnpm install primeicons --save" }, { "code": null, "e": 28749, "s": 28697, "text": "Project Structure: It will look like the following:" }, { "code": null, "e": 28831, "s": 28749, "text": "Example 1: This is the basic example that shows how to use the Rating component. " }, { "code": null, "e": 28850, "s": 28831, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG Rating component</h5><p-rating [cancel]=\"false\"></p-rating>", "e": 28944, "s": 28850, "text": null }, { "code": null, "e": 28961, "s": 28944, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent {}", "e": 29106, "s": 28961, "text": null }, { "code": null, "e": 29122, "s": 29108, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { FormsModule } from \"@angular/forms\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { RatingModule } from \"primeng/rating\"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, RatingModule, FormsModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 29649, "s": 29122, "text": null }, { "code": null, "e": 29657, "s": 29649, "text": "Output:" }, { "code": null, "e": 29754, "s": 29657, "text": "Example 2: In this example, we will know how to use the cancel property in the Rating component." }, { "code": null, "e": 29773, "s": 29754, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG Rating component</h5> <p-rating cancel='true'></p-rating>", "e": 29865, "s": 29773, "text": null }, { "code": null, "e": 29882, "s": 29865, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent {}", "e": 30027, "s": 29882, "text": null }, { "code": null, "e": 30041, "s": 30027, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { FormsModule } from \"@angular/forms\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { RatingModule } from \"primeng/rating\"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, RatingModule, FormsModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 30568, "s": 30041, "text": null }, { "code": null, "e": 30576, "s": 30568, "text": "Output:" }, { "code": null, "e": 30675, "s": 30576, "text": "Example 3: In this example, we will know how to use the readOnly property in the Rating component." }, { "code": null, "e": 30694, "s": 30675, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG Rating component</h5><p-rating readonly=\"true\" cancel=\"true\"></p-rating>", "e": 30801, "s": 30694, "text": null }, { "code": null, "e": 30818, "s": 30801, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent {}", "e": 30963, "s": 30818, "text": null }, { "code": null, "e": 30977, "s": 30963, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { FormsModule } from \"@angular/forms\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { RatingModule } from \"primeng/rating\"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, RatingModule, FormsModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 31504, "s": 30977, "text": null }, { "code": null, "e": 31512, "s": 31504, "text": "Output:" }, { "code": null, "e": 31572, "s": 31512, "text": "Reference: https://primefaces.org/primeng/showcase/#/rating" }, { "code": null, "e": 31588, "s": 31572, "text": "Angular-PrimeNG" }, { "code": null, "e": 31598, "s": 31588, "text": "AngularJS" }, { "code": null, "e": 31615, "s": 31598, "text": "Web Technologies" }, { "code": null, "e": 31713, "s": 31615, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31748, "s": 31713, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 31783, "s": 31748, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 31807, "s": 31783, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 31860, "s": 31807, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 31895, "s": 31860, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 31935, "s": 31895, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31968, "s": 31935, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 32013, "s": 31968, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 32056, "s": 32013, "text": "How to fetch data from an API in ReactJS ?" } ]
Matplotlib.axes.Axes.fill_between() in Python - GeeksforGeeks
13 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. The Axes.fill_between() function in axes module of matplotlib library is used to fill the area between two horizontal curves. Syntax: Axes.fill_between(self, x, y1, y2=0, where=None, interpolate=False, step=None, *, data=None, **kwargs) Parameters: This method accept the following parameters that are described below: x: This parameter contains the horizontal coordinates of the data points which are used to define the curves. y1: This parameter contains the y coordinates of the data points which are used to define the first curves y2: This parameter contains the y coordinates of the data points which are used to define the second curves. It is an optional with default value of 0. where: This parameter is an optional parameter. And it is used to exclude some horizontal regions from being filled. interpolate: This parameter is also an optional parameter. And it is the linewidth of the errorbar lines with default value NONE. step: This parameter is also an optional parameter. And it is used to define if the filling should be a step function or not. Returns: This returns a PolyCollection containing the plotted polygons. Below examples illustrate the matplotlib.axes.Axes.fill_between() function in matplotlib.axes: Example-1: # Implementation of matplotlib function import numpy as npimport matplotlib.pyplot as plt x = np.arange(-5, 5, 0.01)y1 = -3 * x*x + 10 * x + 10y2 = 3 * x*x + x fig, ax = plt.subplots()ax.plot(x, y1, x, y2, color ='black')ax.fill_between(x, y1, y2, where = y2 >y1, facecolor ='green', alpha = 0.8) ax.fill_between(x, y1, y2, where = y2 <= y1, facecolor ='black', alpha = 0.8) ax.set_title('matplotlib.axes.Axes.fill_between Example1')plt.show() Output: Example-2: # Implementation of matplotlib function import numpy as npimport matplotlib.pyplot as plt x = np.arange(0.0, 2, 0.01)y1 = np.sin(2 * np.pi * x)y2 = 0.8 * np.sin(4 * np.pi * x) fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, 1, sharex = True, figsize =(6, 6)) ax1.fill_between(x, y1, facecolor ='green')ax1.set_title('Fill_Between y1 and 0') ax2.fill_between(x, y1, 1, facecolor ='green')ax2.set_title('Fill_Between y1 and 1') ax3.fill_between(x, y1, y2, facecolor ='green')ax3.set_title('Fill_Between y1 and y2')ax3.set_xlabel('x')fig.tight_layout() ax4.fill_between(x, y1, y2, where = y2 <= y1, facecolor ='green') ax4.set_title('Fill_Between y1 and y2 with condition y2 <= y1 ' )ax4.set_xlabel('x')fig.tight_layout() plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Read a file line by line in Python Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Convert integer to string in Python
[ { "code": null, "e": 26079, "s": 26051, "text": "\n13 Apr, 2020" }, { "code": null, "e": 26177, "s": 26079, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library." }, { "code": null, "e": 26379, "s": 26177, "text": "The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute." }, { "code": null, "e": 26505, "s": 26379, "text": "The Axes.fill_between() function in axes module of matplotlib library is used to fill the area between two horizontal curves." }, { "code": null, "e": 26616, "s": 26505, "text": "Syntax: Axes.fill_between(self, x, y1, y2=0, where=None, interpolate=False, step=None, *, data=None, **kwargs)" }, { "code": null, "e": 26698, "s": 26616, "text": "Parameters: This method accept the following parameters that are described below:" }, { "code": null, "e": 26808, "s": 26698, "text": "x: This parameter contains the horizontal coordinates of the data points which are used to define the curves." }, { "code": null, "e": 26915, "s": 26808, "text": "y1: This parameter contains the y coordinates of the data points which are used to define the first curves" }, { "code": null, "e": 27067, "s": 26915, "text": "y2: This parameter contains the y coordinates of the data points which are used to define the second curves. It is an optional with default value of 0." }, { "code": null, "e": 27184, "s": 27067, "text": "where: This parameter is an optional parameter. And it is used to exclude some horizontal regions from being filled." }, { "code": null, "e": 27314, "s": 27184, "text": "interpolate: This parameter is also an optional parameter. And it is the linewidth of the errorbar lines with default value NONE." }, { "code": null, "e": 27440, "s": 27314, "text": "step: This parameter is also an optional parameter. And it is used to define if the filling should be a step function or not." }, { "code": null, "e": 27512, "s": 27440, "text": "Returns: This returns a PolyCollection containing the plotted polygons." }, { "code": null, "e": 27607, "s": 27512, "text": "Below examples illustrate the matplotlib.axes.Axes.fill_between() function in matplotlib.axes:" }, { "code": null, "e": 27618, "s": 27607, "text": "Example-1:" }, { "code": "# Implementation of matplotlib function import numpy as npimport matplotlib.pyplot as plt x = np.arange(-5, 5, 0.01)y1 = -3 * x*x + 10 * x + 10y2 = 3 * x*x + x fig, ax = plt.subplots()ax.plot(x, y1, x, y2, color ='black')ax.fill_between(x, y1, y2, where = y2 >y1, facecolor ='green', alpha = 0.8) ax.fill_between(x, y1, y2, where = y2 <= y1, facecolor ='black', alpha = 0.8) ax.set_title('matplotlib.axes.Axes.fill_between Example1')plt.show()", "e": 28102, "s": 27618, "text": null }, { "code": null, "e": 28110, "s": 28102, "text": "Output:" }, { "code": null, "e": 28121, "s": 28110, "text": "Example-2:" }, { "code": "# Implementation of matplotlib function import numpy as npimport matplotlib.pyplot as plt x = np.arange(0.0, 2, 0.01)y1 = np.sin(2 * np.pi * x)y2 = 0.8 * np.sin(4 * np.pi * x) fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, 1, sharex = True, figsize =(6, 6)) ax1.fill_between(x, y1, facecolor ='green')ax1.set_title('Fill_Between y1 and 0') ax2.fill_between(x, y1, 1, facecolor ='green')ax2.set_title('Fill_Between y1 and 1') ax3.fill_between(x, y1, y2, facecolor ='green')ax3.set_title('Fill_Between y1 and y2')ax3.set_xlabel('x')fig.tight_layout() ax4.fill_between(x, y1, y2, where = y2 <= y1, facecolor ='green') ax4.set_title('Fill_Between y1 and y2 with condition y2 <= y1 ' )ax4.set_xlabel('x')fig.tight_layout() plt.show()", "e": 28956, "s": 28121, "text": null }, { "code": null, "e": 28964, "s": 28956, "text": "Output:" }, { "code": null, "e": 28982, "s": 28964, "text": "Python-matplotlib" }, { "code": null, "e": 28989, "s": 28982, "text": "Python" }, { "code": null, "e": 29087, "s": 28989, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29105, "s": 29087, "text": "Python Dictionary" }, { "code": null, "e": 29137, "s": 29105, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29172, "s": 29137, "text": "Read a file line by line in Python" }, { "code": null, "e": 29194, "s": 29172, "text": "Enumerate() in Python" }, { "code": null, "e": 29236, "s": 29194, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29266, "s": 29236, "text": "Iterate over a list in Python" }, { "code": null, "e": 29292, "s": 29266, "text": "Python String | replace()" }, { "code": null, "e": 29336, "s": 29292, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 29365, "s": 29336, "text": "*args and **kwargs in Python" } ]
Node.js path.extname() Method - GeeksforGeeks
13 Oct, 2021 The path.extname() method is used to get the extension portion of a file path. The extension string returned from the last occurrence of a period (.) in the path to the end of the path string. If there are no periods in the file path, then an empty string is returned. Syntax: path.extname( path ) Parameters: This method accepts single parameter path which holds the file path that would be used to extract the extension. Return Value: It returns a string with the extension portion of the path. It throws a TypeError if this parameter is not a string value. Below examples illustrate the path.extname() method in node.js: Example 1: // Node.js program to demonstrate the // path.extname() method // Import the path moduleconst path = require('path'); path1 = path.extname("hello.txt");console.log(path1) path2 = path.extname("readme.md");console.log(path2) // File with no extension// Returns empty stringpath3 = path.extname("fileDump")console.log(path3) // File with blank extension// Return only the periodpath4 = path.extname("example.")console.log(path4) path5 = path.extname("readme.md.txt")console.log(path5) // Extension name of the current scriptpath6 = path.extname(__filename)console.log(path6) Output: .txt .md . .txt .js Example 2: // Node.js program to demonstrate the // path.extname() method // Import the path moduleconst path = require('path'); // Comparing extensions from a// list of file pathspaths_array = [ "/home/user/website/index.html", "/home/user/website/style.css", "/home/user/website/bootstrap.css", "/home/user/website/main.js", "/home/user/website/contact_us.html", "/home/user/website/services.html",] paths_array.forEach(filePath => { if (path.extname(filePath) == ".html") console.log(filePath);}); Output: /home/user/website/index.html /home/user/website/contact_us.html /home/user/website/services.html Reference: https://nodejs.org/api/path.html#path_path_extname_path Node.js-Methods Node.js-path-module Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method Node.js fs.writeFile() Method How to update NPM ? Difference between promise and async await in Node.js Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 38501, "s": 38473, "text": "\n13 Oct, 2021" }, { "code": null, "e": 38770, "s": 38501, "text": "The path.extname() method is used to get the extension portion of a file path. The extension string returned from the last occurrence of a period (.) in the path to the end of the path string. If there are no periods in the file path, then an empty string is returned." }, { "code": null, "e": 38778, "s": 38770, "text": "Syntax:" }, { "code": null, "e": 38799, "s": 38778, "text": "path.extname( path )" }, { "code": null, "e": 38924, "s": 38799, "text": "Parameters: This method accepts single parameter path which holds the file path that would be used to extract the extension." }, { "code": null, "e": 39061, "s": 38924, "text": "Return Value: It returns a string with the extension portion of the path. It throws a TypeError if this parameter is not a string value." }, { "code": null, "e": 39125, "s": 39061, "text": "Below examples illustrate the path.extname() method in node.js:" }, { "code": null, "e": 39136, "s": 39125, "text": "Example 1:" }, { "code": "// Node.js program to demonstrate the // path.extname() method // Import the path moduleconst path = require('path'); path1 = path.extname(\"hello.txt\");console.log(path1) path2 = path.extname(\"readme.md\");console.log(path2) // File with no extension// Returns empty stringpath3 = path.extname(\"fileDump\")console.log(path3) // File with blank extension// Return only the periodpath4 = path.extname(\"example.\")console.log(path4) path5 = path.extname(\"readme.md.txt\")console.log(path5) // Extension name of the current scriptpath6 = path.extname(__filename)console.log(path6)", "e": 39724, "s": 39136, "text": null }, { "code": null, "e": 39732, "s": 39724, "text": "Output:" }, { "code": null, "e": 39753, "s": 39732, "text": ".txt\n.md\n\n.\n.txt\n.js" }, { "code": null, "e": 39764, "s": 39753, "text": "Example 2:" }, { "code": "// Node.js program to demonstrate the // path.extname() method // Import the path moduleconst path = require('path'); // Comparing extensions from a// list of file pathspaths_array = [ \"/home/user/website/index.html\", \"/home/user/website/style.css\", \"/home/user/website/bootstrap.css\", \"/home/user/website/main.js\", \"/home/user/website/contact_us.html\", \"/home/user/website/services.html\",] paths_array.forEach(filePath => { if (path.extname(filePath) == \".html\") console.log(filePath);});", "e": 40289, "s": 39764, "text": null }, { "code": null, "e": 40297, "s": 40289, "text": "Output:" }, { "code": null, "e": 40395, "s": 40297, "text": "/home/user/website/index.html\n/home/user/website/contact_us.html\n/home/user/website/services.html" }, { "code": null, "e": 40462, "s": 40395, "text": "Reference: https://nodejs.org/api/path.html#path_path_extname_path" }, { "code": null, "e": 40478, "s": 40462, "text": "Node.js-Methods" }, { "code": null, "e": 40498, "s": 40478, "text": "Node.js-path-module" }, { "code": null, "e": 40506, "s": 40498, "text": "Node.js" }, { "code": null, "e": 40523, "s": 40506, "text": "Web Technologies" }, { "code": null, "e": 40621, "s": 40523, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40669, "s": 40621, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 40702, "s": 40669, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 40732, "s": 40702, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 40752, "s": 40732, "text": "How to update NPM ?" }, { "code": null, "e": 40806, "s": 40752, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 40846, "s": 40806, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 40891, "s": 40846, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 40934, "s": 40891, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 40984, "s": 40934, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
ReactJS Blueprint Toast Component - GeeksforGeeks
08 Apr, 2022 BlueprintJS is a React-based UI toolkit for the web. This library is very optimized and popular for building interfaces that are complex data-dense for desktop applications. Toast Component provides a way for users to the user to show an ephemeral message as an overlay. We can use the following approach in ReactJS to use the ReactJS Blueprint Toast Component. Toast Props: action: It is an action that is rendered as a minimal AnchorButton. className: It is used to denote a space-delimited list of class names to pass along to a child element. icon: It is used to denote the name of an icon or an icon element to render before the message. intent: It is used to denote the visual intent color to apply to the element. message: It is used to denote the message to display in the body of the toast. onDismiss: It is a callback function that is triggered when the toast is dismissed, either by the user or by the timeout. timeout: It is used to denote the milliseconds to wait before automatically dismissing toast. Toaster Props: autoFocus: It is used to indicate whether a toast should acquire application focus when it first opens or not. canEscapeKeyClear: It is used to indicate whether pressing the ESC key should clear all active toasts or not. className: It is used to denote a space-delimited list of class names to pass along to a child element. maxToasts: It is used to denote the maximum number of active toasts that can be displayed at once. position: It is used to denote the position of the Toaster within its container. usePortal: It is used to indicate whether the toaster should be rendered into a new element attached to document.body or not. Creating React Application And Installing Module: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the required module using the following command:npm install @blueprintjs/core npm install @blueprintjs/core Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. Appp.js import React from 'react'import '@blueprintjs/core/lib/css/blueprint.css';import { Toast } from "@blueprintjs/core"; function App() { return ( <div style={{ display: 'block', width: 400, padding: 30 }}> <h4>ReactJS Blueprint Toast Component</h4> <Toast message='Sample Toast Message' /> </div > );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://blueprintjs.com/docs/#core/components/toast Blueprint-Core Blueprint-Overlays React-Blueprint JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? How to pass data from one component to other component in ReactJS ? ReactJS Functional Components
[ { "code": null, "e": 26557, "s": 26529, "text": "\n08 Apr, 2022" }, { "code": null, "e": 26731, "s": 26557, "text": "BlueprintJS is a React-based UI toolkit for the web. This library is very optimized and popular for building interfaces that are complex data-dense for desktop applications." }, { "code": null, "e": 26919, "s": 26731, "text": "Toast Component provides a way for users to the user to show an ephemeral message as an overlay. We can use the following approach in ReactJS to use the ReactJS Blueprint Toast Component." }, { "code": null, "e": 26932, "s": 26919, "text": "Toast Props:" }, { "code": null, "e": 27000, "s": 26932, "text": "action: It is an action that is rendered as a minimal AnchorButton." }, { "code": null, "e": 27104, "s": 27000, "text": "className: It is used to denote a space-delimited list of class names to pass along to a child element." }, { "code": null, "e": 27200, "s": 27104, "text": "icon: It is used to denote the name of an icon or an icon element to render before the message." }, { "code": null, "e": 27278, "s": 27200, "text": "intent: It is used to denote the visual intent color to apply to the element." }, { "code": null, "e": 27357, "s": 27278, "text": "message: It is used to denote the message to display in the body of the toast." }, { "code": null, "e": 27479, "s": 27357, "text": "onDismiss: It is a callback function that is triggered when the toast is dismissed, either by the user or by the timeout." }, { "code": null, "e": 27573, "s": 27479, "text": "timeout: It is used to denote the milliseconds to wait before automatically dismissing toast." }, { "code": null, "e": 27588, "s": 27573, "text": "Toaster Props:" }, { "code": null, "e": 27699, "s": 27588, "text": "autoFocus: It is used to indicate whether a toast should acquire application focus when it first opens or not." }, { "code": null, "e": 27809, "s": 27699, "text": "canEscapeKeyClear: It is used to indicate whether pressing the ESC key should clear all active toasts or not." }, { "code": null, "e": 27913, "s": 27809, "text": "className: It is used to denote a space-delimited list of class names to pass along to a child element." }, { "code": null, "e": 28012, "s": 27913, "text": "maxToasts: It is used to denote the maximum number of active toasts that can be displayed at once." }, { "code": null, "e": 28093, "s": 28012, "text": "position: It is used to denote the position of the Toaster within its container." }, { "code": null, "e": 28219, "s": 28093, "text": "usePortal: It is used to indicate whether the toaster should be rendered into a new element attached to document.body or not." }, { "code": null, "e": 28271, "s": 28221, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 28366, "s": 28271, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 28430, "s": 28366, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 28462, "s": 28430, "text": "npx create-react-app foldername" }, { "code": null, "e": 28575, "s": 28462, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 28675, "s": 28575, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 28689, "s": 28675, "text": "cd foldername" }, { "code": null, "e": 28823, "s": 28689, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install @blueprintjs/core" }, { "code": null, "e": 28853, "s": 28823, "text": "npm install @blueprintjs/core" }, { "code": null, "e": 28905, "s": 28853, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 28923, "s": 28905, "text": "Project Structure" }, { "code": null, "e": 29053, "s": 28923, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 29061, "s": 29053, "text": "Appp.js" }, { "code": "import React from 'react'import '@blueprintjs/core/lib/css/blueprint.css';import { Toast } from \"@blueprintjs/core\"; function App() { return ( <div style={{ display: 'block', width: 400, padding: 30 }}> <h4>ReactJS Blueprint Toast Component</h4> <Toast message='Sample Toast Message' /> </div > );} export default App;", "e": 29442, "s": 29061, "text": null }, { "code": null, "e": 29555, "s": 29442, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 29565, "s": 29555, "text": "npm start" }, { "code": null, "e": 29664, "s": 29565, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 29727, "s": 29664, "text": "Reference: https://blueprintjs.com/docs/#core/components/toast" }, { "code": null, "e": 29742, "s": 29727, "text": "Blueprint-Core" }, { "code": null, "e": 29761, "s": 29742, "text": "Blueprint-Overlays" }, { "code": null, "e": 29777, "s": 29761, "text": "React-Blueprint" }, { "code": null, "e": 29788, "s": 29777, "text": "JavaScript" }, { "code": null, "e": 29796, "s": 29788, "text": "ReactJS" }, { "code": null, "e": 29813, "s": 29796, "text": "Web Technologies" }, { "code": null, "e": 29911, "s": 29813, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29951, "s": 29911, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30012, "s": 29951, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30053, "s": 30012, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 30075, "s": 30053, "text": "JavaScript | Promises" }, { "code": null, "e": 30129, "s": 30075, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 30172, "s": 30129, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 30217, "s": 30172, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 30282, "s": 30217, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 30350, "s": 30282, "text": "How to pass data from one component to other component in ReactJS ?" } ]
C | Loops & Control Structure | Question 1 - GeeksforGeeks
09 Jan, 2013 #include <stdio.h> int main(){ int i = 1024; for (; i; i >>= 1) printf("GeeksQuiz"); return 0;} How many times will GeeksQuiz be printed in the above program?(A) 10(B) 11(C) Infinite(D) The program will show compile-time errorAnswer: (B)Explanation: In for loop, mentioning expression is optional. >>= is a composite operator. It shifts the binary representation of the value by 1 to the right and assigns the resulting value to the same variable. The for loop is executed until value of variable i doesn’t drop to 0. C-Loops & Control Structure Loops & Control Structure C Language C Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C rand() and srand() in C/C++ std::string class in C++ fork() in C Compiling a C program:- Behind the Scenes Operator Precedence and Associativity in C C | File Handling | Question 1 C | Misc | Question 7 C | Arrays | Question 7
[ { "code": null, "e": 26057, "s": 26029, "text": "\n09 Jan, 2013" }, { "code": "#include <stdio.h> int main(){ int i = 1024; for (; i; i >>= 1) printf(\"GeeksQuiz\"); return 0;}", "e": 26170, "s": 26057, "text": null }, { "code": null, "e": 26592, "s": 26170, "text": "How many times will GeeksQuiz be printed in the above program?(A) 10(B) 11(C) Infinite(D) The program will show compile-time errorAnswer: (B)Explanation: In for loop, mentioning expression is optional. >>= is a composite operator. It shifts the binary representation of the value by 1 to the right and assigns the resulting value to the same variable. The for loop is executed until value of variable i doesn’t drop to 0." }, { "code": null, "e": 26620, "s": 26592, "text": "C-Loops & Control Structure" }, { "code": null, "e": 26646, "s": 26620, "text": "Loops & Control Structure" }, { "code": null, "e": 26657, "s": 26646, "text": "C Language" }, { "code": null, "e": 26664, "s": 26657, "text": "C Quiz" }, { "code": null, "e": 26762, "s": 26664, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26779, "s": 26762, "text": "Substring in C++" }, { "code": null, "e": 26801, "s": 26779, "text": "Function Pointer in C" }, { "code": null, "e": 26829, "s": 26801, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 26854, "s": 26829, "text": "std::string class in C++" }, { "code": null, "e": 26866, "s": 26854, "text": "fork() in C" }, { "code": null, "e": 26908, "s": 26866, "text": "Compiling a C program:- Behind the Scenes" }, { "code": null, "e": 26951, "s": 26908, "text": "Operator Precedence and Associativity in C" }, { "code": null, "e": 26982, "s": 26951, "text": "C | File Handling | Question 1" }, { "code": null, "e": 27004, "s": 26982, "text": "C | Misc | Question 7" } ]
Remove all the occurrences of an element from a list in Python - GeeksforGeeks
09 Apr, 2022 The task is to perform the operation of removing all the occurrences of a given item/element present in a list. Examples : Input : 1 1 2 3 4 5 1 2 1 Output : 2 3 4 5 2 Explanation : The input list is [1, 1, 2, 3, 4, 5, 1, 2] and the item to be removed is 1. After removing the item, the output list is [2, 3, 4, 5, 2] Input : 5 6 7 8 9 10 7 Output : 5 6 8 9 10 In this article, we shall see how to execute this task in 3 ways : Using list comprehensionUsing filter() and __ne__Using remove() Using list comprehension Using filter() and __ne__ Using remove() Method 1 : Using list comprehension The list comprehension can be used to perform this task in which we just check for a match and reconstruct the list without the target element. We can create a sublist of those elements in the list that satisfies a certain condition. Python3 # Python 3 code to demonstrate# the removal of all occurrences of a# given item using list comprehension def remove_items(test_list, item): # using list comprehension to perform the task res = [i for i in test_list if i != item] return res # driver codeif __name__=="__main__": # initializing the list test_list = [1, 3, 4, 6, 5, 1] # the item which is to be removed item = 1 # printing the original list print ("The original list is : " + str(test_list)) # calling the function remove_items() res = remove_items(test_list, item) # printing result print ("The list after performing the remove operation is : " + str(res)) Output The original list is : [1, 3, 4, 6, 5, 1] The list after performing the remove operation is : [3, 4, 6, 5] Method 2 : Using filter() and __ne__ We filter those items of the list which are not equal __ne__ to the item. Python3 # Python 3 code to demonstrate# the removal of all occurrences of# a given item using filter() and __ne__ def remove_items(test_list, item): # using filter() + __ne__ to perform the task res = list(filter((item).__ne__, test_list)) return res # driver codeif __name__=="__main__": # initializing the list test_list = [1, 3, 4, 6, 5, 1] # the item which is to be removed item = 1 # printing the original list print ("The original list is : " + str(test_list)) # calling the function remove_items() res = remove_items(test_list, item) # printing result print ("The list after performing the remove operation is : " + str(res)) Output The original list is : [1, 3, 4, 6, 5, 1] The list after performing the remove operation is : [3, 4, 6, 5] Method 3 : Using remove() In this method, we iterate through each item in the list, and when we find a match for the item to be removed, we will call remove() function on the list. Python3 # Python 3 code to demonstrate# the removal of all occurrences of# a given item using remove() def remove_items(test_list, item): # remove the item for all its occurrences c = test_list.count(item) for i in range(c): test_list.remove(item) return test_list # driver codeif __name__=="__main__": # initializing the list test_list = [1, 3, 4, 6, 5, 1] # the item which is to be removed item = 1 # printing the original list print ("The original list is :" + str(test_list)) # calling the function remove_items() res = remove_items(test_list, item) # printing result print ("The list after performing the remove operation is :" + str(res)) Output The original list is : [1, 3, 4, 6, 5, 1] The list after performing the remove operation is : [3, 4, 6, 5] saumya1126 Python list-programs python-list Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25562, "s": 25534, "text": "\n09 Apr, 2022" }, { "code": null, "e": 25685, "s": 25562, "text": "The task is to perform the operation of removing all the occurrences of a given item/element present in a list. Examples :" }, { "code": null, "e": 25923, "s": 25685, "text": "Input : 1 1 2 3 4 5 1 2 1 Output : 2 3 4 5 2 Explanation : The input list is [1, 1, 2, 3, 4, 5, 1, 2] and the item to be removed is 1. After removing the item, the output list is [2, 3, 4, 5, 2] Input : 5 6 7 8 9 10 7 Output : 5 6 8 9 10" }, { "code": null, "e": 25990, "s": 25923, "text": "In this article, we shall see how to execute this task in 3 ways :" }, { "code": null, "e": 26054, "s": 25990, "text": "Using list comprehensionUsing filter() and __ne__Using remove()" }, { "code": null, "e": 26079, "s": 26054, "text": "Using list comprehension" }, { "code": null, "e": 26105, "s": 26079, "text": "Using filter() and __ne__" }, { "code": null, "e": 26120, "s": 26105, "text": "Using remove()" }, { "code": null, "e": 26391, "s": 26120, "text": "Method 1 : Using list comprehension The list comprehension can be used to perform this task in which we just check for a match and reconstruct the list without the target element. We can create a sublist of those elements in the list that satisfies a certain condition. " }, { "code": null, "e": 26399, "s": 26391, "text": "Python3" }, { "code": "# Python 3 code to demonstrate# the removal of all occurrences of a# given item using list comprehension def remove_items(test_list, item): # using list comprehension to perform the task res = [i for i in test_list if i != item] return res # driver codeif __name__==\"__main__\": # initializing the list test_list = [1, 3, 4, 6, 5, 1] # the item which is to be removed item = 1 # printing the original list print (\"The original list is : \" + str(test_list)) # calling the function remove_items() res = remove_items(test_list, item) # printing result print (\"The list after performing the remove operation is : \" + str(res))", "e": 27075, "s": 26399, "text": null }, { "code": null, "e": 27082, "s": 27075, "text": "Output" }, { "code": null, "e": 27189, "s": 27082, "text": "The original list is : [1, 3, 4, 6, 5, 1]\nThe list after performing the remove operation is : [3, 4, 6, 5]" }, { "code": null, "e": 27301, "s": 27189, "text": "Method 2 : Using filter() and __ne__ We filter those items of the list which are not equal __ne__ to the item. " }, { "code": null, "e": 27309, "s": 27301, "text": "Python3" }, { "code": "# Python 3 code to demonstrate# the removal of all occurrences of# a given item using filter() and __ne__ def remove_items(test_list, item): # using filter() + __ne__ to perform the task res = list(filter((item).__ne__, test_list)) return res # driver codeif __name__==\"__main__\": # initializing the list test_list = [1, 3, 4, 6, 5, 1] # the item which is to be removed item = 1 # printing the original list print (\"The original list is : \" + str(test_list)) # calling the function remove_items() res = remove_items(test_list, item) # printing result print (\"The list after performing the remove operation is : \" + str(res))", "e": 27988, "s": 27309, "text": null }, { "code": null, "e": 27995, "s": 27988, "text": "Output" }, { "code": null, "e": 28102, "s": 27995, "text": "The original list is : [1, 3, 4, 6, 5, 1]\nThe list after performing the remove operation is : [3, 4, 6, 5]" }, { "code": null, "e": 28284, "s": 28102, "text": "Method 3 : Using remove() In this method, we iterate through each item in the list, and when we find a match for the item to be removed, we will call remove() function on the list. " }, { "code": null, "e": 28292, "s": 28284, "text": "Python3" }, { "code": "# Python 3 code to demonstrate# the removal of all occurrences of# a given item using remove() def remove_items(test_list, item): # remove the item for all its occurrences c = test_list.count(item) for i in range(c): test_list.remove(item) return test_list # driver codeif __name__==\"__main__\": # initializing the list test_list = [1, 3, 4, 6, 5, 1] # the item which is to be removed item = 1 # printing the original list print (\"The original list is :\" + str(test_list)) # calling the function remove_items() res = remove_items(test_list, item) # printing result print (\"The list after performing the remove operation is :\" + str(res))", "e": 28997, "s": 28292, "text": null }, { "code": null, "e": 29004, "s": 28997, "text": "Output" }, { "code": null, "e": 29111, "s": 29004, "text": "The original list is : [1, 3, 4, 6, 5, 1]\nThe list after performing the remove operation is : [3, 4, 6, 5]" }, { "code": null, "e": 29122, "s": 29111, "text": "saumya1126" }, { "code": null, "e": 29143, "s": 29122, "text": "Python list-programs" }, { "code": null, "e": 29155, "s": 29143, "text": "python-list" }, { "code": null, "e": 29162, "s": 29155, "text": "Python" }, { "code": null, "e": 29174, "s": 29162, "text": "python-list" }, { "code": null, "e": 29272, "s": 29174, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29304, "s": 29272, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29346, "s": 29304, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29388, "s": 29346, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29415, "s": 29388, "text": "Python Classes and Objects" }, { "code": null, "e": 29471, "s": 29415, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29493, "s": 29471, "text": "Defaultdict in Python" }, { "code": null, "e": 29532, "s": 29493, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29563, "s": 29532, "text": "Python | os.path.join() method" }, { "code": null, "e": 29592, "s": 29563, "text": "Create a directory in Python" } ]
Most Useful CMD Commands in Windows - GeeksforGeeks
31 Aug, 2021 CMD Commands are the most preferred way of doing anything to computer experts and coders. Today we’re going to learn some useful commands that make our work easy and productive. Most Useful CMD Commands in Windows Usually, when we open our command prompt, we see in the left corner path of the current directory is written. So now we want to change it to our wish. Here Prompt command is used. Syntax: prompt name_that_you_want Similarly, like prompt, when we open command prompt, the title of the application is like β€œC:\WINDOWS\system32\cmd.exe” is written. If we want to change it, then we use the title command. Syntax: title name_that_you_want When we see hackers in movies, having some green codes moving very fast on their computer screen, we get fascinated. Maybe you’ve got bored while working on a black and white screen. Then you can use the color command. It requires two Hexadecimal digits. First for background and second for the foreground. Example: color 02 makes it green text and black background. There are many ways to open command prompt in windows. One we’re going to discuss today is, to open CMD in any folder. Yes, we’ll open it in any folder. Simply go to the address bar of that folder type β€œcmd” and hit β€œenter”. When we hide any folder going from its properties, it gets showed as we check β€œShow hidden files” and the same thing happens when we use β€œattrib +h filename”. So now we are going to see a command that will hide your folder and there’s no any way to find it out again by others instead of you. Syntax: attrib +h +s +r filename Note: Use β€œattrib -h -s -r file name ” to unhide the file. So, the first command is for checking the battery health of the laptop. The command prompt will give you brief information and technical details about your laptop’s battery. To view a battery report, open a command prompt as an administrator and run the following command: powercfg /batteryreport /output β€œC:\battery_report.html” After hitting the enter key, your laptop’s battery report will be saved in your specified route in html format. (here we have given the path of the C drive). Battery report generated Check out this detailed article checking laptop’s battery health. With Windows command prompt, you can check all system files for any system problems like file corruption within a single command. Just open a command prompt in administrative mode and type: sfc /scannow This command will scan all protected system files, and replace corrupted files with a cached copy that is located in a compressed folder at %WinDir%\System32\dllcache. This process will take some time, so don’t close command prompt until verification gets completed. Scan for system problems Sometimes you need to transfer your Windows 10 license to a new computer. At that time, your Windows product license key is very important. Let’s see how you can get your windows license key using a command prompt. As earlier, open a command prompt in administrative mode and after typing the command mentioned below, press the enter key. wmic path softwarelicensingservice get OA3xOriginalProductKey Windows license key Sometimes you can’t find an overview of all the nested folders on a drive and get confused about the location of a particular folder. In this situation, the command line helps you out. It will give you a tree-like representation of all the nested folders in that directory. Type this command and after pressing enter you’ll see the pictorial representation of all the folders. tree Overview of all the nested folders on a drive You can also add β€œ> c:\export.txt” after tree, to save the results in a text file that you can browse in your local storage. All the folders list is saved to the C drive. You might know that your computer has a Domain Name System (DNS) which converts the site URL that you type in the browser address bar into an IP address equivalent to that site. So your Incognito history also gets saved in a DNS cache, sometimes referred to as a DNS resolver cache. To view DNS cache type ipconfig /displaydns in the command line, and press enter and you will see all the sites with their IP addresses. DNS Cache consisting list of websites and their IP Addresses To delete DNS cache type ipconfig /flushdns and your incognito history will be cleared. DNS Cache cleared You can also checkout our detailed article about How to Check Incognito History and Delete it. So these are five command tricks you need to know. Hope you find value from it. For more about such command tricks, visit this article about Useful CMD commands for daily use in Windows OS user282 Technical Scripter 2020 GBlog Technical Scripter TechTips Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar Top 10 Projects For Beginners To Practice HTML and CSS Skills Types of Software Testing Working with csv files in Python How to Start Learning DSA? How to Find the Wi-Fi Password Using CMD in Windows? Docker - COPY Instruction Top Programming Languages for Android App Development How to Run a Python Script using Docker? Setting up the environment in Java
[ { "code": null, "e": 26007, "s": 25979, "text": "\n31 Aug, 2021" }, { "code": null, "e": 26185, "s": 26007, "text": "CMD Commands are the most preferred way of doing anything to computer experts and coders. Today we’re going to learn some useful commands that make our work easy and productive." }, { "code": null, "e": 26221, "s": 26185, "text": "Most Useful CMD Commands in Windows" }, { "code": null, "e": 26401, "s": 26221, "text": "Usually, when we open our command prompt, we see in the left corner path of the current directory is written. So now we want to change it to our wish. Here Prompt command is used." }, { "code": null, "e": 26409, "s": 26401, "text": "Syntax:" }, { "code": null, "e": 26435, "s": 26409, "text": "prompt name_that_you_want" }, { "code": null, "e": 26623, "s": 26435, "text": "Similarly, like prompt, when we open command prompt, the title of the application is like β€œC:\\WINDOWS\\system32\\cmd.exe” is written. If we want to change it, then we use the title command." }, { "code": null, "e": 26632, "s": 26623, "text": "Syntax: " }, { "code": null, "e": 26657, "s": 26632, "text": "title name_that_you_want" }, { "code": null, "e": 26876, "s": 26657, "text": "When we see hackers in movies, having some green codes moving very fast on their computer screen, we get fascinated. Maybe you’ve got bored while working on a black and white screen. Then you can use the color command." }, { "code": null, "e": 26965, "s": 26876, "text": "It requires two Hexadecimal digits. First for background and second for the foreground. " }, { "code": null, "e": 27026, "s": 26965, "text": "Example: color 02 makes it green text and black background. " }, { "code": null, "e": 27251, "s": 27026, "text": "There are many ways to open command prompt in windows. One we’re going to discuss today is, to open CMD in any folder. Yes, we’ll open it in any folder. Simply go to the address bar of that folder type β€œcmd” and hit β€œenter”." }, { "code": null, "e": 27546, "s": 27251, "text": "When we hide any folder going from its properties, it gets showed as we check β€œShow hidden files” and the same thing happens when we use β€œattrib +h filename”. So now we are going to see a command that will hide your folder and there’s no any way to find it out again by others instead of you. " }, { "code": null, "e": 27555, "s": 27546, "text": "Syntax: " }, { "code": null, "e": 27580, "s": 27555, "text": "attrib +h +s +r filename" }, { "code": null, "e": 27639, "s": 27580, "text": "Note: Use β€œattrib -h -s -r file name ” to unhide the file." }, { "code": null, "e": 27912, "s": 27639, "text": "So, the first command is for checking the battery health of the laptop. The command prompt will give you brief information and technical details about your laptop’s battery. To view a battery report, open a command prompt as an administrator and run the following command:" }, { "code": null, "e": 27969, "s": 27912, "text": "powercfg /batteryreport /output β€œC:\\battery_report.html”" }, { "code": null, "e": 28127, "s": 27969, "text": "After hitting the enter key, your laptop’s battery report will be saved in your specified route in html format. (here we have given the path of the C drive)." }, { "code": null, "e": 28152, "s": 28127, "text": "Battery report generated" }, { "code": null, "e": 28218, "s": 28152, "text": "Check out this detailed article checking laptop’s battery health." }, { "code": null, "e": 28408, "s": 28218, "text": "With Windows command prompt, you can check all system files for any system problems like file corruption within a single command. Just open a command prompt in administrative mode and type:" }, { "code": null, "e": 28421, "s": 28408, "text": "sfc /scannow" }, { "code": null, "e": 28688, "s": 28421, "text": "This command will scan all protected system files, and replace corrupted files with a cached copy that is located in a compressed folder at %WinDir%\\System32\\dllcache. This process will take some time, so don’t close command prompt until verification gets completed." }, { "code": null, "e": 28713, "s": 28688, "text": "Scan for system problems" }, { "code": null, "e": 29052, "s": 28713, "text": "Sometimes you need to transfer your Windows 10 license to a new computer. At that time, your Windows product license key is very important. Let’s see how you can get your windows license key using a command prompt. As earlier, open a command prompt in administrative mode and after typing the command mentioned below, press the enter key." }, { "code": null, "e": 29114, "s": 29052, "text": "wmic path softwarelicensingservice get OA3xOriginalProductKey" }, { "code": null, "e": 29134, "s": 29114, "text": "Windows license key" }, { "code": null, "e": 29511, "s": 29134, "text": "Sometimes you can’t find an overview of all the nested folders on a drive and get confused about the location of a particular folder. In this situation, the command line helps you out. It will give you a tree-like representation of all the nested folders in that directory. Type this command and after pressing enter you’ll see the pictorial representation of all the folders." }, { "code": null, "e": 29516, "s": 29511, "text": "tree" }, { "code": null, "e": 29562, "s": 29516, "text": "Overview of all the nested folders on a drive" }, { "code": null, "e": 29687, "s": 29562, "text": "You can also add β€œ> c:\\export.txt” after tree, to save the results in a text file that you can browse in your local storage." }, { "code": null, "e": 29733, "s": 29687, "text": "All the folders list is saved to the C drive." }, { "code": null, "e": 30016, "s": 29733, "text": "You might know that your computer has a Domain Name System (DNS) which converts the site URL that you type in the browser address bar into an IP address equivalent to that site. So your Incognito history also gets saved in a DNS cache, sometimes referred to as a DNS resolver cache." }, { "code": null, "e": 30153, "s": 30016, "text": "To view DNS cache type ipconfig /displaydns in the command line, and press enter and you will see all the sites with their IP addresses." }, { "code": null, "e": 30214, "s": 30153, "text": "DNS Cache consisting list of websites and their IP Addresses" }, { "code": null, "e": 30303, "s": 30214, "text": "To delete DNS cache type ipconfig /flushdns and your incognito history will be cleared." }, { "code": null, "e": 30321, "s": 30303, "text": "DNS Cache cleared" }, { "code": null, "e": 30416, "s": 30321, "text": "You can also checkout our detailed article about How to Check Incognito History and Delete it." }, { "code": null, "e": 30605, "s": 30416, "text": "So these are five command tricks you need to know. Hope you find value from it. For more about such command tricks, visit this article about Useful CMD commands for daily use in Windows OS" }, { "code": null, "e": 30613, "s": 30605, "text": "user282" }, { "code": null, "e": 30637, "s": 30613, "text": "Technical Scripter 2020" }, { "code": null, "e": 30643, "s": 30637, "text": "GBlog" }, { "code": null, "e": 30662, "s": 30643, "text": "Technical Scripter" }, { "code": null, "e": 30671, "s": 30662, "text": "TechTips" }, { "code": null, "e": 30769, "s": 30671, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30794, "s": 30769, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 30856, "s": 30794, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 30882, "s": 30856, "text": "Types of Software Testing" }, { "code": null, "e": 30915, "s": 30882, "text": "Working with csv files in Python" }, { "code": null, "e": 30942, "s": 30915, "text": "How to Start Learning DSA?" }, { "code": null, "e": 30995, "s": 30942, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 31021, "s": 30995, "text": "Docker - COPY Instruction" }, { "code": null, "e": 31075, "s": 31021, "text": "Top Programming Languages for Android App Development" }, { "code": null, "e": 31116, "s": 31075, "text": "How to Run a Python Script using Docker?" } ]
Heap and Priority Queue using heapq module in Python - GeeksforGeeks
10 May, 2022 Heaps are widely used tree-like data structures in which the parent nodes satisfy any one of the criteria given below. The value of the parent node in each level is less than or equal to its children’s values – min-heap. The value of the parent node in each level higher than or equal to its children’s values – max-heap. The heaps are complete binary trees and are used in the implementation of the priority queues. The min-heaps play a vital role in scheduling jobs, scheduling emails or in assigning the resources to tasks based on the priority. These are abstract data types and are a special form of queues. The elements in the queue have priorities assigned to them. Based on the priorities, the first element in the priority queue will be the one with the highest priority. The basic operations associated with these priority queues are listed below: is_empty: To check whether the queue is empty. insert : To insert an element along with its priority. The element will be placed in the order of its priority only. pop : To pop the element with the highest priority. The first element will be the element with the highest priority. The priority queues can be used for all scheduling kind of processes. The programmer can decide whether the largest number is considered as the highest priority or the lowest number will be considered as the highest priority. If two elements have the same priority, then they appear in the order in which they appear in the queue. Heapq module is an implementation of heap queue algorithm (priority queue algorithm) in which the property of min-heap is preserved. The module takes up a list of items and rearranges it such that they satisfy the following criteria of min-heap: The parent node in index β€˜i’ is less than or equal to its children. The left child of a node in index β€˜i’ is in index β€˜(2*i) + 1’. The right child of a node in index β€˜i’ is in index β€˜(2*i) + 2’. The priority queue is implemented in Python as a list of tuples where the tuple contains the priority as the first element and the value as the next element. Example : [ (1, 2), (2, 3), (4, 5), (6,7)] consider (1,2) : Priority : 1 Value/element : 2 Example: Consider a simple priority queue implementation for scheduling the presentations of students based on their roll number. Here roll number decides the priority of the student to present. Since it is a min-heap, roll number 1 is considered to be of the highest priority. Python3 # import modulesimport heapq as hq # list of studentslist_stu = [(5,'Rina'),(1,'Anish'),(3,'Moana'),(2,'cathy'),(4,'Lucy')] # Arrange based on the roll numberhq.heapify(list_stu) print("The order of presentation is :") for i in list_stu: print(i[0],':',i[1]) The order of presentation is : 1 : Anish 2 : cathy 3 : Moana 5 : Rina 4 : Lucy Example 2: Now let us implement a simple scheduler that assigns the jobs to the processor. The priority queue is used by the scheduler to decide which task has to be performed. Apart from the tasks, there will be interrupts approaching the scheduler. So the scheduler has to decide whether to execute the interrupt or the existing task. If the interrupt has a higher priority, it is executed first otherwise, once all the jobs are completed, the interrupt will be serviced. To implement this the heapq module is used. The approach is given below. The tasks to be executed are assigned with priorities. The element that has β€˜1’ as priority is considered to be the most important task. All the tasks are in a priority queue and are maintained with the min-heap property. The tasks are serviced and while in progress, just a message gets printed as an execution log stating which task is in progress. The interrupts along with their priorities approach the scheduler. The interrupts are pushed into the priority queue preserving the min-heap property. The task/interrupt with the highest priority will be serviced first and it is always the first element in the queue. Once a task.interrupt is serviced, it is popped out from heap queue. Python3 import timeimport heapq as hq # jobs to be executedjobs = [(2, 'task_1'), (5, 'task_2'), (1, 'task_4'), (4, 'task_5'), (3, 'task_3'), (1, 'task_8')] # interruptsinterrupts = [(1, 'intr_1'), (2, 'intr_2'), (13, 'intr_3')] i, j = 0, 0 # Arranging jobs in heaphq.heapify(jobs) print(jobs, "\n\n") # scheduling the taskswhile len(jobs) != 0: # printing execution log print("The ", jobs[0][1], " with priority ", jobs[0][0], " in progress", end="") # servicing the tasks for _ in range(0, 5): print(".", end="") time.sleep(0.5) # pop the job that completed hq.heappop(jobs) # adding interrupts if j < len(interrupts): hq.heappush(jobs, interrupts[j]) print("\n\nNew interrupt arrived!!", interrupts[j]) print() j = j+1 # job queue after arrival of interrupt print("\n Job queue currently :", jobs) print("\n") print("\nAll interrupts and jobs completed!") Output Data Structures-Heap priority-queue Python-Data-Structures Python priority-queue Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Python | Get unique values from a list Python | Pandas dataframe.groupby() Defaultdict in Python
[ { "code": null, "e": 25581, "s": 25553, "text": "\n10 May, 2022" }, { "code": null, "e": 25700, "s": 25581, "text": "Heaps are widely used tree-like data structures in which the parent nodes satisfy any one of the criteria given below." }, { "code": null, "e": 25802, "s": 25700, "text": "The value of the parent node in each level is less than or equal to its children’s values – min-heap." }, { "code": null, "e": 25903, "s": 25802, "text": "The value of the parent node in each level higher than or equal to its children’s values – max-heap." }, { "code": null, "e": 26131, "s": 25903, "text": "The heaps are complete binary trees and are used in the implementation of the priority queues. The min-heaps play a vital role in scheduling jobs, scheduling emails or in assigning the resources to tasks based on the priority. " }, { "code": null, "e": 26441, "s": 26131, "text": "These are abstract data types and are a special form of queues. The elements in the queue have priorities assigned to them. Based on the priorities, the first element in the priority queue will be the one with the highest priority. The basic operations associated with these priority queues are listed below: " }, { "code": null, "e": 26488, "s": 26441, "text": "is_empty: To check whether the queue is empty." }, { "code": null, "e": 26605, "s": 26488, "text": "insert : To insert an element along with its priority. The element will be placed in the order of its priority only." }, { "code": null, "e": 26722, "s": 26605, "text": "pop : To pop the element with the highest priority. The first element will be the element with the highest priority." }, { "code": null, "e": 27054, "s": 26722, "text": "The priority queues can be used for all scheduling kind of processes. The programmer can decide whether the largest number is considered as the highest priority or the lowest number will be considered as the highest priority. If two elements have the same priority, then they appear in the order in which they appear in the queue. " }, { "code": null, "e": 27300, "s": 27054, "text": "Heapq module is an implementation of heap queue algorithm (priority queue algorithm) in which the property of min-heap is preserved. The module takes up a list of items and rearranges it such that they satisfy the following criteria of min-heap:" }, { "code": null, "e": 27368, "s": 27300, "text": "The parent node in index β€˜i’ is less than or equal to its children." }, { "code": null, "e": 27431, "s": 27368, "text": "The left child of a node in index β€˜i’ is in index β€˜(2*i) + 1’." }, { "code": null, "e": 27495, "s": 27431, "text": "The right child of a node in index β€˜i’ is in index β€˜(2*i) + 2’." }, { "code": null, "e": 27653, "s": 27495, "text": "The priority queue is implemented in Python as a list of tuples where the tuple contains the priority as the first element and the value as the next element." }, { "code": null, "e": 27696, "s": 27653, "text": "Example : [ (1, 2), (2, 3), (4, 5), (6,7)]" }, { "code": null, "e": 27714, "s": 27696, "text": "consider (1,2) : " }, { "code": null, "e": 27727, "s": 27714, "text": "Priority : 1" }, { "code": null, "e": 27745, "s": 27727, "text": "Value/element : 2" }, { "code": null, "e": 27754, "s": 27745, "text": "Example:" }, { "code": null, "e": 28023, "s": 27754, "text": "Consider a simple priority queue implementation for scheduling the presentations of students based on their roll number. Here roll number decides the priority of the student to present. Since it is a min-heap, roll number 1 is considered to be of the highest priority." }, { "code": null, "e": 28031, "s": 28023, "text": "Python3" }, { "code": "# import modulesimport heapq as hq # list of studentslist_stu = [(5,'Rina'),(1,'Anish'),(3,'Moana'),(2,'cathy'),(4,'Lucy')] # Arrange based on the roll numberhq.heapify(list_stu) print(\"The order of presentation is :\") for i in list_stu: print(i[0],':',i[1])", "e": 28295, "s": 28031, "text": null }, { "code": null, "e": 28375, "s": 28295, "text": "The order of presentation is :\n1 : Anish\n2 : cathy\n3 : Moana\n5 : Rina\n4 : Lucy\n" }, { "code": null, "e": 28386, "s": 28375, "text": "Example 2:" }, { "code": null, "e": 28922, "s": 28386, "text": "Now let us implement a simple scheduler that assigns the jobs to the processor. The priority queue is used by the scheduler to decide which task has to be performed. Apart from the tasks, there will be interrupts approaching the scheduler. So the scheduler has to decide whether to execute the interrupt or the existing task. If the interrupt has a higher priority, it is executed first otherwise, once all the jobs are completed, the interrupt will be serviced. To implement this the heapq module is used. The approach is given below." }, { "code": null, "e": 29059, "s": 28922, "text": "The tasks to be executed are assigned with priorities. The element that has β€˜1’ as priority is considered to be the most important task." }, { "code": null, "e": 29144, "s": 29059, "text": "All the tasks are in a priority queue and are maintained with the min-heap property." }, { "code": null, "e": 29273, "s": 29144, "text": "The tasks are serviced and while in progress, just a message gets printed as an execution log stating which task is in progress." }, { "code": null, "e": 29340, "s": 29273, "text": "The interrupts along with their priorities approach the scheduler." }, { "code": null, "e": 29424, "s": 29340, "text": "The interrupts are pushed into the priority queue preserving the min-heap property." }, { "code": null, "e": 29541, "s": 29424, "text": "The task/interrupt with the highest priority will be serviced first and it is always the first element in the queue." }, { "code": null, "e": 29610, "s": 29541, "text": "Once a task.interrupt is serviced, it is popped out from heap queue." }, { "code": null, "e": 29618, "s": 29610, "text": "Python3" }, { "code": "import timeimport heapq as hq # jobs to be executedjobs = [(2, 'task_1'), (5, 'task_2'), (1, 'task_4'), (4, 'task_5'), (3, 'task_3'), (1, 'task_8')] # interruptsinterrupts = [(1, 'intr_1'), (2, 'intr_2'), (13, 'intr_3')] i, j = 0, 0 # Arranging jobs in heaphq.heapify(jobs) print(jobs, \"\\n\\n\") # scheduling the taskswhile len(jobs) != 0: # printing execution log print(\"The \", jobs[0][1], \" with priority \", jobs[0][0], \" in progress\", end=\"\") # servicing the tasks for _ in range(0, 5): print(\".\", end=\"\") time.sleep(0.5) # pop the job that completed hq.heappop(jobs) # adding interrupts if j < len(interrupts): hq.heappush(jobs, interrupts[j]) print(\"\\n\\nNew interrupt arrived!!\", interrupts[j]) print() j = j+1 # job queue after arrival of interrupt print(\"\\n Job queue currently :\", jobs) print(\"\\n\") print(\"\\nAll interrupts and jobs completed!\")", "e": 30583, "s": 29618, "text": null }, { "code": null, "e": 30590, "s": 30583, "text": "Output" }, { "code": null, "e": 30611, "s": 30590, "text": "Data Structures-Heap" }, { "code": null, "e": 30626, "s": 30611, "text": "priority-queue" }, { "code": null, "e": 30649, "s": 30626, "text": "Python-Data-Structures" }, { "code": null, "e": 30656, "s": 30649, "text": "Python" }, { "code": null, "e": 30671, "s": 30656, "text": "priority-queue" }, { "code": null, "e": 30769, "s": 30671, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30801, "s": 30769, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30843, "s": 30801, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 30885, "s": 30843, "text": "Check if element exists in list in Python" }, { "code": null, "e": 30941, "s": 30885, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 30968, "s": 30941, "text": "Python Classes and Objects" }, { "code": null, "e": 30999, "s": 30968, "text": "Python | os.path.join() method" }, { "code": null, "e": 31028, "s": 30999, "text": "Create a directory in Python" }, { "code": null, "e": 31067, "s": 31028, "text": "Python | Get unique values from a list" }, { "code": null, "e": 31103, "s": 31067, "text": "Python | Pandas dataframe.groupby()" } ]
How To Compare Two Dataframes with Pandas compare?
12 Nov, 2020 A DataFrame is a 2D structure composed of rows and columns, and where data is stored into a tubular form. It is mutable in terms of size, and heterogeneous tabular data. Arithmetic operations can also be performed on both row and column labels. To know more about the creation of Pandas DataFrame. Here, we will see how to compare two DataFrames with pandas.DataFrame.compare. Syntax: DataFrame.compare(other, align_axis=1, keep_shape=False, keep_equal=False) So, let’s understand each of its parameters – other : This is the first parameter which actually takes the DataFrame object to be compared with the present DataFrame.align_axis : It deals with the axis(vertical / horizontal) where the comparison is to be made(by default False).0 or index : Here the output of the differences are presented vertically, 1 or columns : The output of the differences are displayed horizontally.keep_shape : It means that whether we want all the data values to be displayed in the output or only the ones with distinct value. It is of bool type and the default value for it is β€œfalse”, i.e. it displays all the values in the table by default.keep_equal : This is mainly for displaying same or equal values in the output when set to True. If it is made false then it will display the equal values as NANs. other : This is the first parameter which actually takes the DataFrame object to be compared with the present DataFrame. align_axis : It deals with the axis(vertical / horizontal) where the comparison is to be made(by default False).0 or index : Here the output of the differences are presented vertically, 1 or columns : The output of the differences are displayed horizontally. keep_shape : It means that whether we want all the data values to be displayed in the output or only the ones with distinct value. It is of bool type and the default value for it is β€œfalse”, i.e. it displays all the values in the table by default. keep_equal : This is mainly for displaying same or equal values in the output when set to True. If it is made false then it will display the equal values as NANs. Returns another DataFrame with the differences between the two dataFrames. Before Starting, an important note is the pandas version must be at least 1.1.0. To check that, run this on your cmd or Anaconda navigator cmd. import pandas as pd print(pd.__version__) If it is 1.1.0 or greater than that, you are good to go! Otherwise, you can install pandas compatible version by the command into your window cmd by running as an administrator, or otherwise into your Anaconda navigator if it is added to the path. # if you want the latest version available pip install pandas --upgrade # or if you want to specify the version pip install pandas==1.1.0 Implementation: Step 1: we will create our first dataframe. Approach: Import pandas for DataFrameImport NumPy for any NAN values which can come up through operations or insertCreate the DataFrames using pandas.DataFrame and passing the value for your rows, columnsSpecify the column headings(from the value you have passed in the dictionary) Import pandas for DataFrame Import NumPy for any NAN values which can come up through operations or insert Create the DataFrames using pandas.DataFrame and passing the value for your rows, columns Specify the column headings(from the value you have passed in the dictionary) Python3 # pandas version == 1.1.0 (min)import pandas as pdimport numpy as np # create your first DataFrame# using pd.DataFramefirst_df = pd.DataFrame( { "Stationary": ["Pens", "Scales", "Pencils", "Geometry Box", "Crayon Set"], "Price": [100, 50, 25, 100, 65], "Quantity": [10, 5, 5, 2, 1] }, columns=["Stationary", "Price", "Quantity"],)# Display the dffirst_df Output: Step 2:Now, let’s make out the next DataFrame for comparing their values: Python3 # creating the second dataFrame by # copying and modifying the first DataFramesecond_df = first_df.copy() # loc specifies the location,# here 0th index of Price Columnsecond_df.loc[0, 'Price'] = 150 second_df.loc[1, 'Price'] = 70second_df.loc[2, 'Price'] = 30second_df.loc[0, 'Quantity'] = 15second_df.loc[1, 'Quantity'] = 7second_df.loc[2, 'Quantity'] = 6 # display the dfsecond_df Output: We are creating another DataFrame by copying the table structure of the first_DataFrame with certain modifications. Now, let’s see the content of the second_DataFrame Step 3: let us do our main operation – compare. Here we have performed two operations, firstly to align the differences of the changes in the columns, for which the align_axis by default is set to 1 and table will be with columns drawn alternately from self and other. Python3 #Align the differences on the columnsfirst_df.compare(second_df) Output: And secondly, we have set the align_axis = 0 which makes the table rows drawn alternately from self and others. Python3 # align the differences on rowsfirst_df.compare(second_df,align_axis=0) Output: Step 4: let’s try to set equal values as true and false. If keep_equal is true, the result also keeps values that are equal. Otherwise, equal values are shown as NaNs. By default it is set to False. Python3 # Keep the equal valuesfirst_df.compare(second_df, keep_equal=True) Output: Python3 # Keep the equal values Falsefirst_df.compare(second_df, keep_equal=False) Output: Step 5: Let’s now check the keep_shape which is by default false. If it is set to true then, all the rows and columns are present in the table, or else only the ones with distinct values are kept. Python3 #Keep all original rows and columnsfirst_df.compare(second_df,keep_shape=True) Output: Python3 #Keep all original rows and columns and #also all original valuesfirst_df.compare(second_df,keep_shape=True, keep_equal=True) Output: Here the keep_shape true will keep the structure and will set all the unchanged values to nan. Whereas, the keep_shape and keep_equal true will keep the whole structure of the table as well as also the values which are not changed Note: Before comparing two DataFrames make sure that the number of records in the first DataFrame matches the number of records in the second DataFrame. If not so, you will be getting a value error which is : ValueError: Can only compare identically-labeled Series objects Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Iterate over a list in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Nov, 2020" }, { "code": null, "e": 273, "s": 28, "text": "A DataFrame is a 2D structure composed of rows and columns, and where data is stored into a tubular form. It is mutable in terms of size, and heterogeneous tabular data. Arithmetic operations can also be performed on both row and column labels." }, { "code": null, "e": 326, "s": 273, "text": "To know more about the creation of Pandas DataFrame." }, { "code": null, "e": 405, "s": 326, "text": "Here, we will see how to compare two DataFrames with pandas.DataFrame.compare." }, { "code": null, "e": 413, "s": 405, "text": "Syntax:" }, { "code": null, "e": 488, "s": 413, "text": "DataFrame.compare(other, align_axis=1, keep_shape=False, keep_equal=False)" }, { "code": null, "e": 534, "s": 488, "text": "So, let’s understand each of its parameters –" }, { "code": null, "e": 1322, "s": 534, "text": "other : This is the first parameter which actually takes the DataFrame object to be compared with the present DataFrame.align_axis : It deals with the axis(vertical / horizontal) where the comparison is to be made(by default False).0 or index : Here the output of the differences are presented vertically, 1 or columns : The output of the differences are displayed horizontally.keep_shape : It means that whether we want all the data values to be displayed in the output or only the ones with distinct value. It is of bool type and the default value for it is β€œfalse”, i.e. it displays all the values in the table by default.keep_equal : This is mainly for displaying same or equal values in the output when set to True. If it is made false then it will display the equal values as NANs." }, { "code": null, "e": 1443, "s": 1322, "text": "other : This is the first parameter which actually takes the DataFrame object to be compared with the present DataFrame." }, { "code": null, "e": 1702, "s": 1443, "text": "align_axis : It deals with the axis(vertical / horizontal) where the comparison is to be made(by default False).0 or index : Here the output of the differences are presented vertically, 1 or columns : The output of the differences are displayed horizontally." }, { "code": null, "e": 1950, "s": 1702, "text": "keep_shape : It means that whether we want all the data values to be displayed in the output or only the ones with distinct value. It is of bool type and the default value for it is β€œfalse”, i.e. it displays all the values in the table by default." }, { "code": null, "e": 2113, "s": 1950, "text": "keep_equal : This is mainly for displaying same or equal values in the output when set to True. If it is made false then it will display the equal values as NANs." }, { "code": null, "e": 2188, "s": 2113, "text": "Returns another DataFrame with the differences between the two dataFrames." }, { "code": null, "e": 2269, "s": 2188, "text": "Before Starting, an important note is the pandas version must be at least 1.1.0." }, { "code": null, "e": 2332, "s": 2269, "text": "To check that, run this on your cmd or Anaconda navigator cmd." }, { "code": null, "e": 2376, "s": 2332, "text": "import pandas as pd\nprint(pd.__version__)\n\n" }, { "code": null, "e": 2624, "s": 2376, "text": "If it is 1.1.0 or greater than that, you are good to go! Otherwise, you can install pandas compatible version by the command into your window cmd by running as an administrator, or otherwise into your Anaconda navigator if it is added to the path." }, { "code": null, "e": 2764, "s": 2624, "text": "# if you want the latest version available\npip install pandas --upgrade\n\n# or if you want to specify the version\npip install pandas==1.1.0\n" }, { "code": null, "e": 2780, "s": 2764, "text": "Implementation:" }, { "code": null, "e": 2824, "s": 2780, "text": "Step 1: we will create our first dataframe." }, { "code": null, "e": 2834, "s": 2824, "text": "Approach:" }, { "code": null, "e": 3106, "s": 2834, "text": "Import pandas for DataFrameImport NumPy for any NAN values which can come up through operations or insertCreate the DataFrames using pandas.DataFrame and passing the value for your rows, columnsSpecify the column headings(from the value you have passed in the dictionary)" }, { "code": null, "e": 3134, "s": 3106, "text": "Import pandas for DataFrame" }, { "code": null, "e": 3213, "s": 3134, "text": "Import NumPy for any NAN values which can come up through operations or insert" }, { "code": null, "e": 3303, "s": 3213, "text": "Create the DataFrames using pandas.DataFrame and passing the value for your rows, columns" }, { "code": null, "e": 3381, "s": 3303, "text": "Specify the column headings(from the value you have passed in the dictionary)" }, { "code": null, "e": 3389, "s": 3381, "text": "Python3" }, { "code": "# pandas version == 1.1.0 (min)import pandas as pdimport numpy as np # create your first DataFrame# using pd.DataFramefirst_df = pd.DataFrame( { \"Stationary\": [\"Pens\", \"Scales\", \"Pencils\", \"Geometry Box\", \"Crayon Set\"], \"Price\": [100, 50, 25, 100, 65], \"Quantity\": [10, 5, 5, 2, 1] }, columns=[\"Stationary\", \"Price\", \"Quantity\"],)# Display the dffirst_df", "e": 3819, "s": 3389, "text": null }, { "code": null, "e": 3827, "s": 3819, "text": "Output:" }, { "code": null, "e": 3901, "s": 3827, "text": "Step 2:Now, let’s make out the next DataFrame for comparing their values:" }, { "code": null, "e": 3909, "s": 3901, "text": "Python3" }, { "code": "# creating the second dataFrame by # copying and modifying the first DataFramesecond_df = first_df.copy() # loc specifies the location,# here 0th index of Price Columnsecond_df.loc[0, 'Price'] = 150 second_df.loc[1, 'Price'] = 70second_df.loc[2, 'Price'] = 30second_df.loc[0, 'Quantity'] = 15second_df.loc[1, 'Quantity'] = 7second_df.loc[2, 'Quantity'] = 6 # display the dfsecond_df", "e": 4294, "s": 3909, "text": null }, { "code": null, "e": 4302, "s": 4294, "text": "Output:" }, { "code": null, "e": 4470, "s": 4302, "text": "We are creating another DataFrame by copying the table structure of the first_DataFrame with certain modifications. Now, let’s see the content of the second_DataFrame " }, { "code": null, "e": 4518, "s": 4470, "text": "Step 3: let us do our main operation – compare." }, { "code": null, "e": 4739, "s": 4518, "text": "Here we have performed two operations, firstly to align the differences of the changes in the columns, for which the align_axis by default is set to 1 and table will be with columns drawn alternately from self and other." }, { "code": null, "e": 4747, "s": 4739, "text": "Python3" }, { "code": "#Align the differences on the columnsfirst_df.compare(second_df)", "e": 4812, "s": 4747, "text": null }, { "code": null, "e": 4820, "s": 4812, "text": "Output:" }, { "code": null, "e": 4932, "s": 4820, "text": "And secondly, we have set the align_axis = 0 which makes the table rows drawn alternately from self and others." }, { "code": null, "e": 4940, "s": 4932, "text": "Python3" }, { "code": "# align the differences on rowsfirst_df.compare(second_df,align_axis=0)", "e": 5012, "s": 4940, "text": null }, { "code": null, "e": 5020, "s": 5012, "text": "Output:" }, { "code": null, "e": 5077, "s": 5020, "text": "Step 4: let’s try to set equal values as true and false." }, { "code": null, "e": 5219, "s": 5077, "text": "If keep_equal is true, the result also keeps values that are equal. Otherwise, equal values are shown as NaNs. By default it is set to False." }, { "code": null, "e": 5227, "s": 5219, "text": "Python3" }, { "code": "# Keep the equal valuesfirst_df.compare(second_df, keep_equal=True)", "e": 5295, "s": 5227, "text": null }, { "code": null, "e": 5303, "s": 5295, "text": "Output:" }, { "code": null, "e": 5311, "s": 5303, "text": "Python3" }, { "code": "# Keep the equal values Falsefirst_df.compare(second_df, keep_equal=False)", "e": 5386, "s": 5311, "text": null }, { "code": null, "e": 5394, "s": 5386, "text": "Output:" }, { "code": null, "e": 5591, "s": 5394, "text": "Step 5: Let’s now check the keep_shape which is by default false. If it is set to true then, all the rows and columns are present in the table, or else only the ones with distinct values are kept." }, { "code": null, "e": 5599, "s": 5591, "text": "Python3" }, { "code": "#Keep all original rows and columnsfirst_df.compare(second_df,keep_shape=True)", "e": 5678, "s": 5599, "text": null }, { "code": null, "e": 5686, "s": 5678, "text": "Output:" }, { "code": null, "e": 5694, "s": 5686, "text": "Python3" }, { "code": "#Keep all original rows and columns and #also all original valuesfirst_df.compare(second_df,keep_shape=True, keep_equal=True) ", "e": 5821, "s": 5694, "text": null }, { "code": null, "e": 5829, "s": 5821, "text": "Output:" }, { "code": null, "e": 6060, "s": 5829, "text": "Here the keep_shape true will keep the structure and will set all the unchanged values to nan. Whereas, the keep_shape and keep_equal true will keep the whole structure of the table as well as also the values which are not changed" }, { "code": null, "e": 6271, "s": 6060, "text": "Note: Before comparing two DataFrames make sure that the number of records in the first DataFrame matches the number of records in the second DataFrame. If not so, you will be getting a value error which is : " }, { "code": null, "e": 6335, "s": 6271, "text": "ValueError: Can only compare identically-labeled Series objects" }, { "code": null, "e": 6359, "s": 6335, "text": "Python pandas-dataFrame" }, { "code": null, "e": 6373, "s": 6359, "text": "Python-pandas" }, { "code": null, "e": 6380, "s": 6373, "text": "Python" }, { "code": null, "e": 6478, "s": 6380, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6496, "s": 6478, "text": "Python Dictionary" }, { "code": null, "e": 6538, "s": 6496, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 6560, "s": 6538, "text": "Enumerate() in Python" }, { "code": null, "e": 6595, "s": 6560, "text": "Read a file line by line in Python" }, { "code": null, "e": 6627, "s": 6595, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 6656, "s": 6627, "text": "*args and **kwargs in Python" }, { "code": null, "e": 6683, "s": 6656, "text": "Python Classes and Objects" }, { "code": null, "e": 6704, "s": 6683, "text": "Python OOPs Concepts" }, { "code": null, "e": 6727, "s": 6704, "text": "Introduction To PYTHON" } ]
What is a Pointer to a Null pointer
16 Jun, 2022 NULL pointer in C At the very high level, we can think of NULL as a null pointer which is used in C for various purposes. Some of the most common use cases for NULL are To initialize a pointer variable when that pointer variable isn’t assigned any valid memory address yet. To initialize a pointer variable when that pointer variable isn’t assigned any valid memory address yet. C int* pInt = NULL; To check for a null pointer before accessing any pointer variable. By doing so, we can perform error handling in pointer related code e.g. dereference pointer variable only if it’s not NULL. To check for a null pointer before accessing any pointer variable. By doing so, we can perform error handling in pointer related code e.g. dereference pointer variable only if it’s not NULL. C if (pInt != NULL) /*We could use if(pInt) as well*/{ /*Some code*/}else { /*Some code*/} To pass a null pointer to a function argument when we don’t want to pass any valid memory address. To pass a null pointer to a function argument when we don’t want to pass any valid memory address. C int fun(int* ptr){ /*Fun specific stuff is done with ptr here*/ return 10;}fun(NULL); Pointer to a Null Pointer As Null pointer always points to null, one would think that Pointer to a Null Pointer is invalid and won’t be compiled by the compiler. But it is not the case. Consider the following example: C++ C #include <iostream>using namespace std; int main(){ // Null pointer char* np = NULL; // Pointer to null pointer char** pnp = &np; if (*pnp == NULL) { cout << "Pointer to a null pointer is valid" << endl; } else { cout << "Pointer to a null pointer is invalid" << endl; } return 0;} // This code is contributed by sarajadhav12052009 #include <stdio.h> int main(){ // Null pointer char* np = NULL; // Pointer to null pointer char** pnp = &np; if (*pnp == NULL) { printf("Pointer to a null pointer is valid\n"); } else { printf("Pointer to a null pointer is invalid\n"); } return 0;} Not only this program compiles but executes successfully to give the output as Output: Pointer to a null pointer is valid Explanation: What happens here is that when a Null pointer is created, it points to null, without any doubt. But the variable of Null pointer takes some memory. Hence when a pointer to a null pointer is created, it points to an actual memory space, which in turn points to null. Hence Pointer to a null pointer is not only valid but important concept. sarajadhav12052009 Advanced Pointer C-Advanced Pointer C-Pointer Basics C-Pointers cpp-double-pointer cpp-pointer pointer Pointers C Programs Pointers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Header files in C/C++ and its uses C Program to read contents of Whole File How to return multiple values from a function in C or C++? C++ Program to check Prime Number Producer Consumer Problem in C C Program to Swap two Numbers How to Append a Character to a String in C C program to sort an array in ascending order Program to find Prime Numbers Between given Interval Set, Clear and Toggle a given bit of a number in C
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Jun, 2022" }, { "code": null, "e": 223, "s": 54, "text": "NULL pointer in C At the very high level, we can think of NULL as a null pointer which is used in C for various purposes. Some of the most common use cases for NULL are" }, { "code": null, "e": 329, "s": 223, "text": "To initialize a pointer variable when that pointer variable isn’t assigned any valid memory address yet. " }, { "code": null, "e": 435, "s": 329, "text": "To initialize a pointer variable when that pointer variable isn’t assigned any valid memory address yet. " }, { "code": null, "e": 437, "s": 435, "text": "C" }, { "code": "int* pInt = NULL;", "e": 455, "s": 437, "text": null }, { "code": null, "e": 647, "s": 455, "text": "To check for a null pointer before accessing any pointer variable. By doing so, we can perform error handling in pointer related code e.g. dereference pointer variable only if it’s not NULL. " }, { "code": null, "e": 839, "s": 647, "text": "To check for a null pointer before accessing any pointer variable. By doing so, we can perform error handling in pointer related code e.g. dereference pointer variable only if it’s not NULL. " }, { "code": null, "e": 841, "s": 839, "text": "C" }, { "code": "if (pInt != NULL) /*We could use if(pInt) as well*/{ /*Some code*/}else { /*Some code*/}", "e": 930, "s": 841, "text": null }, { "code": null, "e": 1030, "s": 930, "text": "To pass a null pointer to a function argument when we don’t want to pass any valid memory address. " }, { "code": null, "e": 1130, "s": 1030, "text": "To pass a null pointer to a function argument when we don’t want to pass any valid memory address. " }, { "code": null, "e": 1132, "s": 1130, "text": "C" }, { "code": "int fun(int* ptr){ /*Fun specific stuff is done with ptr here*/ return 10;}fun(NULL);", "e": 1224, "s": 1132, "text": null }, { "code": null, "e": 1443, "s": 1224, "text": "Pointer to a Null Pointer As Null pointer always points to null, one would think that Pointer to a Null Pointer is invalid and won’t be compiled by the compiler. But it is not the case. Consider the following example: " }, { "code": null, "e": 1447, "s": 1443, "text": "C++" }, { "code": null, "e": 1449, "s": 1447, "text": "C" }, { "code": "#include <iostream>using namespace std; int main(){ // Null pointer char* np = NULL; // Pointer to null pointer char** pnp = &np; if (*pnp == NULL) { cout << \"Pointer to a null pointer is valid\" << endl; } else { cout << \"Pointer to a null pointer is invalid\" << endl; } return 0;} // This code is contributed by sarajadhav12052009", "e": 1826, "s": 1449, "text": null }, { "code": "#include <stdio.h> int main(){ // Null pointer char* np = NULL; // Pointer to null pointer char** pnp = &np; if (*pnp == NULL) { printf(\"Pointer to a null pointer is valid\\n\"); } else { printf(\"Pointer to a null pointer is invalid\\n\"); } return 0;}", "e": 2120, "s": 1826, "text": null }, { "code": null, "e": 2207, "s": 2120, "text": "Not only this program compiles but executes successfully to give the output as Output:" }, { "code": null, "e": 2242, "s": 2207, "text": "Pointer to a null pointer is valid" }, { "code": null, "e": 2594, "s": 2242, "text": "Explanation: What happens here is that when a Null pointer is created, it points to null, without any doubt. But the variable of Null pointer takes some memory. Hence when a pointer to a null pointer is created, it points to an actual memory space, which in turn points to null. Hence Pointer to a null pointer is not only valid but important concept." }, { "code": null, "e": 2613, "s": 2594, "text": "sarajadhav12052009" }, { "code": null, "e": 2630, "s": 2613, "text": "Advanced Pointer" }, { "code": null, "e": 2649, "s": 2630, "text": "C-Advanced Pointer" }, { "code": null, "e": 2666, "s": 2649, "text": "C-Pointer Basics" }, { "code": null, "e": 2677, "s": 2666, "text": "C-Pointers" }, { "code": null, "e": 2696, "s": 2677, "text": "cpp-double-pointer" }, { "code": null, "e": 2708, "s": 2696, "text": "cpp-pointer" }, { "code": null, "e": 2716, "s": 2708, "text": "pointer" }, { "code": null, "e": 2725, "s": 2716, "text": "Pointers" }, { "code": null, "e": 2736, "s": 2725, "text": "C Programs" }, { "code": null, "e": 2745, "s": 2736, "text": "Pointers" }, { "code": null, "e": 2843, "s": 2745, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2878, "s": 2843, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 2919, "s": 2878, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 2978, "s": 2919, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 3012, "s": 2978, "text": "C++ Program to check Prime Number" }, { "code": null, "e": 3043, "s": 3012, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 3073, "s": 3043, "text": "C Program to Swap two Numbers" }, { "code": null, "e": 3116, "s": 3073, "text": "How to Append a Character to a String in C" }, { "code": null, "e": 3162, "s": 3116, "text": "C program to sort an array in ascending order" }, { "code": null, "e": 3215, "s": 3162, "text": "Program to find Prime Numbers Between given Interval" } ]
Sum of the nodes of a Singly Linked List
26 Oct, 2021 Given a singly linked list. The task is to find the sum of nodes of the given linked list. Task is to do A + B + C + D. Examples: Input: 7->6->8->4->1 Output: 26 Sum of nodes: 7 + 6 + 8 + 4 + 1 = 26 Input: 1->7->3->9->11->5 Output: 36 Recursive Solution: Call a function by passing the head and variable to store the sum.Then recursively call the function by passing the next of current node and sum variable.Add the value of the current node to the sum. Then recursively call the function by passing the next of current node and sum variable.Add the value of the current node to the sum. Add the value of the current node to the sum. Below is the implementation of above approach: C++ Java Python3 C# Javascript // C++ implementation to find the sum of// nodes of the Linked List#include <bits/stdc++.h>using namespace std; /* A Linked list node */struct Node { int data; struct Node* next;}; // function to insert a node at the// beginning of the linked listvoid push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = new Node; /* put in the data */ new_node->data = new_data; /* link the old list to the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // function to recursively find the sum of// nodes of the given linked listvoid sumOfNodes(struct Node* head, int* sum){ // if head = NULL if (!head) return; // recursively traverse the remaining nodes sumOfNodes(head->next, sum); // accumulate sum *sum = *sum + head->data;} // utility function to find the sum of nodesint sumOfNodesUtil(struct Node* head){ int sum = 0; // find the sum of nodes sumOfNodes(head, &sum); // required sum return sum;} // Driver program to test aboveint main(){ struct Node* head = NULL; // create linked list 7->6->8->4->1 push(&head, 7); push(&head, 6); push(&head, 8); push(&head, 4); push(&head, 1); cout << "Sum of nodes = " << sumOfNodesUtil(head); return 0;} // Java implementation to find the sum of // nodes of the Linked List class GFG { static int sum=0; // A Linked list node /static class Node{ int data; Node next; } // function to insert a node at the // beginning of the linked list static Node push( Node head_ref, int new_data) { // allocate node / Node new_node = new Node(); // put in the data / new_node.data = new_data; // link the old list to the new node / new_node.next = (head_ref); // move the head to point to the new node / (head_ref) = new_node; return head_ref;} // function to recursively find the sum of // nodes of the given linked list static void sumOfNodes( Node head) { // if head = null if (head == null) return; // recursively traverse the remaining nodes sumOfNodes(head.next); // accumulate sum sum = sum + head.data; } // utility function to find the sum of nodes static int sumOfNodesUtil( Node head) { sum = 0; // find the sum of nodes sumOfNodes(head); // required sum return sum; } // Driver program to test above public static void main(String args[]){ Node head = null; // create linked list 7.6.8.4.1 head = push(head, 7); head = push(head, 6); head = push(head, 8); head = push(head, 4); head = push(head, 1); System.out.println( "Sum of nodes = " + sumOfNodesUtil(head)); } } // This code is contributed by Arnab Kundu # Python3 implementation to find the sum of # nodes of the Linked List import math # class for a Sumclass Sum: tsum = None # A Linked list node class Node: def __init__(self,data): self.data = data self.next = None # function to insert a node at the # beginning of the linked list def push(head, data): if not head: return Node(data) # put in the data # and allocate node new_node = Node(data) # link the old list to the new node new_node.next = head # move the head to point # to the new node head = new_node return head # function to recursively find # the sum of nodes of the given# linked list def sumOfNode(head, S): # if head = NULL if not head: return # recursively traverse the # remaining nodes sumOfNode(head.next, S) # accumulate sum S.tsum += head.data # utility function to find # the sum of nodesdef sumOfNodesUtil(head): S = Sum() S.tsum = 0 # find the sum of nodes sumOfNode(head, S) # required sum return S.tsum # Driver Codeif __name__=='__main__': head = None # create linked list 7->6->8->4->1 head = push(head, 7) head = push(head, 6) head = push(head, 8) head = push(head, 4) head = push(head, 1) print("Sum of Nodes = {}" . format(sumOfNodesUtil(head))) # This code is contributed # by Vikash Kumar 37 // C# implementation to find the sum of // nodes of the Linked List using System; class GFG { public static int sum = 0; // A Linked list node / public class Node { public int data; public Node next; } // function to insert a node at the // beginning of the linked list static Node push(Node head_ref, int new_data) { // allocate node / Node new_node = new Node(); // put in the data / new_node.data = new_data; // link the old list to the new node / new_node.next = (head_ref); // move the head to point to the new node / (head_ref) = new_node; return head_ref; } // function to recursively find the sum of // nodes of the given linked list static void sumOfNodes(Node head) { // if head = null if (head == null) return; // recursively traverse the remaining nodes sumOfNodes(head.next); // accumulate sum sum = sum + head.data; } // utility function to find the sum of nodes static int sumOfNodesUtil(Node head) { sum = 0; // find the sum of nodes sumOfNodes(head); // required sum return sum; } // Driver program to test above public static void Main(String[] args) { Node head = null; // create linked list 7.6.8.4.1 head = push(head, 7); head = push(head, 6); head = push(head, 8); head = push(head, 4); head = push(head, 1); Console.WriteLine("Sum of nodes = " + sumOfNodesUtil(head)); } } // This code is contributed by Rajput-Ji <script> // JavaScript implementation to find the sum of // nodes of the Linked List var sum = 0; // A Linked list node /class Node { constructor(val) { this.data = val; this.next = null; }} // function to insert a node at the // beginning of the linked list function push(head_ref , new_data) { // allocate node / var new_node = new Node(); // put in the data / new_node.data = new_data; // link the old list to the new node / new_node.next = (head_ref); // move the head to point to the new node / (head_ref) = new_node; return head_ref; } // function to recursively find the sum of // nodes of the given linked list function sumOfNodes(head) { // if head = null if (head == null) return; // recursively traverse the remaining nodes sumOfNodes(head.next); // accumulate sum sum = sum + head.data; } // utility function to find the sum of nodes function sumOfNodesUtil(head) { sum = 0; // find the sum of nodes sumOfNodes(head); // required sum return sum; } // Driver program to test above var head = null; // create linked list 7.6.8.4.1 head = push(head, 7); head = push(head, 6); head = push(head, 8); head = push(head, 4); head = push(head, 1); document.write("Sum of nodes = " + sumOfNodesUtil(head)); // This code contributed by umadevi9616 </script> Sum of nodes = 26 Time Complexity: O(N) , N is the number of nodes in a linked list. Auxiliary Space: O(N), only if the stack size is considered during recursive calls.Iterative Solution: Initialize a pointer ptr with the head of the linked list and a sum variable with 0.Start traversing the linked list using a loop until all the nodes get traversed.Add the value of current node to the sum i.e. sum += ptr -> data .Increment the pointer to the next node of linked list i.e. ptr = ptr ->next .Return the sum. Initialize a pointer ptr with the head of the linked list and a sum variable with 0. Start traversing the linked list using a loop until all the nodes get traversed.Add the value of current node to the sum i.e. sum += ptr -> data .Increment the pointer to the next node of linked list i.e. ptr = ptr ->next . Add the value of current node to the sum i.e. sum += ptr -> data . Increment the pointer to the next node of linked list i.e. ptr = ptr ->next . Return the sum. Below is the implementation of above approach: C++ Java Python3 C# Javascript // C++ implementation to find the sum of// nodes of the Linked List#include <bits/stdc++.h>using namespace std; /* A Linked list node */struct Node { int data; struct Node* next;}; // function to insert a node at the// beginning of the linked listvoid push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = new Node; /* put in the data */ new_node->data = new_data; /* link the old list to the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // function to find the sum of// nodes of the given linked listint sumOfNodes(struct Node* head){ struct Node* ptr = head; int sum = 0; while (ptr != NULL) { sum += ptr->data; ptr = ptr->next; } return sum;} // Driver program to test aboveint main(){ struct Node* head = NULL; // create linked list 7->6->8->4->1 push(&head, 7); push(&head, 6); push(&head, 8); push(&head, 4); push(&head, 1); cout << "Sum of nodes = " << sumOfNodes(head); return 0;} // Java implementation to find the sum of// nodes of the Linked List class GFG { static Node head; /* A Linked list node */static class Node{ int data; Node next;}; // function to insert a node at the// beginning of the linked list// Inserting node at the beginningstatic Node push(Node head_ref, int new_data){ /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list to the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; return head=head_ref;} // function to find the sum of// nodes of the given linked liststatic int sumOfNodes( Node head){ Node ptr = head; int sum = 0; while (ptr != null) { sum += ptr.data; ptr = ptr.next; } return sum;} // Driver codepublic static void main(String[] args){ // create linked list 7.6.8.4.1 push(head, 7); push(head, 6); push(head, 8); push(head, 4); push(head, 1); System.out.println("Sum of nodes = " + sumOfNodes(head));}} /* This code is contributed by PrinciRaj1992 */ # Python3 implementation to find the # sum of nodes of the Linked Listimport math # A Linked list node class Node: def __init__(self, data): self.data = data self.next = None # function to insert a node at the# beginning of the linked listdef push(head_ref, new_data): # allocate node new_node = Node(new_data) # put in the data new_node.data = new_data # link the old list to the new node new_node.next = head_ref # move the head to po to the new node head_ref = new_node return head_ref # function to find the sum of# nodes of the given linked listdef sumOfNodes(head): ptr = head sum = 0 while (ptr != None): sum = sum + ptr.data ptr = ptr.next return sum # Driver Codeif __name__=='__main__': head = None # create linked list 7.6.8.4.1 head = push(head, 7) head = push(head, 6) head = push(head, 8) head = push(head, 4) head = push(head, 1) print("Sum of nodes =", sumOfNodes(head)) # This code is contributed by Srathore // C# implementation to find the sum of // nodes of the Linked List using System; class GFG { static Node head; /* A Linked list node */public class Node { public int data; public Node next; }; // function to insert a node at the // beginning of the linked list // Inserting node at the beginning static Node push(Node head_ref, int new_data) { /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list to the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; return head=head_ref; } // function to find the sum of // nodes of the given linked list static int sumOfNodes( Node head) { Node ptr = head; int sum = 0; while (ptr != null) { sum += ptr.data; ptr = ptr.next; } return sum; } // Driver code public static void Main(String[] args) { // create linked list 7.6.8.4.1 push(head, 7); push(head, 6); push(head, 8); push(head, 4); push(head, 1); Console.WriteLine("Sum of nodes = " + sumOfNodes(head)); } } // This code is contributed by 29AjayKumar <script>// javascript implementation to find the sum of// nodes of the Linked List var head; /* A Linked list node */ class Node { constructor() { this.data = 0; this.next = null; } } // function to insert a node at the // beginning of the linked list // Inserting node at the beginning function push(head_ref , new_data) { /* allocate node */var new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list to the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; return head = head_ref; } // function to find the sum of // nodes of the given linked list function sumOfNodes(head) {var ptr = head; var sum = 0; while (ptr != null) { sum += ptr.data; ptr = ptr.next; } return sum; } // Driver code // create linked list 7.6.8.4.1 push(head, 7); push(head, 6); push(head, 8); push(head, 4); push(head, 1); document.write("Sum of nodes = " + sumOfNodes(head)); // This code contributed by aashish1995</script> Sum of nodes = 26 Time Complexity: O(N), N is the number of nodes in a linked list. Auxiliary Space: O(1) andrew1234 Vikash Kumar 37 Rajput-Ji princiraj1992 29AjayKumar sapnasingh4991 aashish1995 umadevi9616 simranarora5sos Algorithms-Recursion Data Structures-Linked List Traversal Linked List Linked List Traversal Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures What is Data Structure: Types, Classifications and Applications Implementing a Linked List in Java using Class Find Length of a Linked List (Iterative and Recursive) Queue - Linked List Implementation Function to check if a singly linked list is palindrome Write a function to get the intersection point of two Linked Lists Remove duplicates from an unsorted linked list Circular Linked List | Set 1 (Introduction and Applications) Implement a stack using singly linked list
[ { "code": null, "e": 54, "s": 26, "text": "\n26 Oct, 2021" }, { "code": null, "e": 146, "s": 54, "text": "Given a singly linked list. The task is to find the sum of nodes of the given linked list. " }, { "code": null, "e": 175, "s": 146, "text": "Task is to do A + B + C + D." }, { "code": null, "e": 187, "s": 175, "text": "Examples: " }, { "code": null, "e": 293, "s": 187, "text": "Input: 7->6->8->4->1\nOutput: 26\nSum of nodes:\n7 + 6 + 8 + 4 + 1 = 26\n\nInput: 1->7->3->9->11->5\nOutput: 36" }, { "code": null, "e": 317, "s": 295, "text": "Recursive Solution: " }, { "code": null, "e": 517, "s": 317, "text": "Call a function by passing the head and variable to store the sum.Then recursively call the function by passing the next of current node and sum variable.Add the value of the current node to the sum." }, { "code": null, "e": 651, "s": 517, "text": "Then recursively call the function by passing the next of current node and sum variable.Add the value of the current node to the sum." }, { "code": null, "e": 697, "s": 651, "text": "Add the value of the current node to the sum." }, { "code": null, "e": 746, "s": 697, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 750, "s": 746, "text": "C++" }, { "code": null, "e": 755, "s": 750, "text": "Java" }, { "code": null, "e": 763, "s": 755, "text": "Python3" }, { "code": null, "e": 766, "s": 763, "text": "C#" }, { "code": null, "e": 777, "s": 766, "text": "Javascript" }, { "code": "// C++ implementation to find the sum of// nodes of the Linked List#include <bits/stdc++.h>using namespace std; /* A Linked list node */struct Node { int data; struct Node* next;}; // function to insert a node at the// beginning of the linked listvoid push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = new Node; /* put in the data */ new_node->data = new_data; /* link the old list to the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // function to recursively find the sum of// nodes of the given linked listvoid sumOfNodes(struct Node* head, int* sum){ // if head = NULL if (!head) return; // recursively traverse the remaining nodes sumOfNodes(head->next, sum); // accumulate sum *sum = *sum + head->data;} // utility function to find the sum of nodesint sumOfNodesUtil(struct Node* head){ int sum = 0; // find the sum of nodes sumOfNodes(head, &sum); // required sum return sum;} // Driver program to test aboveint main(){ struct Node* head = NULL; // create linked list 7->6->8->4->1 push(&head, 7); push(&head, 6); push(&head, 8); push(&head, 4); push(&head, 1); cout << \"Sum of nodes = \" << sumOfNodesUtil(head); return 0;}", "e": 2145, "s": 777, "text": null }, { "code": "// Java implementation to find the sum of // nodes of the Linked List class GFG { static int sum=0; // A Linked list node /static class Node{ int data; Node next; } // function to insert a node at the // beginning of the linked list static Node push( Node head_ref, int new_data) { // allocate node / Node new_node = new Node(); // put in the data / new_node.data = new_data; // link the old list to the new node / new_node.next = (head_ref); // move the head to point to the new node / (head_ref) = new_node; return head_ref;} // function to recursively find the sum of // nodes of the given linked list static void sumOfNodes( Node head) { // if head = null if (head == null) return; // recursively traverse the remaining nodes sumOfNodes(head.next); // accumulate sum sum = sum + head.data; } // utility function to find the sum of nodes static int sumOfNodesUtil( Node head) { sum = 0; // find the sum of nodes sumOfNodes(head); // required sum return sum; } // Driver program to test above public static void main(String args[]){ Node head = null; // create linked list 7.6.8.4.1 head = push(head, 7); head = push(head, 6); head = push(head, 8); head = push(head, 4); head = push(head, 1); System.out.println( \"Sum of nodes = \" + sumOfNodesUtil(head)); } } // This code is contributed by Arnab Kundu", "e": 3620, "s": 2145, "text": null }, { "code": "# Python3 implementation to find the sum of # nodes of the Linked List import math # class for a Sumclass Sum: tsum = None # A Linked list node class Node: def __init__(self,data): self.data = data self.next = None # function to insert a node at the # beginning of the linked list def push(head, data): if not head: return Node(data) # put in the data # and allocate node new_node = Node(data) # link the old list to the new node new_node.next = head # move the head to point # to the new node head = new_node return head # function to recursively find # the sum of nodes of the given# linked list def sumOfNode(head, S): # if head = NULL if not head: return # recursively traverse the # remaining nodes sumOfNode(head.next, S) # accumulate sum S.tsum += head.data # utility function to find # the sum of nodesdef sumOfNodesUtil(head): S = Sum() S.tsum = 0 # find the sum of nodes sumOfNode(head, S) # required sum return S.tsum # Driver Codeif __name__=='__main__': head = None # create linked list 7->6->8->4->1 head = push(head, 7) head = push(head, 6) head = push(head, 8) head = push(head, 4) head = push(head, 1) print(\"Sum of Nodes = {}\" . format(sumOfNodesUtil(head))) # This code is contributed # by Vikash Kumar 37", "e": 5036, "s": 3620, "text": null }, { "code": "// C# implementation to find the sum of // nodes of the Linked List using System; class GFG { public static int sum = 0; // A Linked list node / public class Node { public int data; public Node next; } // function to insert a node at the // beginning of the linked list static Node push(Node head_ref, int new_data) { // allocate node / Node new_node = new Node(); // put in the data / new_node.data = new_data; // link the old list to the new node / new_node.next = (head_ref); // move the head to point to the new node / (head_ref) = new_node; return head_ref; } // function to recursively find the sum of // nodes of the given linked list static void sumOfNodes(Node head) { // if head = null if (head == null) return; // recursively traverse the remaining nodes sumOfNodes(head.next); // accumulate sum sum = sum + head.data; } // utility function to find the sum of nodes static int sumOfNodesUtil(Node head) { sum = 0; // find the sum of nodes sumOfNodes(head); // required sum return sum; } // Driver program to test above public static void Main(String[] args) { Node head = null; // create linked list 7.6.8.4.1 head = push(head, 7); head = push(head, 6); head = push(head, 8); head = push(head, 4); head = push(head, 1); Console.WriteLine(\"Sum of nodes = \" + sumOfNodesUtil(head)); } } // This code is contributed by Rajput-Ji", "e": 6834, "s": 5036, "text": null }, { "code": "<script> // JavaScript implementation to find the sum of // nodes of the Linked List var sum = 0; // A Linked list node /class Node { constructor(val) { this.data = val; this.next = null; }} // function to insert a node at the // beginning of the linked list function push(head_ref , new_data) { // allocate node / var new_node = new Node(); // put in the data / new_node.data = new_data; // link the old list to the new node / new_node.next = (head_ref); // move the head to point to the new node / (head_ref) = new_node; return head_ref; } // function to recursively find the sum of // nodes of the given linked list function sumOfNodes(head) { // if head = null if (head == null) return; // recursively traverse the remaining nodes sumOfNodes(head.next); // accumulate sum sum = sum + head.data; } // utility function to find the sum of nodes function sumOfNodesUtil(head) { sum = 0; // find the sum of nodes sumOfNodes(head); // required sum return sum; } // Driver program to test above var head = null; // create linked list 7.6.8.4.1 head = push(head, 7); head = push(head, 6); head = push(head, 8); head = push(head, 4); head = push(head, 1); document.write(\"Sum of nodes = \" + sumOfNodesUtil(head)); // This code contributed by umadevi9616 </script>", "e": 8408, "s": 6834, "text": null }, { "code": null, "e": 8426, "s": 8408, "text": "Sum of nodes = 26" }, { "code": null, "e": 8600, "s": 8428, "text": "Time Complexity: O(N) , N is the number of nodes in a linked list. Auxiliary Space: O(N), only if the stack size is considered during recursive calls.Iterative Solution: " }, { "code": null, "e": 8923, "s": 8600, "text": "Initialize a pointer ptr with the head of the linked list and a sum variable with 0.Start traversing the linked list using a loop until all the nodes get traversed.Add the value of current node to the sum i.e. sum += ptr -> data .Increment the pointer to the next node of linked list i.e. ptr = ptr ->next .Return the sum." }, { "code": null, "e": 9008, "s": 8923, "text": "Initialize a pointer ptr with the head of the linked list and a sum variable with 0." }, { "code": null, "e": 9232, "s": 9008, "text": "Start traversing the linked list using a loop until all the nodes get traversed.Add the value of current node to the sum i.e. sum += ptr -> data .Increment the pointer to the next node of linked list i.e. ptr = ptr ->next ." }, { "code": null, "e": 9299, "s": 9232, "text": "Add the value of current node to the sum i.e. sum += ptr -> data ." }, { "code": null, "e": 9377, "s": 9299, "text": "Increment the pointer to the next node of linked list i.e. ptr = ptr ->next ." }, { "code": null, "e": 9393, "s": 9377, "text": "Return the sum." }, { "code": null, "e": 9442, "s": 9393, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 9446, "s": 9442, "text": "C++" }, { "code": null, "e": 9451, "s": 9446, "text": "Java" }, { "code": null, "e": 9459, "s": 9451, "text": "Python3" }, { "code": null, "e": 9462, "s": 9459, "text": "C#" }, { "code": null, "e": 9473, "s": 9462, "text": "Javascript" }, { "code": "// C++ implementation to find the sum of// nodes of the Linked List#include <bits/stdc++.h>using namespace std; /* A Linked list node */struct Node { int data; struct Node* next;}; // function to insert a node at the// beginning of the linked listvoid push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = new Node; /* put in the data */ new_node->data = new_data; /* link the old list to the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // function to find the sum of// nodes of the given linked listint sumOfNodes(struct Node* head){ struct Node* ptr = head; int sum = 0; while (ptr != NULL) { sum += ptr->data; ptr = ptr->next; } return sum;} // Driver program to test aboveint main(){ struct Node* head = NULL; // create linked list 7->6->8->4->1 push(&head, 7); push(&head, 6); push(&head, 8); push(&head, 4); push(&head, 1); cout << \"Sum of nodes = \" << sumOfNodes(head); return 0;}", "e": 10575, "s": 9473, "text": null }, { "code": "// Java implementation to find the sum of// nodes of the Linked List class GFG { static Node head; /* A Linked list node */static class Node{ int data; Node next;}; // function to insert a node at the// beginning of the linked list// Inserting node at the beginningstatic Node push(Node head_ref, int new_data){ /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list to the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; return head=head_ref;} // function to find the sum of// nodes of the given linked liststatic int sumOfNodes( Node head){ Node ptr = head; int sum = 0; while (ptr != null) { sum += ptr.data; ptr = ptr.next; } return sum;} // Driver codepublic static void main(String[] args){ // create linked list 7.6.8.4.1 push(head, 7); push(head, 6); push(head, 8); push(head, 4); push(head, 1); System.out.println(\"Sum of nodes = \" + sumOfNodes(head));}} /* This code is contributed by PrinciRaj1992 */", "e": 11731, "s": 10575, "text": null }, { "code": "# Python3 implementation to find the # sum of nodes of the Linked Listimport math # A Linked list node class Node: def __init__(self, data): self.data = data self.next = None # function to insert a node at the# beginning of the linked listdef push(head_ref, new_data): # allocate node new_node = Node(new_data) # put in the data new_node.data = new_data # link the old list to the new node new_node.next = head_ref # move the head to po to the new node head_ref = new_node return head_ref # function to find the sum of# nodes of the given linked listdef sumOfNodes(head): ptr = head sum = 0 while (ptr != None): sum = sum + ptr.data ptr = ptr.next return sum # Driver Codeif __name__=='__main__': head = None # create linked list 7.6.8.4.1 head = push(head, 7) head = push(head, 6) head = push(head, 8) head = push(head, 4) head = push(head, 1) print(\"Sum of nodes =\", sumOfNodes(head)) # This code is contributed by Srathore", "e": 12803, "s": 11731, "text": null }, { "code": "// C# implementation to find the sum of // nodes of the Linked List using System; class GFG { static Node head; /* A Linked list node */public class Node { public int data; public Node next; }; // function to insert a node at the // beginning of the linked list // Inserting node at the beginning static Node push(Node head_ref, int new_data) { /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list to the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; return head=head_ref; } // function to find the sum of // nodes of the given linked list static int sumOfNodes( Node head) { Node ptr = head; int sum = 0; while (ptr != null) { sum += ptr.data; ptr = ptr.next; } return sum; } // Driver code public static void Main(String[] args) { // create linked list 7.6.8.4.1 push(head, 7); push(head, 6); push(head, 8); push(head, 4); push(head, 1); Console.WriteLine(\"Sum of nodes = \" + sumOfNodes(head)); } } // This code is contributed by 29AjayKumar", "e": 14021, "s": 12803, "text": null }, { "code": "<script>// javascript implementation to find the sum of// nodes of the Linked List var head; /* A Linked list node */ class Node { constructor() { this.data = 0; this.next = null; } } // function to insert a node at the // beginning of the linked list // Inserting node at the beginning function push(head_ref , new_data) { /* allocate node */var new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list to the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; return head = head_ref; } // function to find the sum of // nodes of the given linked list function sumOfNodes(head) {var ptr = head; var sum = 0; while (ptr != null) { sum += ptr.data; ptr = ptr.next; } return sum; } // Driver code // create linked list 7.6.8.4.1 push(head, 7); push(head, 6); push(head, 8); push(head, 4); push(head, 1); document.write(\"Sum of nodes = \" + sumOfNodes(head)); // This code contributed by aashish1995</script>", "e": 15278, "s": 14021, "text": null }, { "code": null, "e": 15296, "s": 15278, "text": "Sum of nodes = 26" }, { "code": null, "e": 15387, "s": 15298, "text": "Time Complexity: O(N), N is the number of nodes in a linked list. Auxiliary Space: O(1) " }, { "code": null, "e": 15398, "s": 15387, "text": "andrew1234" }, { "code": null, "e": 15414, "s": 15398, "text": "Vikash Kumar 37" }, { "code": null, "e": 15424, "s": 15414, "text": "Rajput-Ji" }, { "code": null, "e": 15438, "s": 15424, "text": "princiraj1992" }, { "code": null, "e": 15450, "s": 15438, "text": "29AjayKumar" }, { "code": null, "e": 15465, "s": 15450, "text": "sapnasingh4991" }, { "code": null, "e": 15477, "s": 15465, "text": "aashish1995" }, { "code": null, "e": 15489, "s": 15477, "text": "umadevi9616" }, { "code": null, "e": 15505, "s": 15489, "text": "simranarora5sos" }, { "code": null, "e": 15526, "s": 15505, "text": "Algorithms-Recursion" }, { "code": null, "e": 15554, "s": 15526, "text": "Data Structures-Linked List" }, { "code": null, "e": 15564, "s": 15554, "text": "Traversal" }, { "code": null, "e": 15576, "s": 15564, "text": "Linked List" }, { "code": null, "e": 15588, "s": 15576, "text": "Linked List" }, { "code": null, "e": 15598, "s": 15588, "text": "Traversal" }, { "code": null, "e": 15696, "s": 15598, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 15728, "s": 15696, "text": "Introduction to Data Structures" }, { "code": null, "e": 15792, "s": 15728, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 15839, "s": 15792, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 15894, "s": 15839, "text": "Find Length of a Linked List (Iterative and Recursive)" }, { "code": null, "e": 15929, "s": 15894, "text": "Queue - Linked List Implementation" }, { "code": null, "e": 15985, "s": 15929, "text": "Function to check if a singly linked list is palindrome" }, { "code": null, "e": 16052, "s": 15985, "text": "Write a function to get the intersection point of two Linked Lists" }, { "code": null, "e": 16099, "s": 16052, "text": "Remove duplicates from an unsorted linked list" }, { "code": null, "e": 16160, "s": 16099, "text": "Circular Linked List | Set 1 (Introduction and Applications)" } ]
DAX Time Intelligence - DATEADD function
Returns a table that contains a column of dates, shifted either forward or backward in time by the specified number of intervals from the dates in the current context. DATEADD (<dates>, <number_of_intervals>, <interval>) dates A column that contains dates. number_of_intervals A column that contains dates. interval The interval by which to shift the dates. The value for interval can be one of the following βˆ’ Year Quarter Month Day A table containing a single column of date values. The dates parameter can be any of the following βˆ’ A reference to a date/time column. A reference to a date/time column. A table expression that returns a single column of date/time values. A table expression that returns a single column of date/time values. A Boolean expression that defines a single-column table of date/time values. A Boolean expression that defines a single-column table of date/time values. Constraints on Boolean expressions βˆ’ The expression cannot reference a calculated field. The expression cannot reference a calculated field. The expression cannot use CALCULATE function. The expression cannot use CALCULATE function. The expression cannot use any function that scans a table or returns a table, including aggregation functions. The expression cannot use any function that scans a table or returns a table, including aggregation functions. However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value. If the number specified for number_of_intervals parameter is positive, the dates are moved forward in time. If the number is negative, the dates are shifted back in time. The interval parameter is an enumeration, not a set of strings. Hence, the values for interval should not be enclosed in quotation marks. Also, the values: year, quarter, month, day should be spelled in full when using them. The result table includes only dates that are specified in the dates parameter. = DATEADD (ProductInventory[InventoryDate],1, YEAR) 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": 2169, "s": 2001, "text": "Returns a table that contains a column of dates, shifted either forward or backward in time by the specified number of intervals from the dates in the current context." }, { "code": null, "e": 2224, "s": 2169, "text": "DATEADD (<dates>, <number_of_intervals>, <interval>) \n" }, { "code": null, "e": 2230, "s": 2224, "text": "dates" }, { "code": null, "e": 2260, "s": 2230, "text": "A column that contains dates." }, { "code": null, "e": 2280, "s": 2260, "text": "number_of_intervals" }, { "code": null, "e": 2310, "s": 2280, "text": "A column that contains dates." }, { "code": null, "e": 2319, "s": 2310, "text": "interval" }, { "code": null, "e": 2361, "s": 2319, "text": "The interval by which to shift the dates." }, { "code": null, "e": 2414, "s": 2361, "text": "The value for interval can be one of the following βˆ’" }, { "code": null, "e": 2419, "s": 2414, "text": "Year" }, { "code": null, "e": 2427, "s": 2419, "text": "Quarter" }, { "code": null, "e": 2433, "s": 2427, "text": "Month" }, { "code": null, "e": 2437, "s": 2433, "text": "Day" }, { "code": null, "e": 2488, "s": 2437, "text": "A table containing a single column of date values." }, { "code": null, "e": 2538, "s": 2488, "text": "The dates parameter can be any of the following βˆ’" }, { "code": null, "e": 2573, "s": 2538, "text": "A reference to a date/time column." }, { "code": null, "e": 2608, "s": 2573, "text": "A reference to a date/time column." }, { "code": null, "e": 2677, "s": 2608, "text": "A table expression that returns a single column of date/time values." }, { "code": null, "e": 2746, "s": 2677, "text": "A table expression that returns a single column of date/time values." }, { "code": null, "e": 2823, "s": 2746, "text": "A Boolean expression that defines a single-column table of date/time values." }, { "code": null, "e": 2900, "s": 2823, "text": "A Boolean expression that defines a single-column table of date/time values." }, { "code": null, "e": 2937, "s": 2900, "text": "Constraints on Boolean expressions βˆ’" }, { "code": null, "e": 2989, "s": 2937, "text": "The expression cannot reference a calculated field." }, { "code": null, "e": 3041, "s": 2989, "text": "The expression cannot reference a calculated field." }, { "code": null, "e": 3087, "s": 3041, "text": "The expression cannot use CALCULATE function." }, { "code": null, "e": 3133, "s": 3087, "text": "The expression cannot use CALCULATE function." }, { "code": null, "e": 3244, "s": 3133, "text": "The expression cannot use any function that scans a table or returns a table, including aggregation functions." }, { "code": null, "e": 3355, "s": 3244, "text": "The expression cannot use any function that scans a table or returns a table, including aggregation functions." }, { "code": null, "e": 3471, "s": 3355, "text": "However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value." }, { "code": null, "e": 3642, "s": 3471, "text": "If the number specified for number_of_intervals parameter is positive, the dates are moved forward in time. If the number is negative, the dates are shifted back in time." }, { "code": null, "e": 3867, "s": 3642, "text": "The interval parameter is an enumeration, not a set of strings. Hence, the values for interval should not be enclosed in quotation marks. Also, the values: year, quarter, month, day should be spelled in full when using them." }, { "code": null, "e": 3947, "s": 3867, "text": "The result table includes only dates that are specified in the dates parameter." }, { "code": null, "e": 4000, "s": 3947, "text": "= DATEADD (ProductInventory[InventoryDate],1, YEAR) " }, { "code": null, "e": 4035, "s": 4000, "text": "\n 53 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4049, "s": 4035, "text": " Abhay Gadiya" }, { "code": null, "e": 4082, "s": 4049, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 4096, "s": 4082, "text": " Randy Minder" }, { "code": null, "e": 4131, "s": 4096, "text": "\n 26 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4145, "s": 4131, "text": " Randy Minder" }, { "code": null, "e": 4152, "s": 4145, "text": " Print" }, { "code": null, "e": 4163, "s": 4152, "text": " Add Notes" } ]
Convert a data frame with grouping column into a list based on groups in R.
To convert a data frame with grouping column into a list based on groups, we can use split function. For Example, if we have a data frame called df that contains a categorical column say Group and a numerical column say DV then we can convert df into a list based on groups in Group column by using the command as mentioned below βˆ’ split(df$DV,df1$Group). Following snippet creates a sample data frame βˆ’ Group<-sample(LETTERS[1:5],20,replace=TRUE) Response_var<-rpois(20,5) df1<-data.frame(Group,Response_var) df1 The following dataframe is created Group Response_var 1 B 4 2 E 3 3 C 9 4 D 4 5 C 5 6 A 4 7 B 5 8 D 9 9 E 4 10 A 5 11 C 2 12 B 11 13 E 5 14 E 6 15 D 1 16 B 4 17 E 2 18 B 2 19 D 4 20 A 7 To split the df1 into a list based on Group column on the above created data frame, add the following code to the above snippet βˆ’ Group<-sample(LETTERS[1:5],20,replace=TRUE) Response_var<-rpois(20,5) df1<-data.frame(Group,Response_var) split(df1$Response_var,df1$Group) $A If you execute all the above given snippets as a single program, it generates the following Output βˆ’ [1] 4 5 7 To split the df1 into a list based on Group column on the above created data frame, add the following code to the above snippet βˆ’ Group<-sample(LETTERS[1:5],20,replace=TRUE) Response_var<-rpois(20,5) df1<-data.frame(Group,Response_var) split(df1$Response_var,df1$Group) $B If you execute all the above given snippets as a single program, it generates the following Output βˆ’ [1] 4 5 11 4 2 To split the df1 into a list based on Group column on the above created data frame, add the following code to the above snippet βˆ’ Group<-sample(LETTERS[1:5],20,replace=TRUE) Response_var<-rpois(20,5) df1<-data.frame(Group,Response_var) split(df1$Response_var,df1$Group) $C If you execute all the above given snippets as a single program, it generates the following Output βˆ’ [1] 9 5 2 To split the df1 into a list based on Group column on the above created data frame, add the following code to the above snippet βˆ’ Group<-sample(LETTERS[1:5],20,replace=TRUE) Response_var<-rpois(20,5) df1<-data.frame(Group,Response_var) split(df1$Response_var,df1$Group) $D If you execute all the above given snippets as a single program, it generates the following Output βˆ’ [1] 4 9 1 4 To split the df1 into a list based on Group column on the above created data frame, add the following code to the above snippet βˆ’ Group<-sample(LETTERS[1:5],20,replace=TRUE) Response_var<-rpois(20,5) df1<-data.frame(Group,Response_var) split(df1$Response_var,df1$Group) $E If you execute all the above given snippets as a single program, it generates the following Output βˆ’ [1] 3 4 5 6 2 Following snippet creates a sample data frame βˆ’ Class<-sample(c("First","Second","Third","Fourth","Fifth"),20,replace=TRUE) Score<-sample(1:10,20,replace=TRUE) df2<-data.frame(Class,Score) df2 The following dataframe is created Class Score 1 Third 6 2 Second 2 3 Fourth 3 4 Fifth 2 5 Second 3 6 Fifth 6 7 Fourth 2 8 First 4 9 Third 10 10 Third 5 11 Third 4 12 First 2 13 Third 6 14 Third 5 15 First 1 16 Fourth 4 17 Second 8 18 First 8 19 Second 7 20 Third 10 To split the df2 into a list based on Class column on the above created data frame, add the following code to the above snippet βˆ’ Class<-sample(c("First","Second","Third","Fourth","Fifth"),20,replace=TRUE) Score<-sample(1:10,20,replace=TRUE) df2<-data.frame(Class,Score) split(df2$Score,df2$Class) $Fifth If you execute all the above given snippets as a single program, it generates the following Output βˆ’ [1] 2 6 To split the df2 into a list based on Class column on the above created data frame, add the following code to the above snippet βˆ’ Class<-sample(c("First","Second","Third","Fourth","Fifth"),20,replace=TRUE) Score<-sample(1:10,20,replace=TRUE) df2<-data.frame(Class,Score) split(df2$Score,df2$Class) $First If you execute all the above given snippets as a single program, it generates the following Output βˆ’ [1] 4 2 1 8 To split the df2 into a list based on Class column on the above created data frame, add the following code to the above snippet βˆ’ Class<-sample(c("First","Second","Third","Fourth","Fifth"),20,replace=TRUE) Score<-sample(1:10,20,replace=TRUE) df2<-data.frame(Class,Score) split(df2$Score,df2$Class) $Fourth If you execute all the above given snippets as a single program, it generates the following Output βˆ’ [1] 3 2 4 To split the df2 into a list based on Class column on the above created data frame, add the following code to the above snippet βˆ’ Class<-sample(c("First","Second","Third","Fourth","Fifth"),20,replace=TRUE) Score<-sample(1:10,20,replace=TRUE) df2<-data.frame(Class,Score) split(df2$Score,df2$Class) $Second If you execute all the above given snippets as a single program, it generates the following Output βˆ’ [1] 2 3 8 7 To split the df2 into a list based on Class column on the above created data frame, add the following code to the above snippet βˆ’ Class<-sample(c("First","Second","Third","Fourth","Fifth"),20,replace=TRUE) Score<-sample(1:10,20,replace=TRUE) df2<-data.frame(Class,Score) split(df2$Score,df2$Class) $Third If you execute all the above given snippets as a single program, it generates the following Output βˆ’ [1] 6 10 5 4 6 5 10
[ { "code": null, "e": 1163, "s": 1062, "text": "To convert a data frame with grouping column into a list based on groups, we can use\nsplit function." }, { "code": null, "e": 1394, "s": 1163, "text": "For Example, if we have a data frame called df that contains a categorical column say\nGroup and a numerical column say DV then we can convert df into a list based on groups\nin Group column by using the command as mentioned below βˆ’" }, { "code": null, "e": 1418, "s": 1394, "text": "split(df$DV,df1$Group)." }, { "code": null, "e": 1466, "s": 1418, "text": "Following snippet creates a sample data frame βˆ’" }, { "code": null, "e": 1576, "s": 1466, "text": "Group<-sample(LETTERS[1:5],20,replace=TRUE)\nResponse_var<-rpois(20,5)\ndf1<-data.frame(Group,Response_var)\ndf1" }, { "code": null, "e": 1611, "s": 1576, "text": "The following dataframe is created" }, { "code": null, "e": 2032, "s": 1611, "text": " Group Response_var\n1 B 4\n2 E 3\n3 C 9\n4 D 4\n5 C 5\n6 A 4\n7 B 5\n8 D 9\n9 E 4\n10 A 5\n11 C 2\n12 B 11\n13 E 5\n14 E 6\n15 D 1\n16 B 4\n17 E 2\n18 B 2\n19 D 4\n20 A 7" }, { "code": null, "e": 2162, "s": 2032, "text": "To split the df1 into a list based on Group column on the above created data frame, add\nthe following code to the above snippet βˆ’" }, { "code": null, "e": 2306, "s": 2162, "text": "Group<-sample(LETTERS[1:5],20,replace=TRUE)\nResponse_var<-rpois(20,5)\ndf1<-data.frame(Group,Response_var)\nsplit(df1$Response_var,df1$Group)\n$A\n" }, { "code": null, "e": 2407, "s": 2306, "text": "If you execute all the above given snippets as a single program, it generates the\nfollowing Output βˆ’" }, { "code": null, "e": 2417, "s": 2407, "text": "[1] 4 5 7" }, { "code": null, "e": 2547, "s": 2417, "text": "To split the df1 into a list based on Group column on the above created data frame, add\nthe following code to the above snippet βˆ’" }, { "code": null, "e": 2690, "s": 2547, "text": "Group<-sample(LETTERS[1:5],20,replace=TRUE)\nResponse_var<-rpois(20,5)\ndf1<-data.frame(Group,Response_var)\nsplit(df1$Response_var,df1$Group)\n$B" }, { "code": null, "e": 2791, "s": 2690, "text": "If you execute all the above given snippets as a single program, it generates the\nfollowing Output βˆ’" }, { "code": null, "e": 2807, "s": 2791, "text": "[1] 4 5 11 4 2\n" }, { "code": null, "e": 2937, "s": 2807, "text": "To split the df1 into a list based on Group column on the above created data frame, add\nthe following code to the above snippet βˆ’" }, { "code": null, "e": 3081, "s": 2937, "text": "Group<-sample(LETTERS[1:5],20,replace=TRUE)\nResponse_var<-rpois(20,5)\ndf1<-data.frame(Group,Response_var)\nsplit(df1$Response_var,df1$Group)\n$C\n" }, { "code": null, "e": 3182, "s": 3081, "text": "If you execute all the above given snippets as a single program, it generates the\nfollowing Output βˆ’" }, { "code": null, "e": 3192, "s": 3182, "text": "[1] 9 5 2" }, { "code": null, "e": 3322, "s": 3192, "text": "To split the df1 into a list based on Group column on the above created data frame, add\nthe following code to the above snippet βˆ’" }, { "code": null, "e": 3466, "s": 3322, "text": "Group<-sample(LETTERS[1:5],20,replace=TRUE)\nResponse_var<-rpois(20,5)\ndf1<-data.frame(Group,Response_var)\nsplit(df1$Response_var,df1$Group)\n$D\n" }, { "code": null, "e": 3567, "s": 3466, "text": "If you execute all the above given snippets as a single program, it generates the\nfollowing Output βˆ’" }, { "code": null, "e": 3579, "s": 3567, "text": "[1] 4 9 1 4" }, { "code": null, "e": 3709, "s": 3579, "text": "To split the df1 into a list based on Group column on the above created data frame, add\nthe following code to the above snippet βˆ’" }, { "code": null, "e": 3853, "s": 3709, "text": "Group<-sample(LETTERS[1:5],20,replace=TRUE)\nResponse_var<-rpois(20,5)\ndf1<-data.frame(Group,Response_var)\nsplit(df1$Response_var,df1$Group)\n$E\n" }, { "code": null, "e": 3954, "s": 3853, "text": "If you execute all the above given snippets as a single program, it generates the\nfollowing Output βˆ’" }, { "code": null, "e": 3968, "s": 3954, "text": "[1] 3 4 5 6 2" }, { "code": null, "e": 4016, "s": 3968, "text": "Following snippet creates a sample data frame βˆ’" }, { "code": null, "e": 4162, "s": 4016, "text": "Class<-sample(c(\"First\",\"Second\",\"Third\",\"Fourth\",\"Fifth\"),20,replace=TRUE)\nScore<-sample(1:10,20,replace=TRUE)\ndf2<-data.frame(Class,Score)\ndf2\n" }, { "code": null, "e": 4197, "s": 4162, "text": "The following dataframe is created" }, { "code": null, "e": 4533, "s": 4197, "text": " Class Score\n1 Third 6\n2 Second 2\n3 Fourth 3\n4 Fifth 2\n5 Second 3\n6 Fifth 6\n7 Fourth 2\n8 First 4\n9 Third 10\n10 Third 5\n11 Third 4\n12 First 2\n13 Third 6\n14 Third 5\n15 First 1\n16 Fourth 4\n17 Second 8\n18 First 8\n19 Second 7\n20 Third 10" }, { "code": null, "e": 4663, "s": 4533, "text": "To split the df2 into a list based on Class column on the above created data frame, add\nthe following code to the above snippet βˆ’" }, { "code": null, "e": 4839, "s": 4663, "text": "Class<-sample(c(\"First\",\"Second\",\"Third\",\"Fourth\",\"Fifth\"),20,replace=TRUE)\nScore<-sample(1:10,20,replace=TRUE)\ndf2<-data.frame(Class,Score)\nsplit(df2$Score,df2$Class)\n$Fifth\n" }, { "code": null, "e": 4940, "s": 4839, "text": "If you execute all the above given snippets as a single program, it generates the\nfollowing Output βˆ’" }, { "code": null, "e": 4948, "s": 4940, "text": "[1] 2 6" }, { "code": null, "e": 5078, "s": 4948, "text": "To split the df2 into a list based on Class column on the above created data frame, add\nthe following code to the above snippet βˆ’" }, { "code": null, "e": 5254, "s": 5078, "text": "Class<-sample(c(\"First\",\"Second\",\"Third\",\"Fourth\",\"Fifth\"),20,replace=TRUE)\nScore<-sample(1:10,20,replace=TRUE)\ndf2<-data.frame(Class,Score)\nsplit(df2$Score,df2$Class)\n$First\n" }, { "code": null, "e": 5355, "s": 5254, "text": "If you execute all the above given snippets as a single program, it generates the\nfollowing Output βˆ’" }, { "code": null, "e": 5367, "s": 5355, "text": "[1] 4 2 1 8" }, { "code": null, "e": 5497, "s": 5367, "text": "To split the df2 into a list based on Class column on the above created data frame, add\nthe following code to the above snippet βˆ’" }, { "code": null, "e": 5673, "s": 5497, "text": "Class<-sample(c(\"First\",\"Second\",\"Third\",\"Fourth\",\"Fifth\"),20,replace=TRUE)\nScore<-sample(1:10,20,replace=TRUE)\ndf2<-data.frame(Class,Score)\nsplit(df2$Score,df2$Class)\n$Fourth" }, { "code": null, "e": 5774, "s": 5673, "text": "If you execute all the above given snippets as a single program, it generates the\nfollowing Output βˆ’" }, { "code": null, "e": 5785, "s": 5774, "text": "[1] 3 2 4\n" }, { "code": null, "e": 5915, "s": 5785, "text": "To split the df2 into a list based on Class column on the above created data frame, add\nthe following code to the above snippet βˆ’" }, { "code": null, "e": 6092, "s": 5915, "text": "Class<-sample(c(\"First\",\"Second\",\"Third\",\"Fourth\",\"Fifth\"),20,replace=TRUE)\nScore<-sample(1:10,20,replace=TRUE)\ndf2<-data.frame(Class,Score)\nsplit(df2$Score,df2$Class)\n$Second\n" }, { "code": null, "e": 6193, "s": 6092, "text": "If you execute all the above given snippets as a single program, it generates the\nfollowing Output βˆ’" }, { "code": null, "e": 6205, "s": 6193, "text": "[1] 2 3 8 7" }, { "code": null, "e": 6335, "s": 6205, "text": "To split the df2 into a list based on Class column on the above created data frame, add\nthe following code to the above snippet βˆ’" }, { "code": null, "e": 6511, "s": 6335, "text": "Class<-sample(c(\"First\",\"Second\",\"Third\",\"Fourth\",\"Fifth\"),20,replace=TRUE)\nScore<-sample(1:10,20,replace=TRUE)\ndf2<-data.frame(Class,Score)\nsplit(df2$Score,df2$Class)\n$Third\n" }, { "code": null, "e": 6612, "s": 6511, "text": "If you execute all the above given snippets as a single program, it generates the\nfollowing Output βˆ’" }, { "code": null, "e": 6632, "s": 6612, "text": "[1] 6 10 5 4 6 5 10" } ]
HTML DOM customElements define() Method - GeeksforGeeks
14 Jul, 2020 The customElements define() method is used to define a new custom element. There are two types of custom elements that can be created: Autonomous custom element: These elements do not inherit from built-in HTML elements. Customized built-in element: These elements inherit from built-in HTML elements. Syntax: customElements.define( name, constructor, options ); Parameters: name: It specifies the name for the new custom element. The name of custom elements must contain hyphen. constructor: It specifies the constructor for the new custom element. options: It specifies the object that controls how the element is defined. It is an optional parameter. Return value: This method returns void. Example: In this example, a custom element is defined, named <gfg-custom-element> with a constructor named CustomEl using this method. HTML <!DOCTYPE HTML><html> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <p> HTML | customElements define() method </p> <button onclick="Geeks();"> click here </button> <p id="arr"></p> <script> var arr = document.getElementById("arr"); // Function to define the element function Geeks() { class CustomEl extends HTMLElement { constructor() { super(); this.attachShadow({ mode: 'open' }); this.shadowRoot.innerHTML = ` <h1 style="color:green;"> GeeksforGeeks Custom Element Data </h1> `; } } // Use the define() method to define // a new element window.customElements.define( 'gfg-custom-element', CustomEl); } </script> <gfg-custom-element></gfg-custom-element></body> </html> Output: Before Clicking the Button: Before Clicking the Button: After Clicking the Button: After Clicking the Button: Supported Browsers: Google Chrome 66.0 Edge 79.0 Firefox 63.0 Safari 10.1 Opera 53.0 Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-DOM HTML-Methods HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML Design a web page using HTML and CSS Form validation using jQuery Angular File Upload Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript?
[ { "code": null, "e": 26139, "s": 26111, "text": "\n14 Jul, 2020" }, { "code": null, "e": 26274, "s": 26139, "text": "The customElements define() method is used to define a new custom element. There are two types of custom elements that can be created:" }, { "code": null, "e": 26360, "s": 26274, "text": "Autonomous custom element: These elements do not inherit from built-in HTML elements." }, { "code": null, "e": 26441, "s": 26360, "text": "Customized built-in element: These elements inherit from built-in HTML elements." }, { "code": null, "e": 26449, "s": 26441, "text": "Syntax:" }, { "code": null, "e": 26502, "s": 26449, "text": "customElements.define( name, constructor, options );" }, { "code": null, "e": 26514, "s": 26502, "text": "Parameters:" }, { "code": null, "e": 26619, "s": 26514, "text": "name: It specifies the name for the new custom element. The name of custom elements must contain hyphen." }, { "code": null, "e": 26689, "s": 26619, "text": "constructor: It specifies the constructor for the new custom element." }, { "code": null, "e": 26793, "s": 26689, "text": "options: It specifies the object that controls how the element is defined. It is an optional parameter." }, { "code": null, "e": 26833, "s": 26793, "text": "Return value: This method returns void." }, { "code": null, "e": 26968, "s": 26833, "text": "Example: In this example, a custom element is defined, named <gfg-custom-element> with a constructor named CustomEl using this method." }, { "code": null, "e": 26973, "s": 26968, "text": "HTML" }, { "code": "<!DOCTYPE HTML><html> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <p> HTML | customElements define() method </p> <button onclick=\"Geeks();\"> click here </button> <p id=\"arr\"></p> <script> var arr = document.getElementById(\"arr\"); // Function to define the element function Geeks() { class CustomEl extends HTMLElement { constructor() { super(); this.attachShadow({ mode: 'open' }); this.shadowRoot.innerHTML = ` <h1 style=\"color:green;\"> GeeksforGeeks Custom Element Data </h1> `; } } // Use the define() method to define // a new element window.customElements.define( 'gfg-custom-element', CustomEl); } </script> <gfg-custom-element></gfg-custom-element></body> </html>", "e": 28003, "s": 26973, "text": null }, { "code": null, "e": 28011, "s": 28003, "text": "Output:" }, { "code": null, "e": 28039, "s": 28011, "text": "Before Clicking the Button:" }, { "code": null, "e": 28067, "s": 28039, "text": "Before Clicking the Button:" }, { "code": null, "e": 28094, "s": 28067, "text": "After Clicking the Button:" }, { "code": null, "e": 28121, "s": 28094, "text": "After Clicking the Button:" }, { "code": null, "e": 28141, "s": 28121, "text": "Supported Browsers:" }, { "code": null, "e": 28160, "s": 28141, "text": "Google Chrome 66.0" }, { "code": null, "e": 28170, "s": 28160, "text": "Edge 79.0" }, { "code": null, "e": 28183, "s": 28170, "text": "Firefox 63.0" }, { "code": null, "e": 28195, "s": 28183, "text": "Safari 10.1" }, { "code": null, "e": 28206, "s": 28195, "text": "Opera 53.0" }, { "code": null, "e": 28343, "s": 28206, "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": 28352, "s": 28343, "text": "HTML-DOM" }, { "code": null, "e": 28365, "s": 28352, "text": "HTML-Methods" }, { "code": null, "e": 28370, "s": 28365, "text": "HTML" }, { "code": null, "e": 28381, "s": 28370, "text": "JavaScript" }, { "code": null, "e": 28398, "s": 28381, "text": "Web Technologies" }, { "code": null, "e": 28403, "s": 28398, "text": "HTML" }, { "code": null, "e": 28501, "s": 28403, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28525, "s": 28501, "text": "REST API (Introduction)" }, { "code": null, "e": 28566, "s": 28525, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 28603, "s": 28566, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28632, "s": 28603, "text": "Form validation using jQuery" }, { "code": null, "e": 28652, "s": 28632, "text": "Angular File Upload" }, { "code": null, "e": 28692, "s": 28652, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28737, "s": 28692, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28798, "s": 28737, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28870, "s": 28798, "text": "Differences between Functional Components and Class Components in React" } ]
Automatic Birthday mail sending with Python - GeeksforGeeks
25 Jan, 2022 Are you bored with sending birthday wishes to your friends or do you forget to send wishes to your friends or do you want to wish them at 12 AM but you always fall asleep? Why not automate this simple task by writing a Python script. The first thing we do is import six libraries: pandas datetime smtplib time requests win10toast Apart from this, Also create an Excel sheet for containing records like this: Name, Email, Contact, Birthday, and Year. Approach: For the sending email part, We define a sendEmail() function which will start a Gmail session, send the email, and quit the session. For the SMS part, we must have an account on www.fast2sms.com from where we will get an API key. This API key is used to send SMS over mobile numbers using your account on fast2sms then We create a sendsms() function which will verify the API key and send SMS. In the driver code section, we read the data from Excel sheet and match today’s date with any of the birthdays. If there is a match, we call the sendEmail() and sendsms() functions and also we add the current year in the Excel sheet. Also, we have used ToastNotifier from win10toast library to show desktop notifications once the e-mail and SMS has been sent successfully. Below is the implementation: Python # import required packagesimport pandas as pdimport datetimeimport smtplibimport timeimport requestsfrom win10toast import ToastNotifier # your gmail credentials hereGMAIL_ID = 'your_email_here'GMAIL_PWD = 'your_password_here' # for desktop notificationtoast = ToastNotifier() # define a function for sending emaildef sendEmail(to, sub, msg): # connection to gmail gmail_obj = smtplib.SMTP('smtp.gmail.com', 587) # starting the session gmail_obj.starttls() # login using credentials gmail_obj.login(GMAIL_ID, GMAIL_PWD) # sending email gmail_obj.sendmail(GMAIL_ID, to, f"Subject : {sub}\n\n{msg}") # quit the session gmail_obj.quit() print("Email sent to " + str(to) + " with subject " + str(sub) + " and message :" + str(msg)) toast.show_toast("Email Sent!" , f"{name} was sent e-mail", threaded = True, icon_path = None, duration = 6) while toast.notification_active(): time.sleep(0.1) # define a function for sending sms def sendsms(to, msg, name, sub): url = "https://www.fast2sms.com/dev/bulk" payload = f"sender_id=FSTSMS&message={msg}&language=english&route=p&numbers={to}" headers = { 'authorization': "API_KEY_HERE", 'Content-Type': "application/x-www-form-urlencoded", 'Cache-Control': "no-cache", } response_obj = requests.request("POST", url, data = payload, headers = headers) print(response_obj.text) print("SMS sent to " + str(to) + " with subject :" + str(sub) + " and message :" + str(msg)) toast.show_toast("SMS Sent!" , f"{name} was sent message", threaded = True, icon_path = None, duration = 6) while toast.notification_active(): time.sleep(0.1) # driver codeif __name__=="__main__": # read the excel sheet having all the details dataframe = pd.read_excel("excelsheet.xlsx") # today date in format : DD-MM today = datetime.datetime.now().strftime("%d-%m") # current year in format : YY yearNow = datetime.datetime.now().strftime("%Y") # writeindex list writeInd = [] for index,item in dataframe.iterrows(): msg = "Many Many Happy Returns of the day dear " + str(item['NAME']) # stripping the birthday in excel # sheet as : DD-MM bday = item['Birthday'].strftime("%d-%m") # condition checking if (today == bday) and yearNow not in str(item['Year']): # calling the sendEmail function sendEmail(item['Email'], "Happy Birthday", msg) # calling the sendsms function sendsms(item['Contact'], msg, item['NAME'], "Happy Birthday") writeInd.append(index) for i in writeInd: yr = dataframe.loc[i,'Year'] # this will record the years in which # email has been sent dataframe.loc[i,'Year'] = str(yr) + ',' + str(yearNow) dataframe.to_excel('excelsheet.xlsx', index = False) sumitgumber28 sagartomar9927 Python-projects python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Create a Pandas DataFrame from Lists Check if element exists in list in Python How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 26211, "s": 26183, "text": "\n25 Jan, 2022" }, { "code": null, "e": 26445, "s": 26211, "text": "Are you bored with sending birthday wishes to your friends or do you forget to send wishes to your friends or do you want to wish them at 12 AM but you always fall asleep? Why not automate this simple task by writing a Python script." }, { "code": null, "e": 26493, "s": 26445, "text": "The first thing we do is import six libraries: " }, { "code": null, "e": 26500, "s": 26493, "text": "pandas" }, { "code": null, "e": 26509, "s": 26500, "text": "datetime" }, { "code": null, "e": 26517, "s": 26509, "text": "smtplib" }, { "code": null, "e": 26522, "s": 26517, "text": "time" }, { "code": null, "e": 26531, "s": 26522, "text": "requests" }, { "code": null, "e": 26542, "s": 26531, "text": "win10toast" }, { "code": null, "e": 26663, "s": 26542, "text": "Apart from this, Also create an Excel sheet for containing records like this: Name, Email, Contact, Birthday, and Year. " }, { "code": null, "e": 26673, "s": 26663, "text": "Approach:" }, { "code": null, "e": 26806, "s": 26673, "text": "For the sending email part, We define a sendEmail() function which will start a Gmail session, send the email, and quit the session." }, { "code": null, "e": 27067, "s": 26806, "text": "For the SMS part, we must have an account on www.fast2sms.com from where we will get an API key. This API key is used to send SMS over mobile numbers using your account on fast2sms then We create a sendsms() function which will verify the API key and send SMS." }, { "code": null, "e": 27440, "s": 27067, "text": "In the driver code section, we read the data from Excel sheet and match today’s date with any of the birthdays. If there is a match, we call the sendEmail() and sendsms() functions and also we add the current year in the Excel sheet. Also, we have used ToastNotifier from win10toast library to show desktop notifications once the e-mail and SMS has been sent successfully." }, { "code": null, "e": 27469, "s": 27440, "text": "Below is the implementation:" }, { "code": null, "e": 27476, "s": 27469, "text": "Python" }, { "code": "# import required packagesimport pandas as pdimport datetimeimport smtplibimport timeimport requestsfrom win10toast import ToastNotifier # your gmail credentials hereGMAIL_ID = 'your_email_here'GMAIL_PWD = 'your_password_here' # for desktop notificationtoast = ToastNotifier() # define a function for sending emaildef sendEmail(to, sub, msg): # connection to gmail gmail_obj = smtplib.SMTP('smtp.gmail.com', 587) # starting the session gmail_obj.starttls() # login using credentials gmail_obj.login(GMAIL_ID, GMAIL_PWD) # sending email gmail_obj.sendmail(GMAIL_ID, to, f\"Subject : {sub}\\n\\n{msg}\") # quit the session gmail_obj.quit() print(\"Email sent to \" + str(to) + \" with subject \" + str(sub) + \" and message :\" + str(msg)) toast.show_toast(\"Email Sent!\" , f\"{name} was sent e-mail\", threaded = True, icon_path = None, duration = 6) while toast.notification_active(): time.sleep(0.1) # define a function for sending sms def sendsms(to, msg, name, sub): url = \"https://www.fast2sms.com/dev/bulk\" payload = f\"sender_id=FSTSMS&message={msg}&language=english&route=p&numbers={to}\" headers = { 'authorization': \"API_KEY_HERE\", 'Content-Type': \"application/x-www-form-urlencoded\", 'Cache-Control': \"no-cache\", } response_obj = requests.request(\"POST\", url, data = payload, headers = headers) print(response_obj.text) print(\"SMS sent to \" + str(to) + \" with subject :\" + str(sub) + \" and message :\" + str(msg)) toast.show_toast(\"SMS Sent!\" , f\"{name} was sent message\", threaded = True, icon_path = None, duration = 6) while toast.notification_active(): time.sleep(0.1) # driver codeif __name__==\"__main__\": # read the excel sheet having all the details dataframe = pd.read_excel(\"excelsheet.xlsx\") # today date in format : DD-MM today = datetime.datetime.now().strftime(\"%d-%m\") # current year in format : YY yearNow = datetime.datetime.now().strftime(\"%Y\") # writeindex list writeInd = [] for index,item in dataframe.iterrows(): msg = \"Many Many Happy Returns of the day dear \" + str(item['NAME']) # stripping the birthday in excel # sheet as : DD-MM bday = item['Birthday'].strftime(\"%d-%m\") # condition checking if (today == bday) and yearNow not in str(item['Year']): # calling the sendEmail function sendEmail(item['Email'], \"Happy Birthday\", msg) # calling the sendsms function sendsms(item['Contact'], msg, item['NAME'], \"Happy Birthday\") writeInd.append(index) for i in writeInd: yr = dataframe.loc[i,'Year'] # this will record the years in which # email has been sent dataframe.loc[i,'Year'] = str(yr) + ',' + str(yearNow) dataframe.to_excel('excelsheet.xlsx', index = False)", "e": 30919, "s": 27476, "text": null }, { "code": null, "e": 30933, "s": 30919, "text": "sumitgumber28" }, { "code": null, "e": 30948, "s": 30933, "text": "sagartomar9927" }, { "code": null, "e": 30964, "s": 30948, "text": "Python-projects" }, { "code": null, "e": 30979, "s": 30964, "text": "python-utility" }, { "code": null, "e": 30986, "s": 30979, "text": "Python" }, { "code": null, "e": 31084, "s": 30986, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31102, "s": 31084, "text": "Python Dictionary" }, { "code": null, "e": 31134, "s": 31102, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 31156, "s": 31134, "text": "Enumerate() in Python" }, { "code": null, "e": 31198, "s": 31156, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 31224, "s": 31198, "text": "Python String | replace()" }, { "code": null, "e": 31268, "s": 31224, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 31297, "s": 31268, "text": "*args and **kwargs in Python" }, { "code": null, "e": 31334, "s": 31297, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 31376, "s": 31334, "text": "Check if element exists in list in Python" } ]
Arduino - Tone Library
In this chapter, we will use the Arduino Tone Library. It is nothing but an Arduino Library, which produces square-wave of a specified frequency (and 50% duty cycle) on any Arduino pin. A duration can optionally be specified, otherwise the wave continues until the stop() function is called. The pin can be connected to a piezo buzzer or a speaker to play the tones. Warning βˆ’ Do not connect the pin directly to any audio input. The voltage is considerably higher than the standard line level voltages, and can damage sound card inputs, etc. You can use a voltage divider to bring the voltage down. You will need the following components βˆ’ 1 Γ— 8-ohm speaker 1 Γ— 1k resistor 1 Γ— Arduino UNO board Follow the circuit diagram and make the connections as shown in the image given below. Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking New. To make the pitches.h file, either click the button just below the serial monitor icon and choose "New Tab", or use Ctrl+Shift+N. Then paste the following code βˆ’ /************************************************* * Public Constants *************************************************/ #define NOTE_B0 31 #define NOTE_C1 33 #define NOTE_CS1 35 #define NOTE_D1 37 #define NOTE_DS1 39 #define NOTE_E1 41 #define NOTE_F1 44 #define NOTE_FS1 46 #define NOTE_G1 49 #define NOTE_GS1 52 #define NOTE_A1 55 #define NOTE_AS1 58 #define NOTE_B1 62 #define NOTE_C2 65 #define NOTE_CS2 69 #define NOTE_D2 73 #define NOTE_DS2 78 #define NOTE_E2 82 #define NOTE_F2 87 #define NOTE_FS2 93 #define NOTE_G2 98 #define NOTE_GS2 104 #define NOTE_A2 110 #define NOTE_AS2 117 #define NOTE_B2 123 #define NOTE_C3 131 #define NOTE_CS3 139 #define NOTE_D3 147 #define NOTE_DS3 156 #define NOTE_E3 165 #define NOTE_F3 175 #define NOTE_FS3 185 #define NOTE_G3 196 #define NOTE_GS3 208 #define NOTE_A3 220 #define NOTE_AS3 233 #define NOTE_B3 247 #define NOTE_C4 262 #define NOTE_CS4 277 #define NOTE_D4 294 #define NOTE_DS4 311 #define NOTE_E4 330 #define NOTE_F4 349 #define NOTE_FS4 370 #define NOTE_G4 392 #define NOTE_GS4 415 #define NOTE_A4 440 #define NOTE_AS4 466 #define NOTE_B4 494 #define NOTE_C5 523 #define NOTE_CS5 554 #define NOTE_D5 587 #define NOTE_DS5 622 #define NOTE_E5 659 #define NOTE_F5 698 #define NOTE_FS5 740 #define NOTE_G5 784 #define NOTE_GS5 831 #define NOTE_A5 880 #define NOTE_AS5 932 #define NOTE_B5 988 #define NOTE_C6 1047 #define NOTE_CS6 1109 #define NOTE_D6 1175 #define NOTE_DS6 1245 #define NOTE_E6 1319 #define NOTE_F6 1397 #define NOTE_FS6 1480 #define NOTE_G6 1568 #define NOTE_GS6 1661 #define NOTE_A6 1760 #define NOTE_AS6 1865 #define NOTE_B6 1976 #define NOTE_C7 2093 #define NOTE_CS7 2217 #define NOTE_D7 2349 #define NOTE_DS7 2489 #define NOTE_E7 2637 #define NOTE_F7 2794 #define NOTE_FS7 2960 #define NOTE_G7 3136 #define NOTE_GS7 3322 #define NOTE_A7 3520 #define NOTE_AS7 3729 #define NOTE_B7 3951 #define NOTE_C8 4186 #define NOTE_CS8 4435 #define NOTE_D8 4699 #define NOTE_DS8 4978 Save the above given code as pitches.h #include "pitches.h" // notes in the melody: int melody[] = { NOTE_C4, NOTE_G3,NOTE_G3, NOTE_GS3, NOTE_G3,0, NOTE_B3, NOTE_C4}; // note durations: 4 = quarter note, 8 = eighth note, etc.: int noteDurations[] = { 4, 8, 8, 4,4,4,4,4 }; void setup() { // iterate over the notes of the melody: for (int thisNote = 0; thisNote < 8; thisNote++) { // to calculate the note duration, take one second // divided by the note type. //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc. int noteDuration = 1000/noteDurations[thisNote]; tone(8, melody[thisNote],noteDuration); //pause for the note's duration plus 30 ms: delay(noteDuration +30); } } void loop() { // no need to repeat the melody. } The code uses an extra file, pitches.h. This file contains all the pitch values for typical notes. For example, NOTE_C4 is middle C. NOTE_FS4 is F sharp, and so forth. This note table was originally written by Brett Hagman, on whose work the tone() command was based. You may find it useful whenever you want to make musical notes. You will hear musical notes saved in the pitches.h. file. 65 Lectures 6.5 hours Amit Rana 43 Lectures 3 hours Amit Rana 20 Lectures 2 hours Ashraf Said 19 Lectures 1.5 hours Ashraf Said 11 Lectures 47 mins Ashraf Said 9 Lectures 41 mins Ashraf Said Print Add Notes Bookmark this page
[ { "code": null, "e": 3237, "s": 2870, "text": "In this chapter, we will use the Arduino Tone Library. It is nothing but an Arduino Library, which produces square-wave of a specified frequency (and 50% duty cycle) on any Arduino pin. A duration can optionally be specified, otherwise the wave continues until the stop() function is called. The pin can be connected to a piezo buzzer or a speaker to play the tones." }, { "code": null, "e": 3469, "s": 3237, "text": "Warning βˆ’ Do not connect the pin directly to any audio input. The voltage is considerably higher than the standard line level voltages, and can damage sound card inputs, etc. You can use a voltage divider to bring the voltage down." }, { "code": null, "e": 3510, "s": 3469, "text": "You will need the following components βˆ’" }, { "code": null, "e": 3528, "s": 3510, "text": "1 Γ— 8-ohm speaker" }, { "code": null, "e": 3544, "s": 3528, "text": "1 Γ— 1k resistor" }, { "code": null, "e": 3566, "s": 3544, "text": "1 Γ— Arduino UNO board" }, { "code": null, "e": 3653, "s": 3566, "text": "Follow the circuit diagram and make the connections as shown in the image given below." }, { "code": null, "e": 3799, "s": 3653, "text": "Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking New." }, { "code": null, "e": 3929, "s": 3799, "text": "To make the pitches.h file, either click the button just below the serial monitor icon and choose \"New Tab\", or use Ctrl+Shift+N." }, { "code": null, "e": 3961, "s": 3929, "text": "Then paste the following code βˆ’" }, { "code": null, "e": 5907, "s": 3961, "text": "/*************************************************\n* Public Constants\n*************************************************/\n\n#define NOTE_B0 31\n#define NOTE_C1 33\n#define NOTE_CS1 35\n#define NOTE_D1 37\n#define NOTE_DS1 39\n#define NOTE_E1 41\n#define NOTE_F1 44\n#define NOTE_FS1 46\n#define NOTE_G1 49\n#define NOTE_GS1 52\n#define NOTE_A1 55\n#define NOTE_AS1 58\n#define NOTE_B1 62\n#define NOTE_C2 65\n#define NOTE_CS2 69\n#define NOTE_D2 73\n#define NOTE_DS2 78\n#define NOTE_E2 82\n#define NOTE_F2 87\n#define NOTE_FS2 93\n#define NOTE_G2 98\n#define NOTE_GS2 104\n#define NOTE_A2 110\n#define NOTE_AS2 117\n#define NOTE_B2 123\n#define NOTE_C3 131\n#define NOTE_CS3 139\n#define NOTE_D3 147\n#define NOTE_DS3 156\n#define NOTE_E3 165\n#define NOTE_F3 175\n#define NOTE_FS3 185\n#define NOTE_G3 196\n#define NOTE_GS3 208\n#define NOTE_A3 220\n#define NOTE_AS3 233\n#define NOTE_B3 247\n#define NOTE_C4 262\n#define NOTE_CS4 277\n#define NOTE_D4 294\n#define NOTE_DS4 311\n#define NOTE_E4 330\n#define NOTE_F4 349\n#define NOTE_FS4 370\n#define NOTE_G4 392\n#define NOTE_GS4 415\n#define NOTE_A4 440\n#define NOTE_AS4 466\n#define NOTE_B4 494\n#define NOTE_C5 523\n#define NOTE_CS5 554\n#define NOTE_D5 587\n#define NOTE_DS5 622\n#define NOTE_E5 659\n#define NOTE_F5 698\n#define NOTE_FS5 740\n#define NOTE_G5 784\n#define NOTE_GS5 831\n#define NOTE_A5 880\n#define NOTE_AS5 932\n#define NOTE_B5 988\n#define NOTE_C6 1047\n#define NOTE_CS6 1109\n#define NOTE_D6 1175\n#define NOTE_DS6 1245\n#define NOTE_E6 1319\n#define NOTE_F6 1397\n#define NOTE_FS6 1480\n#define NOTE_G6 1568\n#define NOTE_GS6 1661\n#define NOTE_A6 1760\n#define NOTE_AS6 1865\n#define NOTE_B6 1976\n#define NOTE_C7 2093\n#define NOTE_CS7 2217\n#define NOTE_D7 2349\n#define NOTE_DS7 2489\n#define NOTE_E7 2637\n#define NOTE_F7 2794\n#define NOTE_FS7 2960\n#define NOTE_G7 3136\n#define NOTE_GS7 3322\n#define NOTE_A7 3520\n#define NOTE_AS7 3729\n#define NOTE_B7 3951\n#define NOTE_C8 4186\n#define NOTE_CS8 4435\n#define NOTE_D8 4699\n#define NOTE_DS8 4978" }, { "code": null, "e": 5946, "s": 5907, "text": "Save the above given code as pitches.h" }, { "code": null, "e": 6698, "s": 5946, "text": "#include \"pitches.h\"\n// notes in the melody:\nint melody[] = {\nNOTE_C4, NOTE_G3,NOTE_G3, NOTE_GS3, NOTE_G3,0, NOTE_B3, NOTE_C4};\n// note durations: 4 = quarter note, 8 = eighth note, etc.:\n\nint noteDurations[] = {\n 4, 8, 8, 4,4,4,4,4 \n};\n\nvoid setup() {\n // iterate over the notes of the melody:\n for (int thisNote = 0; thisNote < 8; thisNote++) {\n // to calculate the note duration, take one second\n // divided by the note type.\n //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.\n int noteDuration = 1000/noteDurations[thisNote];\n tone(8, melody[thisNote],noteDuration);\n //pause for the note's duration plus 30 ms:\n delay(noteDuration +30);\n }\n}\n\nvoid loop() {\n // no need to repeat the melody.\n}" }, { "code": null, "e": 7030, "s": 6698, "text": "The code uses an extra file, pitches.h. This file contains all the pitch values for typical notes. For example, NOTE_C4 is middle C. NOTE_FS4 is F sharp, and so forth. This note table was originally written by Brett Hagman, on whose work the tone() command was based. You may find it useful whenever you want to make musical notes." }, { "code": null, "e": 7088, "s": 7030, "text": "You will hear musical notes saved in the pitches.h. file." }, { "code": null, "e": 7123, "s": 7088, "text": "\n 65 Lectures \n 6.5 hours \n" }, { "code": null, "e": 7134, "s": 7123, "text": " Amit Rana" }, { "code": null, "e": 7167, "s": 7134, "text": "\n 43 Lectures \n 3 hours \n" }, { "code": null, "e": 7178, "s": 7167, "text": " Amit Rana" }, { "code": null, "e": 7211, "s": 7178, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 7224, "s": 7211, "text": " Ashraf Said" }, { "code": null, "e": 7259, "s": 7224, "text": "\n 19 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7272, "s": 7259, "text": " Ashraf Said" }, { "code": null, "e": 7304, "s": 7272, "text": "\n 11 Lectures \n 47 mins\n" }, { "code": null, "e": 7317, "s": 7304, "text": " Ashraf Said" }, { "code": null, "e": 7348, "s": 7317, "text": "\n 9 Lectures \n 41 mins\n" }, { "code": null, "e": 7361, "s": 7348, "text": " Ashraf Said" }, { "code": null, "e": 7368, "s": 7361, "text": " Print" }, { "code": null, "e": 7379, "s": 7368, "text": " Add Notes" } ]
Python | Convert string dictionary to dictionary - GeeksforGeeks
22 May, 2019 Interconversions of data types have been discussed many times and have been quite a popular problem to solve. This article discusses yet another problem of interconversion of dictionary, in string format to a dictionary. Let’s discuss certain ways in which this can be done. Method #1 : Using json.loads() This task can easily be performed using the inbuilt function of loads of json library of python which converts the string of valid dictionary into json form, dictionary in Python. # Python3 code to demonstrate# convert dictionary string to dictionary# using json.loads()import json # initializing string test_string = '{"Nikhil" : 1, "Akshat" : 2, "Akash" : 3}' # printing original string print("The original string : " + str(test_string)) # using json.loads()# convert dictionary string to dictionaryres = json.loads(test_string) # print resultprint("The converted dictionary : " + str(res)) The original string : {"Nikhil" : 1, "Akshat" : 2, "Akash" : 3} The converted dictionary : {'Nikhil': 1, 'Akshat': 2, 'Akash': 3} Method #2 : Using ast.literal_eval() The above method can also be used to perform a similar conversion. Function safer than the eval function and can be used for interconversion of all data types other than dictionary as well. # Python3 code to demonstrate# convert dictionary string to dictionary# using ast.literal_eval()import ast # initializing string test_string = '{"Nikhil" : 1, "Akshat" : 2, "Akash" : 3}' # printing original string print("The original string : " + str(test_string)) # using ast.literal_eval()# convert dictionary string to dictionaryres = ast.literal_eval(test_string) # print resultprint("The converted dictionary : " + str(res)) The original string : {"Nikhil" : 1, "Akshat" : 2, "Akash" : 3} The converted dictionary : {'Nikhil': 1, 'Akshat': 2, 'Akash': 3} Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 24136, "s": 24108, "text": "\n22 May, 2019" }, { "code": null, "e": 24411, "s": 24136, "text": "Interconversions of data types have been discussed many times and have been quite a popular problem to solve. This article discusses yet another problem of interconversion of dictionary, in string format to a dictionary. Let’s discuss certain ways in which this can be done." }, { "code": null, "e": 24442, "s": 24411, "text": "Method #1 : Using json.loads()" }, { "code": null, "e": 24622, "s": 24442, "text": "This task can easily be performed using the inbuilt function of loads of json library of python which converts the string of valid dictionary into json form, dictionary in Python." }, { "code": "# Python3 code to demonstrate# convert dictionary string to dictionary# using json.loads()import json # initializing string test_string = '{\"Nikhil\" : 1, \"Akshat\" : 2, \"Akash\" : 3}' # printing original string print(\"The original string : \" + str(test_string)) # using json.loads()# convert dictionary string to dictionaryres = json.loads(test_string) # print resultprint(\"The converted dictionary : \" + str(res))", "e": 25040, "s": 24622, "text": null }, { "code": null, "e": 25171, "s": 25040, "text": "The original string : {\"Nikhil\" : 1, \"Akshat\" : 2, \"Akash\" : 3}\nThe converted dictionary : {'Nikhil': 1, 'Akshat': 2, 'Akash': 3}\n" }, { "code": null, "e": 25210, "s": 25173, "text": "Method #2 : Using ast.literal_eval()" }, { "code": null, "e": 25400, "s": 25210, "text": "The above method can also be used to perform a similar conversion. Function safer than the eval function and can be used for interconversion of all data types other than dictionary as well." }, { "code": "# Python3 code to demonstrate# convert dictionary string to dictionary# using ast.literal_eval()import ast # initializing string test_string = '{\"Nikhil\" : 1, \"Akshat\" : 2, \"Akash\" : 3}' # printing original string print(\"The original string : \" + str(test_string)) # using ast.literal_eval()# convert dictionary string to dictionaryres = ast.literal_eval(test_string) # print resultprint(\"The converted dictionary : \" + str(res))", "e": 25835, "s": 25400, "text": null }, { "code": null, "e": 25966, "s": 25835, "text": "The original string : {\"Nikhil\" : 1, \"Akshat\" : 2, \"Akash\" : 3}\nThe converted dictionary : {'Nikhil': 1, 'Akshat': 2, 'Akash': 3}\n" }, { "code": null, "e": 25993, "s": 25966, "text": "Python dictionary-programs" }, { "code": null, "e": 26000, "s": 25993, "text": "Python" }, { "code": null, "e": 26016, "s": 26000, "text": "Python Programs" }, { "code": null, "e": 26114, "s": 26016, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26123, "s": 26114, "text": "Comments" }, { "code": null, "e": 26136, "s": 26123, "text": "Old Comments" }, { "code": null, "e": 26171, "s": 26136, "text": "Read a file line by line in Python" }, { "code": null, "e": 26193, "s": 26171, "text": "Enumerate() in Python" }, { "code": null, "e": 26225, "s": 26193, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26255, "s": 26225, "text": "Iterate over a list in Python" }, { "code": null, "e": 26297, "s": 26255, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26340, "s": 26297, "text": "Python program to convert a list to string" }, { "code": null, "e": 26362, "s": 26340, "text": "Defaultdict in Python" }, { "code": null, "e": 26401, "s": 26362, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26447, "s": 26401, "text": "Python | Split string into list of characters" } ]
Maximum sum of minimums of pairs in an array - GeeksforGeeks
07 Mar, 2022 Given an array arr[] of N integers where N is even, the task is to group the array elements in the pairs (X1, Y1), (X2, Y2), (X3, Y3), ... such that the sum min(X1, Y1) + min(X2, Y2) + min(X3, Y3) + ... is maximum.Examples: Input: arr[] = {1, 5, 3, 2} Output: 4 (1, 5) and (3, 2) -> 1 + 2 = 3 (1, 3) and (5, 2) -> 1 + 2 = 3 (1, 2) and (5, 3) -> 1 + 3 = 4Input: arr[] = {1, 3, 2, 1, 4, 5} Output: 7 Approach: No matter how the pairs are formed, the maximum element from the array will always be ignored as it will be the maximum element in every pair it is put into. Same goes for the second maximum element unless it is paired with the maximum element. So, to maximize the sum an optimal approach will be to sort the array and start making pairs in order starting from the maximum element.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 return the maximum// required sum of the pairsint maxSum(int a[], int n){ // Sort the array sort(a, a + n); // To store the sum int sum = 0; // Start making pairs of every two // consecutive elements as n is even for (int i = 0; i < n - 1; i += 2) { // Minimum element of the current pair sum += a[i]; } // Return the maximum possible sum return sum;} // Driver codeint main(){ int arr[] = { 1, 3, 2, 1, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << maxSum(arr, n); return 0;} // Java implementation of the approachimport java.util.Arrays; class GFG{ // Function to return the maximum// required sum of the pairsstatic int maxSum(int a[], int n){ // Sort the array Arrays.sort(a); // To store the sum int sum = 0; // Start making pairs of every two // consecutive elements as n is even for (int i = 0; i < n - 1; i += 2) { // Minimum element of the current pair sum += a[i]; } // Return the maximum possible sum return sum;} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 3, 2, 1, 4, 5 }; int n = arr.length; System.out.println(maxSum(arr, n));}} // This code is contributed by Code_Mech # Python3 implementation of the approach # Function to return the maximum# required sum of the pairsdef maxSum(a, n) : # Sort the array a.sort(); # To store the sum sum = 0; # Start making pairs of every two # consecutive elements as n is even for i in range(0, n - 1, 2) : # Minimum element of the current pair sum += a[i]; # Return the maximum possible sum return sum; # Driver codeif __name__ == "__main__" : arr = [ 1, 3, 2, 1, 4, 5 ]; n = len(arr); print(maxSum(arr, n)); # This code is contributed by AnkitRai01 // C# implementation of the approachusing System; class GFG{ // Function to return the maximum// required sum of the pairsstatic int maxSum(int []a, int n){ // Sort the array Array.Sort(a); // To store the sum int sum = 0; // Start making pairs of every two // consecutive elements as n is even for (int i = 0; i < n - 1; i += 2) { // Minimum element of the current pair sum += a[i]; } // Return the maximum possible sum return sum;} // Driver codepublic static void Main(String[] args){ int []arr = { 1, 3, 2, 1, 4, 5 }; int n = arr.Length; Console.WriteLine(maxSum(arr, n));}} // This code is contributed by 29AjayKumar <script>// Javascript implementation of the approach // Function to return the maximum// required sum of the pairsfunction maxSum(a, n) { // Sort the array a.sort((a, b) => a - b); // To store the sum let sum = 0; // Start making pairs of every two // consecutive elements as n is even for (let i = 0; i < n - 1; i += 2) { // Minimum element of the current pair sum += a[i]; } // Return the maximum possible sum return sum;} // Driver codelet arr = [1, 3, 2, 1, 4, 5];let n = arr.length; document.write(maxSum(arr, n)); // This code is contributed by _saurabh_jaiswal</script> 7 Time Complexity: O(n logn)Auxiliary Space: O(1) ankthon Code_Mech 29AjayKumar _saurabh_jaiswal singhh3010 Constructive Algorithms Algorithms Arrays Sorting Arrays Sorting Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments DSA Sheet by Love Babbar Difference between Informed and Uninformed Search in AI SCAN (Elevator) Disk Scheduling Algorithms Quadratic Probing in Hashing K means Clustering - Introduction Arrays in Java Arrays in C/C++ Program for array rotation Stack Data Structure (Introduction and Program) Largest Sum Contiguous Subarray
[ { "code": null, "e": 24301, "s": 24273, "text": "\n07 Mar, 2022" }, { "code": null, "e": 24527, "s": 24301, "text": "Given an array arr[] of N integers where N is even, the task is to group the array elements in the pairs (X1, Y1), (X2, Y2), (X3, Y3), ... such that the sum min(X1, Y1) + min(X2, Y2) + min(X3, Y3) + ... is maximum.Examples: " }, { "code": null, "e": 24703, "s": 24527, "text": "Input: arr[] = {1, 5, 3, 2} Output: 4 (1, 5) and (3, 2) -> 1 + 2 = 3 (1, 3) and (5, 2) -> 1 + 2 = 3 (1, 2) and (5, 3) -> 1 + 3 = 4Input: arr[] = {1, 3, 2, 1, 4, 5} Output: 7 " }, { "code": null, "e": 25149, "s": 24705, "text": "Approach: No matter how the pairs are formed, the maximum element from the array will always be ignored as it will be the maximum element in every pair it is put into. Same goes for the second maximum element unless it is paired with the maximum element. So, to maximize the sum an optimal approach will be to sort the array and start making pairs in order starting from the maximum element.Below is the implementation of the above approach: " }, { "code": null, "e": 25153, "s": 25149, "text": "C++" }, { "code": null, "e": 25158, "s": 25153, "text": "Java" }, { "code": null, "e": 25166, "s": 25158, "text": "Python3" }, { "code": null, "e": 25169, "s": 25166, "text": "C#" }, { "code": null, "e": 25180, "s": 25169, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the maximum// required sum of the pairsint maxSum(int a[], int n){ // Sort the array sort(a, a + n); // To store the sum int sum = 0; // Start making pairs of every two // consecutive elements as n is even for (int i = 0; i < n - 1; i += 2) { // Minimum element of the current pair sum += a[i]; } // Return the maximum possible sum return sum;} // Driver codeint main(){ int arr[] = { 1, 3, 2, 1, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << maxSum(arr, n); return 0;}", "e": 25825, "s": 25180, "text": null }, { "code": "// Java implementation of the approachimport java.util.Arrays; class GFG{ // Function to return the maximum// required sum of the pairsstatic int maxSum(int a[], int n){ // Sort the array Arrays.sort(a); // To store the sum int sum = 0; // Start making pairs of every two // consecutive elements as n is even for (int i = 0; i < n - 1; i += 2) { // Minimum element of the current pair sum += a[i]; } // Return the maximum possible sum return sum;} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 3, 2, 1, 4, 5 }; int n = arr.length; System.out.println(maxSum(arr, n));}} // This code is contributed by Code_Mech", "e": 26526, "s": 25825, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the maximum# required sum of the pairsdef maxSum(a, n) : # Sort the array a.sort(); # To store the sum sum = 0; # Start making pairs of every two # consecutive elements as n is even for i in range(0, n - 1, 2) : # Minimum element of the current pair sum += a[i]; # Return the maximum possible sum return sum; # Driver codeif __name__ == \"__main__\" : arr = [ 1, 3, 2, 1, 4, 5 ]; n = len(arr); print(maxSum(arr, n)); # This code is contributed by AnkitRai01", "e": 27101, "s": 26526, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the maximum// required sum of the pairsstatic int maxSum(int []a, int n){ // Sort the array Array.Sort(a); // To store the sum int sum = 0; // Start making pairs of every two // consecutive elements as n is even for (int i = 0; i < n - 1; i += 2) { // Minimum element of the current pair sum += a[i]; } // Return the maximum possible sum return sum;} // Driver codepublic static void Main(String[] args){ int []arr = { 1, 3, 2, 1, 4, 5 }; int n = arr.Length; Console.WriteLine(maxSum(arr, n));}} // This code is contributed by 29AjayKumar", "e": 27793, "s": 27101, "text": null }, { "code": "<script>// Javascript implementation of the approach // Function to return the maximum// required sum of the pairsfunction maxSum(a, n) { // Sort the array a.sort((a, b) => a - b); // To store the sum let sum = 0; // Start making pairs of every two // consecutive elements as n is even for (let i = 0; i < n - 1; i += 2) { // Minimum element of the current pair sum += a[i]; } // Return the maximum possible sum return sum;} // Driver codelet arr = [1, 3, 2, 1, 4, 5];let n = arr.length; document.write(maxSum(arr, n)); // This code is contributed by _saurabh_jaiswal</script>", "e": 28420, "s": 27793, "text": null }, { "code": null, "e": 28422, "s": 28420, "text": "7" }, { "code": null, "e": 28472, "s": 28424, "text": "Time Complexity: O(n logn)Auxiliary Space: O(1)" }, { "code": null, "e": 28480, "s": 28472, "text": "ankthon" }, { "code": null, "e": 28490, "s": 28480, "text": "Code_Mech" }, { "code": null, "e": 28502, "s": 28490, "text": "29AjayKumar" }, { "code": null, "e": 28519, "s": 28502, "text": "_saurabh_jaiswal" }, { "code": null, "e": 28530, "s": 28519, "text": "singhh3010" }, { "code": null, "e": 28554, "s": 28530, "text": "Constructive Algorithms" }, { "code": null, "e": 28565, "s": 28554, "text": "Algorithms" }, { "code": null, "e": 28572, "s": 28565, "text": "Arrays" }, { "code": null, "e": 28580, "s": 28572, "text": "Sorting" }, { "code": null, "e": 28587, "s": 28580, "text": "Arrays" }, { "code": null, "e": 28595, "s": 28587, "text": "Sorting" }, { "code": null, "e": 28606, "s": 28595, "text": "Algorithms" }, { "code": null, "e": 28704, "s": 28606, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28713, "s": 28704, "text": "Comments" }, { "code": null, "e": 28726, "s": 28713, "text": "Old Comments" }, { "code": null, "e": 28751, "s": 28726, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 28807, "s": 28751, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 28850, "s": 28807, "text": "SCAN (Elevator) Disk Scheduling Algorithms" }, { "code": null, "e": 28879, "s": 28850, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 28913, "s": 28879, "text": "K means Clustering - Introduction" }, { "code": null, "e": 28928, "s": 28913, "text": "Arrays in Java" }, { "code": null, "e": 28944, "s": 28928, "text": "Arrays in C/C++" }, { "code": null, "e": 28971, "s": 28944, "text": "Program for array rotation" }, { "code": null, "e": 29019, "s": 28971, "text": "Stack Data Structure (Introduction and Program)" } ]
Convert an image into jpg format using Pillow in Python - GeeksforGeeks
20 Aug, 2020 Let us see how to convert an image into jpg format in Python. The size of png is larger when compared to jpg format. We also know that some applications might ask for images of smaller sizes. Hence conversion from png(larger ) to jpg(smaller) is needed.For this task we will be using the Image.convert() method of the Pillow module. Algorithm : Import the Image module from PIL and import the os module.Import the image to be converted using the Image.open() method.Display the size of the image before the conversion using the os.path.getsize() method.Convert the image using the Image.convert() method. Pass "RGB" as the parameter.Export the image using the Image.save() method.Display the size of the image after the conversion using the os.path.getsize() method. Import the Image module from PIL and import the os module. Import the image to be converted using the Image.open() method. Display the size of the image before the conversion using the os.path.getsize() method. Convert the image using the Image.convert() method. Pass "RGB" as the parameter. Export the image using the Image.save() method. Display the size of the image after the conversion using the os.path.getsize() method. We will be converting the following image : # importing the modulefrom PIL import Imageimport os # importing the image im = Image.open("geeksforgeeks.png")print("The size of the image before conversion : ", end = "")print(os.path.getsize("geeksforgeeks.png")) # converting to jpgrgb_im = im.convert("RGB") # exporting the imagergb_im.save("geeksforgeeks_jpg.jpg")print("The size of the image after conversion : ", end = "")print(os.path.getsize("geeksforgeeks_jpg.jpg")) Output : The size of the image before conversion : 26617 The size of the image after conversion : 18118 Python-pil Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary How to Install PIP on Windows ? Read a file line by line in Python Enumerate() in Python Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Create a Pandas DataFrame from Lists Python String | replace() Reading and Writing to text files in Python
[ { "code": null, "e": 24392, "s": 24364, "text": "\n20 Aug, 2020" }, { "code": null, "e": 24725, "s": 24392, "text": "Let us see how to convert an image into jpg format in Python. The size of png is larger when compared to jpg format. We also know that some applications might ask for images of smaller sizes. Hence conversion from png(larger ) to jpg(smaller) is needed.For this task we will be using the Image.convert() method of the Pillow module." }, { "code": null, "e": 24737, "s": 24725, "text": "Algorithm :" }, { "code": null, "e": 25159, "s": 24737, "text": "Import the Image module from PIL and import the os module.Import the image to be converted using the Image.open() method.Display the size of the image before the conversion using the os.path.getsize() method.Convert the image using the Image.convert() method. Pass \"RGB\" as the parameter.Export the image using the Image.save() method.Display the size of the image after the conversion using the os.path.getsize() method." }, { "code": null, "e": 25218, "s": 25159, "text": "Import the Image module from PIL and import the os module." }, { "code": null, "e": 25282, "s": 25218, "text": "Import the image to be converted using the Image.open() method." }, { "code": null, "e": 25370, "s": 25282, "text": "Display the size of the image before the conversion using the os.path.getsize() method." }, { "code": null, "e": 25451, "s": 25370, "text": "Convert the image using the Image.convert() method. Pass \"RGB\" as the parameter." }, { "code": null, "e": 25499, "s": 25451, "text": "Export the image using the Image.save() method." }, { "code": null, "e": 25586, "s": 25499, "text": "Display the size of the image after the conversion using the os.path.getsize() method." }, { "code": null, "e": 25630, "s": 25586, "text": "We will be converting the following image :" }, { "code": "# importing the modulefrom PIL import Imageimport os # importing the image im = Image.open(\"geeksforgeeks.png\")print(\"The size of the image before conversion : \", end = \"\")print(os.path.getsize(\"geeksforgeeks.png\")) # converting to jpgrgb_im = im.convert(\"RGB\") # exporting the imagergb_im.save(\"geeksforgeeks_jpg.jpg\")print(\"The size of the image after conversion : \", end = \"\")print(os.path.getsize(\"geeksforgeeks_jpg.jpg\"))", "e": 26060, "s": 25630, "text": null }, { "code": null, "e": 26069, "s": 26060, "text": "Output :" }, { "code": null, "e": 26165, "s": 26069, "text": "The size of the image before conversion : 26617\nThe size of the image after conversion : 18118\n" }, { "code": null, "e": 26176, "s": 26165, "text": "Python-pil" }, { "code": null, "e": 26183, "s": 26176, "text": "Python" }, { "code": null, "e": 26281, "s": 26183, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26290, "s": 26281, "text": "Comments" }, { "code": null, "e": 26303, "s": 26290, "text": "Old Comments" }, { "code": null, "e": 26321, "s": 26303, "text": "Python Dictionary" }, { "code": null, "e": 26353, "s": 26321, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26388, "s": 26353, "text": "Read a file line by line in Python" }, { "code": null, "e": 26410, "s": 26388, "text": "Enumerate() in Python" }, { "code": null, "e": 26440, "s": 26410, "text": "Iterate over a list in Python" }, { "code": null, "e": 26482, "s": 26440, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26525, "s": 26482, "text": "Python program to convert a list to string" }, { "code": null, "e": 26562, "s": 26525, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26588, "s": 26562, "text": "Python String | replace()" } ]
How can BeautifulSoup be used to extract β€˜href’ links from a website?
BeautifulSoup is a third party Python library that is used to parse data from web pages. It helps in web scraping, which is a process of extracting, using, and manipulating the data from different resources. Web scraping can also be used to extract data for research purposes, understand/compare market trends, perform SEO monitoring, and so on. The below line can be run to install BeautifulSoup on Windows βˆ’ pip install beautifulsoup4 Following is an example βˆ’ from bs4 import BeautifulSoup import requests url = "https://en.wikipedia.org/wiki/Algorithm" req = requests.get(url) soup = BeautifulSoup(req.text, "html.parser") print("The href links are :") for link in soup.find_all('a'): print(link.get('href')) The href links are : ... https://stats.wikimedia.org/#/en.wikipedia.org https://foundation.wikimedia.org/wiki/Cookie_statement https://wikimediafoundation.org/ https://www.mediawiki.org/ The required packages are imported, and aliased. The required packages are imported, and aliased. The website is defined. The website is defined. The url is opened, and data is read from it. The url is opened, and data is read from it. The β€˜BeautifulSoup’ function is used to extract text from the webpage. The β€˜BeautifulSoup’ function is used to extract text from the webpage. The β€˜find_all’ function is used to extract text from the webpage data. The β€˜find_all’ function is used to extract text from the webpage data. The href links are printed on the console. The href links are printed on the console.
[ { "code": null, "e": 1270, "s": 1062, "text": "BeautifulSoup is a third party Python library that is used to parse data from web pages. It helps in web scraping, which is a process of extracting, using, and manipulating the data from different resources." }, { "code": null, "e": 1408, "s": 1270, "text": "Web scraping can also be used to extract data for research purposes, understand/compare market trends, perform SEO monitoring, and so on." }, { "code": null, "e": 1472, "s": 1408, "text": "The below line can be run to install BeautifulSoup on Windows βˆ’" }, { "code": null, "e": 1499, "s": 1472, "text": "pip install beautifulsoup4" }, { "code": null, "e": 1525, "s": 1499, "text": "Following is an example βˆ’" }, { "code": null, "e": 1778, "s": 1525, "text": "from bs4 import BeautifulSoup\nimport requests\nurl = \"https://en.wikipedia.org/wiki/Algorithm\"\nreq = requests.get(url)\nsoup = BeautifulSoup(req.text, \"html.parser\")\nprint(\"The href links are :\")\nfor link in soup.find_all('a'):\n print(link.get('href'))" }, { "code": null, "e": 1965, "s": 1778, "text": "The href links are :\n...\nhttps://stats.wikimedia.org/#/en.wikipedia.org\nhttps://foundation.wikimedia.org/wiki/Cookie_statement\nhttps://wikimediafoundation.org/\nhttps://www.mediawiki.org/" }, { "code": null, "e": 2014, "s": 1965, "text": "The required packages are imported, and aliased." }, { "code": null, "e": 2063, "s": 2014, "text": "The required packages are imported, and aliased." }, { "code": null, "e": 2087, "s": 2063, "text": "The website is defined." }, { "code": null, "e": 2111, "s": 2087, "text": "The website is defined." }, { "code": null, "e": 2156, "s": 2111, "text": "The url is opened, and data is read from it." }, { "code": null, "e": 2201, "s": 2156, "text": "The url is opened, and data is read from it." }, { "code": null, "e": 2272, "s": 2201, "text": "The β€˜BeautifulSoup’ function is used to extract text from the webpage." }, { "code": null, "e": 2343, "s": 2272, "text": "The β€˜BeautifulSoup’ function is used to extract text from the webpage." }, { "code": null, "e": 2414, "s": 2343, "text": "The β€˜find_all’ function is used to extract text from the webpage data." }, { "code": null, "e": 2485, "s": 2414, "text": "The β€˜find_all’ function is used to extract text from the webpage data." }, { "code": null, "e": 2528, "s": 2485, "text": "The href links are printed on the console." }, { "code": null, "e": 2571, "s": 2528, "text": "The href links are printed on the console." } ]
Python | Append String to list - GeeksforGeeks
29 Nov, 2019 Sometimes, while working with data, we can have a problem in which we need to add elements to a container. List can contain any type of data type. Let’s discuss certain ways in which we can perform string append operation in list of integers. Method #1 : Using + operator + list conversionIn this method, we first convert the string into a list and then perform the task of append using + operator. # Python3 code to demonstrate working of# Appending String to list# using + operator + list conversion # initialize list test_list = [1, 3, 4, 5] # initialize string test_str = 'gfg' # printing original list print("The original list : " + str(test_list)) # printing original string print("The original string : " + str(test_str)) # Appending String to list# using + operator + list conversiontest_list += [test_str] # printing resultprint("The list after appending is : " + str(test_list)) The original list : [1, 3, 4, 5] The original string : gfg The list after appending is : [1, 3, 4, 5, 'gfg'] Method #2 : Using append()This particular function can be used to perform the operation of appending string element to end of list without changing the state of string to list of characters. # Python3 code to demonstrate working of# Appending String to list# using append() # initialize list test_list = [1, 3, 4, 5] # initialize string test_str = 'gfg' # printing original list print("The original list : " + str(test_list)) # printing original string print("The original string : " + str(test_str)) # Appending String to list# using append()test_list.append(test_str) # printing resultprint("The list after appending is : " + str(test_list)) The original list : [1, 3, 4, 5] The original string : gfg The list after appending is : [1, 3, 4, 5, 'gfg'] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 23994, "s": 23966, "text": "\n29 Nov, 2019" }, { "code": null, "e": 24237, "s": 23994, "text": "Sometimes, while working with data, we can have a problem in which we need to add elements to a container. List can contain any type of data type. Let’s discuss certain ways in which we can perform string append operation in list of integers." }, { "code": null, "e": 24393, "s": 24237, "text": "Method #1 : Using + operator + list conversionIn this method, we first convert the string into a list and then perform the task of append using + operator." }, { "code": "# Python3 code to demonstrate working of# Appending String to list# using + operator + list conversion # initialize list test_list = [1, 3, 4, 5] # initialize string test_str = 'gfg' # printing original list print(\"The original list : \" + str(test_list)) # printing original string print(\"The original string : \" + str(test_str)) # Appending String to list# using + operator + list conversiontest_list += [test_str] # printing resultprint(\"The list after appending is : \" + str(test_list))", "e": 24889, "s": 24393, "text": null }, { "code": null, "e": 24999, "s": 24889, "text": "The original list : [1, 3, 4, 5]\nThe original string : gfg\nThe list after appending is : [1, 3, 4, 5, 'gfg']\n" }, { "code": null, "e": 25192, "s": 25001, "text": "Method #2 : Using append()This particular function can be used to perform the operation of appending string element to end of list without changing the state of string to list of characters." }, { "code": "# Python3 code to demonstrate working of# Appending String to list# using append() # initialize list test_list = [1, 3, 4, 5] # initialize string test_str = 'gfg' # printing original list print(\"The original list : \" + str(test_list)) # printing original string print(\"The original string : \" + str(test_str)) # Appending String to list# using append()test_list.append(test_str) # printing resultprint(\"The list after appending is : \" + str(test_list))", "e": 25651, "s": 25192, "text": null }, { "code": null, "e": 25761, "s": 25651, "text": "The original list : [1, 3, 4, 5]\nThe original string : gfg\nThe list after appending is : [1, 3, 4, 5, 'gfg']\n" }, { "code": null, "e": 25782, "s": 25761, "text": "Python list-programs" }, { "code": null, "e": 25789, "s": 25782, "text": "Python" }, { "code": null, "e": 25805, "s": 25789, "text": "Python Programs" }, { "code": null, "e": 25903, "s": 25805, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25912, "s": 25903, "text": "Comments" }, { "code": null, "e": 25925, "s": 25912, "text": "Old Comments" }, { "code": null, "e": 25943, "s": 25925, "text": "Python Dictionary" }, { "code": null, "e": 25978, "s": 25943, "text": "Read a file line by line in Python" }, { "code": null, "e": 26010, "s": 25978, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26052, "s": 26010, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26078, "s": 26052, "text": "Python String | replace()" }, { "code": null, "e": 26121, "s": 26078, "text": "Python program to convert a list to string" }, { "code": null, "e": 26143, "s": 26121, "text": "Defaultdict in Python" }, { "code": null, "e": 26182, "s": 26143, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26228, "s": 26182, "text": "Python | Split string into list of characters" } ]
How to find the nth occurrence of substring in a string in Python?
You can find the nth occurrence of a substring in a string by splitting at the substring with max n+1 splits. If the resulting list has a size greater than n+1, it means that the substring occurs more than n times. Its index can be found by a simple formula, length of the original string - length of last splitted part - length of the substring. def findnth(string, substring, n): parts = string.split(substring, n + 1) if len(parts) <= n + 1: return -1 return len(string) - len(parts[-1]) - len(substring) findnth('foobarfobar akfjfoobar afskjdf foobar', 'foobar', 2) This would give the output: 31 The n in this starts from 0. It is quite trivial to change that.
[ { "code": null, "e": 1409, "s": 1062, "text": "You can find the nth occurrence of a substring in a string by splitting at the substring with max n+1 splits. If the resulting list has a size greater than n+1, it means that the substring occurs more than n times. Its index can be found by a simple formula, length of the original string - length of last splitted part - length of the substring." }, { "code": null, "e": 1652, "s": 1409, "text": "def findnth(string, substring, n):\n parts = string.split(substring, n + 1)\n if len(parts) <= n + 1:\n return -1\n return len(string) - len(parts[-1]) - len(substring)\nfindnth('foobarfobar akfjfoobar afskjdf foobar', 'foobar', 2)" }, { "code": null, "e": 1680, "s": 1652, "text": "This would give the output:" }, { "code": null, "e": 1683, "s": 1680, "text": "31" }, { "code": null, "e": 1748, "s": 1683, "text": "The n in this starts from 0. It is quite trivial to change that." } ]
HashSet in C#
HashSet in C# eliminates duplicate strings or elements in an array.In C#, it is an optimized set collection. Let us see an example to remove duplicate strings using C# HashSet. Here, we have duplicate elements βˆ’ Live Demo using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { string[] arr1 = { "bus", "truck", "bus", "car", "truck" }; Console.WriteLine(string.Join(",", arr1)); // HashSet var h = new HashSet(arr1); // eliminates duplicate words string[] arr2 = h.ToArray(); Console.WriteLine(string.Join(",", arr2)); } } bus,truck,bus,car,truck bus,truck,car To declare HashSet βˆ’ var h = new HashSet(arr1); Now set it on the array to remove the duplicate words βˆ’ string[] arr2 = h.ToArray();
[ { "code": null, "e": 1171, "s": 1062, "text": "HashSet in C# eliminates duplicate strings or elements in an array.In C#, it is an optimized set collection." }, { "code": null, "e": 1274, "s": 1171, "text": "Let us see an example to remove duplicate strings using C# HashSet. Here, we have duplicate elements βˆ’" }, { "code": null, "e": 1285, "s": 1274, "text": " Live Demo" }, { "code": null, "e": 1738, "s": 1285, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program {\n static void Main() {\n\n string[] arr1 = {\n \"bus\",\n \"truck\",\n \"bus\",\n \"car\",\n \"truck\"\n };\n\n Console.WriteLine(string.Join(\",\", arr1));\n\n // HashSet\n var h = new HashSet(arr1);\n // eliminates duplicate words\n string[] arr2 = h.ToArray();\n Console.WriteLine(string.Join(\",\", arr2));\n }\n}" }, { "code": null, "e": 1776, "s": 1738, "text": "bus,truck,bus,car,truck\nbus,truck,car" }, { "code": null, "e": 1797, "s": 1776, "text": "To declare HashSet βˆ’" }, { "code": null, "e": 1824, "s": 1797, "text": "var h = new HashSet(arr1);" }, { "code": null, "e": 1880, "s": 1824, "text": "Now set it on the array to remove the duplicate words βˆ’" }, { "code": null, "e": 1909, "s": 1880, "text": "string[] arr2 = h.ToArray();" } ]
PHP - session_start() Function
Sessions or session handling is a way to make the data available across various pages of a web application. The session_start() function is used to start a new session or, resume an existing one. session_start([$options]); array(Optional) This is an array representing a set of session options. This function returns a boolean value which is TRUE if the session started successfully and FALSE if not successful. This function was first introduced in PHP Version 4 and works in all the later versions. Following example demonstrates the usage of the session_start() function. <?php //Starting the session session_start(); if( isset( $_SESSION['counter'] ) ) { $_SESSION['counter'] += 1; } else { $_SESSION['counter'] = 1; } $msg = "You have visited this page ". $_SESSION['counter']; $msg .= "in this session."; ?> <html> <head> <title>Setting up a PHP session</title> </head> <body> <?php echo ( $msg ); ?> </body> </html> One executing the above html file it will display the following message βˆ’ You have visited this page 1 times in this session. The number in the message keeps changing based on the number of times you refresh the page without closing the browser. For example, if you refresh 10 times, then the same page displays the following message. You have visited this page 16 times in this session. Following is another example of this function, in here we have two pages from the same application in the same session βˆ’ session_page1.htm <?php if(isset($_POST['SubmitButton'])){ //Starting the session session_start(); $_SESSION['name'] = $_POST['name']; $_SESSION['age'] = $_POST['age']; } ?> <html> <body> <form action="#" method="post"> <br?> <label for="fname">Enter the values click Submit and click on Next</label?> <label for="fname"?>Name:</label> <input type="text" id="name" name="name"><br><br> <label for="lname"?>Age: <input type="text" id="age" name="age"><br?><br> <input type="submit" name="SubmitButton"/?> <?php echo '<br?><br /?><a href="session_page2.htm">Next</a>'; ?> </form> </body> </html> This will produce the following output βˆ’ On clicking on Next the following file is executed. session_page2.htm <html> <head> <title>Second Page</title> </head> <body> <?php //Session started session_start(); print($_SESSION['name']); echo "<br>"; print($_SESSION['age']); ?> </body> </html> This will produce the following output βˆ’ Krishna 30 You can pass optional array to this function as shown below βˆ’ <html> <head> <title>Setting up a PHP session</title> </head> <body> <?php //Starting the session $options = ['cookie_lifetime' => 86400,'read_and_close' => true]; session_start($options); ?> </body> </html> 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": 2953, "s": 2757, "text": "Sessions or session handling is a way to make the data available across various pages of a web application. The session_start() function is used to start a new session or, resume an existing one." }, { "code": null, "e": 2981, "s": 2953, "text": "session_start([$options]);\n" }, { "code": null, "e": 2997, "s": 2981, "text": "array(Optional)" }, { "code": null, "e": 3053, "s": 2997, "text": "This is an array representing a set of session options." }, { "code": null, "e": 3170, "s": 3053, "text": "This function returns a boolean value which is TRUE if the session started successfully and FALSE if not successful." }, { "code": null, "e": 3259, "s": 3170, "text": "This function was first introduced in PHP Version 4 and works in all the later versions." }, { "code": null, "e": 3333, "s": 3259, "text": "Following example demonstrates the usage of the session_start() function." }, { "code": null, "e": 3754, "s": 3333, "text": "<?php\n //Starting the session\n session_start(); \n if( isset( $_SESSION['counter'] ) ) {\n $_SESSION['counter'] += 1;\n } else {\n $_SESSION['counter'] = 1;\n }\t\n $msg = \"You have visited this page \". $_SESSION['counter'];\n $msg .= \"in this session.\";\n?>\n<html> \n <head>\n <title>Setting up a PHP session</title>\n </head> \n <body>\n <?php echo ( $msg ); ?>\n </body> \n</html> " }, { "code": null, "e": 3828, "s": 3754, "text": "One executing the above html file it will display the following message βˆ’" }, { "code": null, "e": 3881, "s": 3828, "text": "You have visited this page 1 times in this session.\n" }, { "code": null, "e": 4090, "s": 3881, "text": "The number in the message keeps changing based on the number of times you refresh the page without closing the browser. For example, if you refresh 10 times, then the same page displays the following message." }, { "code": null, "e": 4144, "s": 4090, "text": "You have visited this page 16 times in this session.\n" }, { "code": null, "e": 4265, "s": 4144, "text": "Following is another example of this function, in here we have two pages from the same application in the same session βˆ’" }, { "code": null, "e": 4283, "s": 4265, "text": "session_page1.htm" }, { "code": null, "e": 4975, "s": 4283, "text": "<?php\n if(isset($_POST['SubmitButton'])){ \n //Starting the session\t\n session_start();\n $_SESSION['name'] = $_POST['name'];\n $_SESSION['age'] = $_POST['age'];\n }\n?>\n<html>\n <body>\n <form action=\"#\" method=\"post\">\n <br?> <label for=\"fname\">Enter the values click Submit and click on Next</label?> <label for=\"fname\"?>Name:</label>\n <input type=\"text\" id=\"name\" name=\"name\"><br><br>\n <label for=\"lname\"?>Age:\n <input type=\"text\" id=\"age\" name=\"age\"><br?><br> \n <input type=\"submit\" name=\"SubmitButton\"/?>\n <?php echo '<br?><br /?><a href=\"session_page2.htm\">Next</a>'; ?>\n </form>\n </body>\n</html>" }, { "code": null, "e": 5016, "s": 4975, "text": "This will produce the following output βˆ’" }, { "code": null, "e": 5068, "s": 5016, "text": "On clicking on Next the following file is executed." }, { "code": null, "e": 5086, "s": 5068, "text": "session_page2.htm" }, { "code": null, "e": 5352, "s": 5086, "text": "<html> \n <head>\n <title>Second Page</title>\n </head>\n <body>\n <?php\n //Session started\n session_start();\n print($_SESSION['name']); \n echo \"<br>\";\n print($_SESSION['age']);\n ?> \n </body> \n</html>\n" }, { "code": null, "e": 5393, "s": 5352, "text": "This will produce the following output βˆ’" }, { "code": null, "e": 5405, "s": 5393, "text": "Krishna\n30\n" }, { "code": null, "e": 5467, "s": 5405, "text": "You can pass optional array to this function as shown below βˆ’" }, { "code": null, "e": 5747, "s": 5467, "text": "<html> \n <head>\n <title>Setting up a PHP session</title>\n </head> \n <body>\n <?php\n //Starting the session\n $options = ['cookie_lifetime' => 86400,'read_and_close' => true];\n session_start($options); \n ?> \n </body> \n</html>" }, { "code": null, "e": 5780, "s": 5747, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 5796, "s": 5780, "text": " Malhar Lathkar" }, { "code": null, "e": 5829, "s": 5796, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 5840, "s": 5829, "text": " Syed Raza" }, { "code": null, "e": 5875, "s": 5840, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5892, "s": 5875, "text": " Frahaan Hussain" }, { "code": null, "e": 5925, "s": 5892, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 5940, "s": 5925, "text": " Nivedita Jain" }, { "code": null, "e": 5975, "s": 5940, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 5987, "s": 5975, "text": " Azaz Patel" }, { "code": null, "e": 6022, "s": 5987, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 6050, "s": 6022, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 6057, "s": 6050, "text": " Print" }, { "code": null, "e": 6068, "s": 6057, "text": " Add Notes" } ]
Django - Quick Guide
Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. Django makes it easier to build better web apps quickly and with less code. Note βˆ’ Django is a registered trademark of the Django Software Foundation, and is licensed under BSD License. 2003 βˆ’ Started by Adrian Holovaty and Simon Willison as an internal project at the Lawrence Journal-World newspaper. 2003 βˆ’ Started by Adrian Holovaty and Simon Willison as an internal project at the Lawrence Journal-World newspaper. 2005 βˆ’ Released July 2005 and named it Django, after the jazz guitarist Django Reinhardt. 2005 βˆ’ Released July 2005 and named it Django, after the jazz guitarist Django Reinhardt. 2005 βˆ’ Mature enough to handle several high-traffic sites. 2005 βˆ’ Mature enough to handle several high-traffic sites. Current βˆ’ Django is now an open source project with contributors across the world. Current βˆ’ Django is now an open source project with contributors across the world. Django comes with the following design philosophies βˆ’ Loosely Coupled βˆ’ Django aims to make each element of its stack independent of the others. Loosely Coupled βˆ’ Django aims to make each element of its stack independent of the others. Less Coding βˆ’ Less code so in turn a quick development. Less Coding βˆ’ Less code so in turn a quick development. Don't Repeat Yourself (DRY) βˆ’ Everything should be developed only in exactly one place instead of repeating it again and again. Don't Repeat Yourself (DRY) βˆ’ Everything should be developed only in exactly one place instead of repeating it again and again. Fast Development βˆ’ Django's philosophy is to do all it can to facilitate hyper-fast development. Fast Development βˆ’ Django's philosophy is to do all it can to facilitate hyper-fast development. Clean Design βˆ’ Django strictly maintains a clean design throughout its own code and makes it easy to follow best web-development practices. Clean Design βˆ’ Django strictly maintains a clean design throughout its own code and makes it easy to follow best web-development practices. Here are few advantages of using Django which can be listed out here βˆ’ Object-Relational Mapping (ORM) Support βˆ’ Django provides a bridge between the data model and the database engine, and supports a large set of database systems including MySQL, Oracle, Postgres, etc. Django also supports NoSQL database through Django-nonrel fork. For now, the only NoSQL databases supported are MongoDB and google app engine. Object-Relational Mapping (ORM) Support βˆ’ Django provides a bridge between the data model and the database engine, and supports a large set of database systems including MySQL, Oracle, Postgres, etc. Django also supports NoSQL database through Django-nonrel fork. For now, the only NoSQL databases supported are MongoDB and google app engine. Multilingual Support βˆ’ Django supports multilingual websites through its built-in internationalization system. So you can develop your website, which would support multiple languages. Multilingual Support βˆ’ Django supports multilingual websites through its built-in internationalization system. So you can develop your website, which would support multiple languages. Framework Support βˆ’ Django has built-in support for Ajax, RSS, Caching and various other frameworks. Framework Support βˆ’ Django has built-in support for Ajax, RSS, Caching and various other frameworks. Administration GUI βˆ’ Django provides a nice ready-to-use user interface for administrative activities. Administration GUI βˆ’ Django provides a nice ready-to-use user interface for administrative activities. Development Environment βˆ’ Django comes with a lightweight web server to facilitate end-to-end application development and testing. Development Environment βˆ’ Django comes with a lightweight web server to facilitate end-to-end application development and testing. As you already know, Django is a Python web framework. And like most modern framework, Django supports the MVC pattern. First let's see what is the Model-View-Controller (MVC) pattern, and then we will look at Django’s specificity for the Model-View-Template (MVT) pattern. When talking about applications that provides UI (web or desktop), we usually talk about MVC architecture. And as the name suggests, MVC pattern is based on three components: Model, View, and Controller. Check our MVC tutorial here to know more. The Model-View-Template (MVT) is slightly different from MVC. In fact the main difference between the two patterns is that Django itself takes care of the Controller part (Software Code that controls the interactions between the Model and View), leaving us with the template. The template is a HTML file mixed with Django Template Language (DTL). The following diagram illustrates how each of the components of the MVT pattern interacts with each other to serve a user request βˆ’ The developer provides the Model, the view and the template then just maps it to a URL and Django does the magic to serve it to the user. Django development environment consists of installing and setting up Python, Django, and a Database System. Since Django deals with web application, it's worth mentioning that you would need a web server setup as well. Django is written in 100% pure Python code, so you'll need to install Python on your system. Latest Django version requires Python 2.6.5 or higher for the 2.6.x branch or higher than 2.7.3 for the 2.7.x branch. If you're on one of the latest Linux or Mac OS X distribution, you probably already have Python installed. You can verify it by typing python command at a command prompt. If you see something like this, then Python is installed. $ python Python 2.7.5 (default, Jun 17 2014, 18:11:42) [GCC 4.8.2 20140120 (Red Hat 4.8.2-16)] on linux2 Otherwise, you can download and install the latest version of Python from the link http://www.python.org/download. Installing Django is very easy, but the steps required for its installation depends on your operating system. Since Python is a platform-independent language, Django has one package that works everywhere regardless of your operating system. You can download the latest version of Django from the link http://www.djangoproject.com/download. You have two ways of installing Django if you are running Linux or Mac OS system βˆ’ You can use the package manager of your OS, or use easy_install or pip if installed. You can use the package manager of your OS, or use easy_install or pip if installed. Install it manually using the official archive you downloaded before. Install it manually using the official archive you downloaded before. We will cover the second option as the first one depends on your OS distribution. If you have decided to follow the first option, just be careful about the version of Django you are installing. Let's say you got your archive from the link above, it should be something like Django-x.xx.tar.gz: Extract and install. $ tar xzvf Django-x.xx.tar.gz $ cd Django-x.xx $ sudo python setup.py install You can test your installation by running this command βˆ’ $ django-admin.py --version If you see the current version of Django printed on the screen, then everything is set. Note βˆ’ For some version of Django it will be django-admin the ".py" is removed. We assume you have your Django archive and python installed on your computer. First, PATH verification. On some version of windows (windows 7) you might need to make sure the Path system variable has the path the following C:\Python27\;C:\Python27\Lib\site-packages\django\bin\ in it, of course depending on your Python version. Then, extract and install Django. c:\>cd c:\Django-x.xx Next, install Django by running the following command for which you will need administrative privileges in windows shell "cmd" βˆ’ c:\Django-x.xx>python setup.py install To test your installation, open a command prompt and type the following command βˆ’ c:\>django-admin.py --version If you see the current version of Django printed on screen, then everything is set. OR Launch a "cmd" prompt and type python then βˆ’ c:\> python >>> import django >>> print django.get_version() Django supports several major database engines and you can set up any of them based on your comfort. MySQL (http://www.mysql.com/) PostgreSQL (http://www.postgresql.org/) SQLite 3 (http://www.sqlite.org/) Oracle (http://www.oracle.com/) MongoDb (https://django-mongodb-engine.readthedocs.org) GoogleAppEngine Datastore (https://cloud.google.com/appengine/articles/django-nonrel) You can refer to respective documentation to installing and configuring a database of your choice. Note βˆ’ Number 5 and 6 are NoSQL databases. Django comes with a lightweight web server for developing and testing applications. This server is pre-configured to work with Django, and more importantly, it restarts whenever you modify the code. However, Django does support Apache and other popular web servers such as Lighttpd. We will discuss both the approaches in coming chapters while working with different examples. Now that we have installed Django, let's start using it. In Django, every web app you want to create is called a project; and a project is a sum of applications. An application is a set of code files relying on the MVT pattern. As example let's say we want to build a website, the website is our project and, the forum, news, contact engine are applications. This structure makes it easier to move an application between projects since every application is independent. Whether you are on Windows or Linux, just get a terminal or a cmd prompt and navigate to the place you want your project to be created, then use this code βˆ’ $ django-admin startproject myproject This will create a "myproject" folder with the following structure βˆ’ myproject/ manage.py myproject/ __init__.py settings.py urls.py wsgi.py The β€œmyproject” folder is just your project container, it actually contains two elements βˆ’ manage.py βˆ’ This file is kind of your project local django-admin for interacting with your project via command line (start the development server, sync db...). To get a full list of command accessible via manage.py you can use the code βˆ’ manage.py βˆ’ This file is kind of your project local django-admin for interacting with your project via command line (start the development server, sync db...). To get a full list of command accessible via manage.py you can use the code βˆ’ $ python manage.py help The β€œmyproject” subfolder βˆ’ This folder is the actual python package of your project. It contains four files βˆ’ __init__.py βˆ’ Just for python, treat this folder as package. settings.py βˆ’ As the name indicates, your project settings. urls.py βˆ’ All links of your project and the function to call. A kind of ToC of your project. wsgi.py βˆ’ If you need to deploy your project over WSGI. The β€œmyproject” subfolder βˆ’ This folder is the actual python package of your project. It contains four files βˆ’ __init__.py βˆ’ Just for python, treat this folder as package. __init__.py βˆ’ Just for python, treat this folder as package. settings.py βˆ’ As the name indicates, your project settings. settings.py βˆ’ As the name indicates, your project settings. urls.py βˆ’ All links of your project and the function to call. A kind of ToC of your project. urls.py βˆ’ All links of your project and the function to call. A kind of ToC of your project. wsgi.py βˆ’ If you need to deploy your project over WSGI. wsgi.py βˆ’ If you need to deploy your project over WSGI. Your project is set up in the subfolder myproject/settings.py. Following are some important options you might need to set βˆ’ DEBUG = True This option lets you set if your project is in debug mode or not. Debug mode lets you get more information about your project's error. Never set it to β€˜True’ for a live project. However, this has to be set to β€˜True’ if you want the Django light server to serve static files. Do it only in the development mode. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'database.sql', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } Database is set in the β€˜Database’ dictionary. The example above is for SQLite engine. As stated earlier, Django also supports βˆ’ MySQL (django.db.backends.mysql) PostGreSQL (django.db.backends.postgresql_psycopg2) Oracle (django.db.backends.oracle) and NoSQL DB MongoDB (django_mongodb_engine) Before setting any new engine, make sure you have the correct db driver installed. You can also set others options like: TIME_ZONE, LANGUAGE_CODE, TEMPLATE... Now that your project is created and configured make sure it's working βˆ’ $ python manage.py runserver You will get something like the following on running the above code βˆ’ Validating models... 0 errors found September 03, 2015 - 11:41:50 Django version 1.6.11, using settings 'myproject.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. A project is a sum of many applications. Every application has an objective and can be reused into another project, like the contact form on a website can be an application, and can be reused for others. See it as a module of your project. We assume you are in your project folder. In our main β€œmyproject” folder, the same folder then manage.py βˆ’ $ python manage.py startapp myapp You just created myapp application and like project, Django create a β€œmyapp” folder with the application structure βˆ’ myapp/ __init__.py admin.py models.py tests.py views.py __init__.py βˆ’ Just to make sure python handles this folder as a package. __init__.py βˆ’ Just to make sure python handles this folder as a package. admin.py βˆ’ This file helps you make the app modifiable in the admin interface. admin.py βˆ’ This file helps you make the app modifiable in the admin interface. models.py βˆ’ This is where all the application models are stored. models.py βˆ’ This is where all the application models are stored. tests.py βˆ’ This is where your unit tests are. tests.py βˆ’ This is where your unit tests are. views.py βˆ’ This is where your application views are. views.py βˆ’ This is where your application views are. At this stage we have our "myapp" application, now we need to register it with our Django project "myproject". To do so, update INSTALLED_APPS tuple in the settings.py file of your project (add your app name) βˆ’ INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', ) Django provides a ready-to-use user interface for administrative activities. We all know how an admin interface is important for a web project. Django automatically generates admin UI based on your project models. The Admin interface depends on the django.countrib module. To have it working you need to make sure some modules are imported in the INSTALLED_APPS and MIDDLEWARE_CLASSES tuples of the myproject/settings.py file. For INSTALLED_APPS make sure you have βˆ’ INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', ) For MIDDLEWARE_CLASSES βˆ’ MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) Before launching your server, to access your Admin Interface, you need to initiate the database βˆ’ $ python manage.py migrate syncdb will create necessary tables or collections depending on your db type, necessary for the admin interface to run. Even if you don't have a superuser, you will be prompted to create one. If you already have a superuser or have forgotten it, you can always create one using the following code βˆ’ $ python manage.py createsuperuser Now to start the Admin Interface, we need to make sure we have configured a URL for our admin interface. Open the myproject/url.py and you should have something like βˆ’ from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'myproject.views.home', name = 'home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), ) Now just run the server. $ python manage.py runserver And your admin interface is accessible at: http://127.0.0.1:8000/admin/ Once connected with your superuser account, you will see the following screen βˆ’ That interface will let you administrate Django groups and users, and all registered models in your app. The interface gives you the ability to do at least the "CRUD" (Create, Read, Update, Delete) operations on your models. A view function, or β€œview” for short, is simply a Python function that takes a web request and returns a web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image, etc. Example: You use view to create web pages, note that you need to associate a view to a URL to see it as a web page. In Django, views have to be created in the app views.py file. We will create a simple view in myapp to say "welcome to my app!" See the following view βˆ’ from django.http import HttpResponse def hello(request): text = """<h1>welcome to my app !</h1>""" return HttpResponse(text) In this view, we use HttpResponse to render the HTML (as you have probably noticed we have the HTML hard coded in the view). To see this view as a page we just need to map it to a URL (this will be discussed in an upcoming chapter). We used HttpResponse to render the HTML in the view before. This is not the best way to render pages. Django supports the MVT pattern so to make the precedent view, Django - MVT like, we will need βˆ’ A template: myapp/templates/hello.html And now our view will look like βˆ’ from django.shortcuts import render def hello(request): return render(request, "myapp/template/hello.html", {}) Views can also accept parameters βˆ’ from django.http import HttpResponse def hello(request, number): text = "<h1>welcome to my app number %s!</h1>"% number return HttpResponse(text) When linked to a URL, the page will display the number passed as a parameter. Note that the parameters will be passed via the URL (discussed in the next chapter). Now that we have a working view as explained in the previous chapters. We want to access that view via a URL. Django has his own way for URL mapping and it's done by editing your project url.py file (myproject/url.py). The url.py file looks like βˆ’ from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', #Examples #url(r'^$', 'myproject.view.home', name = 'home'), #url(r'^blog/', include('blog.urls')), url(r'^admin', include(admin.site.urls)), ) When a user makes a request for a page on your web app, Django controller takes over to look for the corresponding view via the url.py file, and then return the HTML response or a 404 not found error, if not found. In url.py, the most important thing is the "urlpatterns" tuple. It’s where you define the mapping between URLs and views. A mapping is a tuple in URL patterns like βˆ’ from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', #Examples #url(r'^$', 'myproject.view.home', name = 'home'), #url(r'^blog/', include('blog.urls')), url(r'^admin', include(admin.site.urls)), url(r'^hello/', 'myapp.views.hello', name = 'hello'), ) The marked line maps the URL "/home" to the hello view created in myapp/view.py file. As you can see above a mapping is composed of three elements βˆ’ The pattern βˆ’ A regexp matching the URL you want to be resolved and map. Everything that can work with the python 're' module is eligible for the pattern (useful when you want to pass parameters via url). The pattern βˆ’ A regexp matching the URL you want to be resolved and map. Everything that can work with the python 're' module is eligible for the pattern (useful when you want to pass parameters via url). The python path to the view βˆ’ Same as when you are importing a module. The python path to the view βˆ’ Same as when you are importing a module. The name βˆ’ In order to perform URL reversing, you’ll need to use named URL patterns as done in the examples above. Once done, just start the server to access your view via :http://127.0.0.1/hello The name βˆ’ In order to perform URL reversing, you’ll need to use named URL patterns as done in the examples above. Once done, just start the server to access your view via :http://127.0.0.1/hello So far, we have created the URLs in β€œmyprojects/url.py” file, however as stated earlier about Django and creating an app, the best point was to be able to reuse applications in different projects. You can easily see what the problem is, if you are saving all your URLs in the β€œprojecturl.py” file. So best practice is to create an β€œurl.py” per application and to include it in our main projects url.py file (we included admin URLs for admin interface before). We need to create an url.py file in myapp using the following code βˆ’ from django.conf.urls import patterns, include, url urlpatterns = patterns('', url(r'^hello/', 'myapp.views.hello', name = 'hello'),) Then myproject/url.py will change to the following βˆ’ from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', #Examples #url(r'^$', 'myproject.view.home', name = 'home'), #url(r'^blog/', include('blog.urls')), url(r'^admin', include(admin.site.urls)), url(r'^myapp/', include('myapp.urls')), ) We have included all URLs from myapp application. The home.html that was accessed through β€œ/hello” is now β€œ/myapp/hello” which is a better and more understandable structure for the web app. Now let's imagine we have another view in myapp β€œmorning” and we want to map it in myapp/url.py, we will then change our myapp/url.py to βˆ’ from django.conf.urls import patterns, include, url urlpatterns = patterns('', url(r'^hello/', 'myapp.views.hello', name = 'hello'), url(r'^morning/', 'myapp.views.morning', name = 'morning'), ) This can be re-factored to βˆ’ from django.conf.urls import patterns, include, url urlpatterns = patterns('myapp.views', url(r'^hello/', 'hello', name = 'hello'), url(r'^morning/', 'morning', name = 'morning'),) As you can see, we now use the first element of our urlpatterns tuple. This can be useful when you want to change your app name. We now know how to map URL, how to organize them, now let us see how to send parameters to views. A classic sample is the article example (you want to access an article via β€œ/articles/article_id”). Passing parameters is done by capturing them with the regexp in the URL pattern. If we have a view like the following one in β€œmyapp/view.py” from django.shortcuts import render from django.http import HttpResponse def hello(request): return render(request, "hello.html", {}) def viewArticle(request, articleId): text = "Displaying article Number : %s"%articleId return HttpResponse(text) We want to map it in myapp/url.py so we can access it via β€œ/myapp/article/articleId”, we need the following in β€œmyapp/url.py” βˆ’ from django.conf.urls import patterns, include, url urlpatterns = patterns('myapp.views', url(r'^hello/', 'hello', name = 'hello'), url(r'^morning/', 'morning', name = 'morning'), url(r'^article/(\d+)/', 'viewArticle', name = 'article'),) When Django will see the url: β€œ/myapp/article/42” it will pass the parameters '42' to the viewArticle view, and in your browser you should get the following result βˆ’ Note that the order of parameters is important here. Suppose we want the list of articles of a month of a year, let's add a viewArticles view. Our view.py becomes βˆ’ from django.shortcuts import render from django.http import HttpResponse def hello(request): return render(request, "hello.html", {}) def viewArticle(request, articleId): text = "Displaying article Number : %s"%articleId return HttpResponse(text) def viewArticles(request, month, year): text = "Displaying articles of : %s/%s"%(year, month) return HttpResponse(text) The corresponding url.py file will look like βˆ’ from django.conf.urls import patterns, include, url urlpatterns = patterns('myapp.views', url(r'^hello/', 'hello', name = 'hello'), url(r'^morning/', 'morning', name = 'morning'), url(r'^article/(\d+)/', 'viewArticle', name = 'article'), url(r'^articles/(\d{2})/(\d{4})', 'viewArticles', name = 'articles'),) Now when you go to β€œ/myapp/articles/12/2006/” you will get 'Displaying articles of: 2006/12' but if you reverse the parameters you won’t get the same result. To avoid that, it is possible to link a URL parameter to the view parameter. For that, our url.py will become βˆ’ from django.conf.urls import patterns, include, url urlpatterns = patterns('myapp.views', url(r'^hello/', 'hello', name = 'hello'), url(r'^morning/', 'morning', name = 'morning'), url(r'^article/(\d+)/', 'viewArticle', name = 'article'), url(r'^articles/(?P\d{2})/(?P\d{4})', 'viewArticles', name = 'articles'),) Django makes it possible to separate python and HTML, the python goes in views and HTML goes in templates. To link the two, Django relies on the render function and the Django Template language. This function takes three parameters βˆ’ Request βˆ’ The initial request. Request βˆ’ The initial request. The path to the template βˆ’ This is the path relative to the TEMPLATE_DIRS option in the project settings.py variables. The path to the template βˆ’ This is the path relative to the TEMPLATE_DIRS option in the project settings.py variables. Dictionary of parameters βˆ’ A dictionary that contains all variables needed in the template. This variable can be created or you can use locals() to pass all local variable declared in the view. Dictionary of parameters βˆ’ A dictionary that contains all variables needed in the template. This variable can be created or you can use locals() to pass all local variable declared in the view. Django’s template engine offers a mini-language to define the user-facing layer of the application. A variable looks like this: {{variable}}. The template replaces the variable by the variable sent by the view in the third parameter of the render function. Let's change our hello.html to display today’s date βˆ’ hello.html <html> <body> Hello World!!!<p>Today is {{today}}</p> </body> </html> Then our view will change to βˆ’ def hello(request): today = datetime.datetime.now().date() return render(request, "hello.html", {"today" : today}) We will now get the following output after accessing the URL/myapp/hello βˆ’ Hello World!!! Today is Sept. 11, 2015 As you have probably noticed, if the variable is not a string, Django will use the __str__ method to display it; and with the same principle you can access an object attribute just like you do it in Python. For example: if we wanted to display the date year, my variable would be: {{today.year}}. They help you modify variables at display time. Filters structure looks like the following: {{var|filters}}. Some examples βˆ’ {{string|truncatewords:80}} βˆ’ This filter will truncate the string, so you will see only the first 80 words. {{string|truncatewords:80}} βˆ’ This filter will truncate the string, so you will see only the first 80 words. {{string|lower}} βˆ’ Converts the string to lowercase. {{string|lower}} βˆ’ Converts the string to lowercase. {{string|escape|linebreaks}} βˆ’ Escapes string contents, then converts line breaks to tags. {{string|escape|linebreaks}} βˆ’ Escapes string contents, then converts line breaks to tags. You can also set the default for a variable. Tags lets you perform the following operations: if condition, for loop, template inheritance and more. Just like in Python you can use if, else and elif in your template βˆ’ <html> <body> Hello World!!!<p>Today is {{today}}</p> We are {% if today.day == 1 %} the first day of month. {% elif today.day == 30 %} the last day of month. {% else %} I don't know. {%endif%} </body> </html> In this new template, depending on the date of the day, the template will render a certain value. Just like 'if', we have the 'for' tag, that works exactly like in Python. Let's change our hello view to transmit a list to our template βˆ’ def hello(request): today = datetime.datetime.now().date() daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] return render(request, "hello.html", {"today" : today, "days_of_week" : daysOfWeek}) The template to display that list using {{ for }} βˆ’ <html> <body> Hello World!!!<p>Today is {{today}}</p> We are {% if today.day == 1 %} the first day of month. {% elif today.day == 30 %} the last day of month. {% else %} I don't know. {%endif%} <p> {% for day in days_of_week %} {{day}} </p> {% endfor %} </body> </html> And we should get something like βˆ’ Hello World!!! Today is Sept. 11, 2015 We are I don't know. Mon Tue Wed Thu Fri Sat Sun A template system cannot be complete without template inheritance. Meaning when you are designing your templates, you should have a main template with holes that the child's template will fill according to his own need, like a page might need a special css for the selected tab. Let’s change the hello.html template to inherit from a main_template.html. main_template.html <html> <head> <title> {% block title %}Page Title{% endblock %} </title> </head> <body> {% block content %} Body content {% endblock %} </body> </html> hello.html {% extends "main_template.html" %} {% block title %}My Hello Page{% endblock %} {% block content %} Hello World!!!<p>Today is {{today}}</p> We are {% if today.day == 1 %} the first day of month. {% elif today.day == 30 %} the last day of month. {% else %} I don't know. {%endif%} <p> {% for day in days_of_week %} {{day}} </p> {% endfor %} {% endblock %} In the above example, on calling /myapp/hello we will still get the same result as before but now we rely on extends and block to refactor our code βˆ’ In the main_template.html we define blocks using the tag block. The title block will contain the page title and the content block will have the page main content. In home.html we use extends to inherit from the main_template.html then we fill the block define above (content and title). The comment tag helps to define comments into templates, not HTML comments, they won’t appear in HTML page. It can be useful for documentation or just commenting a line of code. A model is a class that represents table or collection in our DB, and where every attribute of the class is a field of the table or collection. Models are defined in the app/models.py (in our example: myapp/models.py) Following is a Dreamreal model created as an example βˆ’ from django.db import models class Dreamreal(models.Model): website = models.CharField(max_length = 50) mail = models.CharField(max_length = 50) name = models.CharField(max_length = 50) phonenumber = models.IntegerField() class Meta: db_table = "dreamreal" Every model inherits from django.db.models.Model. Our class has 4 attributes (3 CharField and 1 Integer), those will be the table fields. The Meta class with the db_table attribute lets us define the actual table or collection name. Django names the table or collection automatically: myapp_modelName. This class will let you force the name of the table to what you like. There is more field's type in django.db.models, you can learn more about them on https://docs.djangoproject.com/en/1.5/ref/models/fields/#field-types After creating your model, you will need Django to generate the actual database βˆ’ $python manage.py syncdb Let's create a "crudops" view to see how we can do CRUD operations on models. Our myapp/views.py will then look like βˆ’ myapp/views.py from myapp.models import Dreamreal from django.http import HttpResponse def crudops(request): #Creating an entry dreamreal = Dreamreal( website = "www.polo.com", mail = "sorex@polo.com", name = "sorex", phonenumber = "002376970" ) dreamreal.save() #Read ALL entries objects = Dreamreal.objects.all() res ='Printing all Dreamreal entries in the DB : <br>' for elt in objects: res += elt.name+"<br>" #Read a specific entry: sorex = Dreamreal.objects.get(name = "sorex") res += 'Printing One entry <br>' res += sorex.name #Delete an entry res += '<br> Deleting an entry <br>' sorex.delete() #Update dreamreal = Dreamreal( website = "www.polo.com", mail = "sorex@polo.com", name = "sorex", phonenumber = "002376970" ) dreamreal.save() res += 'Updating entry<br>' dreamreal = Dreamreal.objects.get(name = 'sorex') dreamreal.name = 'thierry' dreamreal.save() return HttpResponse(res) Let's explore other manipulations we can do on Models. Note that the CRUD operations were done on instances of our model, now we will be working directly with the class representing our model. Let's create a 'datamanipulation' view in myapp/views.py from myapp.models import Dreamreal from django.http import HttpResponse def datamanipulation(request): res = '' #Filtering data: qs = Dreamreal.objects.filter(name = "paul") res += "Found : %s results<br>"%len(qs) #Ordering results qs = Dreamreal.objects.order_by("name") for elt in qs: res += elt.name + '<br>' return HttpResponse(res) Django ORM offers 3 ways to link models βˆ’ One of the first case we will see here is the one-to-many relationships. As you can see in the above example, Dreamreal company can have multiple online websites. Defining that relation is done by using django.db.models.ForeignKey βˆ’ myapp/models.py from django.db import models class Dreamreal(models.Model): website = models.CharField(max_length = 50) mail = models.CharField(max_length = 50) name = models.CharField(max_length = 50) phonenumber = models.IntegerField() online = models.ForeignKey('Online', default = 1) class Meta: db_table = "dreamreal" class Online(models.Model): domain = models.CharField(max_length = 30) class Meta: db_table = "online" As you can see in our updated myapp/models.py, we added the online model and linked it to our Dreamreal model. Let's check how all of this is working via manage.py shell βˆ’ First let’s create some companies (Dreamreal entries) for testing in our Django shell βˆ’ $python manage.py shell >>> from myapp.models import Dreamreal, Online >>> dr1 = Dreamreal() >>> dr1.website = 'company1.com' >>> dr1.name = 'company1' >>> dr1.mail = 'contact@company1' >>> dr1.phonenumber = '12345' >>> dr1.save() >>> dr2 = Dreamreal() >>> dr1.website = 'company2.com' >>> dr2.website = 'company2.com' >>> dr2.name = 'company2' >>> dr2.mail = 'contact@company2' >>> dr2.phonenumber = '56789' >>> dr2.save() Now some hosted domains βˆ’ >>> on1 = Online() >>> on1.company = dr1 >>> on1.domain = "site1.com" >>> on2 = Online() >>> on2.company = dr1 >>> on2.domain = "site2.com" >>> on3 = Online() >>> on3.domain = "site3.com" >>> dr2 = Dreamreal.objects.all()[2] >>> on3.company = dr2 >>> on1.save() >>> on2.save() >>> on3.save() Accessing attribute of the hosting company (Dreamreal entry) from an online domain is simple βˆ’ >>> on1.company.name And if we want to know all the online domain hosted by a Company in Dreamreal we will use the code βˆ’ >>> dr1.online_set.all() To get a QuerySet, note that all manipulating method we have seen before (filter, all, exclude, order_by....) You can also access the linked model attributes for filtering operations, let's say you want to get all online domains where the Dreamreal name contains 'company' βˆ’ >>> Online.objects.filter(company__name__contains = 'company' Note βˆ’ That kind of query is just supported for SQL DB. It won’t work for non-relational DB where joins doesn’t exist and there are two '_'. But that's not the only way to link models, you also have OneToOneField, a link that guarantees that the relation between two objects is unique. If we used the OneToOneField in our example above, that would mean for every Dreamreal entry only one Online entry is possible and in the other way to. And the last one, the ManyToManyField for (n-n) relation between tables. Note, those are relevant for SQL based DB. Page redirection is needed for many reasons in web application. You might want to redirect a user to another page when a specific action occurs, or basically in case of error. For example, when a user logs in to your website, he is often redirected either to the main home page or to his personal dashboard. In Django, redirection is accomplished using the 'redirect' method. The 'redirect' method takes as argument: The URL you want to be redirected to as string A view's name. The myapp/views looks like the following so far βˆ’ def hello(request): today = datetime.datetime.now().date() daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] return render(request, "hello.html", {"today" : today, "days_of_week" : daysOfWeek}) def viewArticle(request, articleId): """ A view that display an article based on his ID""" text = "Displaying article Number : %s" %articleId return HttpResponse(text) def viewArticles(request, year, month): text = "Displaying articles of : %s/%s"%(year, month) return HttpResponse(text) Let's change the hello view to redirect to djangoproject.com and our viewArticle to redirect to our internal '/myapp/articles'. To do so the myapp/view.py will change to βˆ’ from django.shortcuts import render, redirect from django.http import HttpResponse import datetime # Create your views here. def hello(request): today = datetime.datetime.now().date() daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] return redirect("https://www.djangoproject.com") def viewArticle(request, articleId): """ A view that display an article based on his ID""" text = "Displaying article Number : %s" %articleId return redirect(viewArticles, year = "2045", month = "02") def viewArticles(request, year, month): text = "Displaying articles of : %s/%s"%(year, month) return HttpResponse(text) In the above example, first we imported redirect from django.shortcuts and for redirection to the Django official website we just pass the full URL to the 'redirect' method as string, and for the second example (the viewArticle view) the 'redirect' method takes the view name and his parameters as arguments. Accessing /myapp/hello, will give you the following screen βˆ’ And accessing /myapp/article/42, will give you the following screen βˆ’ It is also possible to specify whether the 'redirect' is temporary or permanent by adding permanent = True parameter. The user will see no difference, but these are details that search engines take into account when ranking of your website. Also remember that 'name' parameter we defined in our url.py while mapping the URLs βˆ’ url(r'^articles/(?P\d{2})/(?P\d{4})/', 'viewArticles', name = 'articles'), That name (here article) can be used as argument for the 'redirect' method, then our viewArticle redirection can be changed from βˆ’ def viewArticle(request, articleId): """ A view that display an article based on his ID""" text = "Displaying article Number : %s" %articleId return redirect(viewArticles, year = "2045", month = "02") To βˆ’ def viewArticle(request, articleId): """ A view that display an article based on his ID""" text = "Displaying article Number : %s" %articleId return redirect(articles, year = "2045", month = "02") Note βˆ’ There is also a function to generate URLs; it is used in the same way as redirect; the 'reverse' method (django.core.urlresolvers.reverse). This function does not return a HttpResponseRedirect object, but simply a string containing the URL to the view compiled with any passed argument. Django comes with a ready and easy-to-use light engine to send e-mail. Similar to Python you just need an import of smtplib. In Django you just need to import django.core.mail. To start sending e-mail, edit your project settings.py file and set the following options βˆ’ EMAIL_HOST βˆ’ smtp server. EMAIL_HOST βˆ’ smtp server. EMAIL_HOST_USER βˆ’ Login credential for the smtp server. EMAIL_HOST_USER βˆ’ Login credential for the smtp server. EMAIL_HOST_PASSWORD βˆ’ Password credential for the smtp server. EMAIL_HOST_PASSWORD βˆ’ Password credential for the smtp server. EMAIL_PORT βˆ’ smtp server port. EMAIL_PORT βˆ’ smtp server port. EMAIL_USE_TLS or _SSL βˆ’ True if secure connection. EMAIL_USE_TLS or _SSL βˆ’ True if secure connection. Let's create a "sendSimpleEmail" view to send a simple e-mail. from django.core.mail import send_mail from django.http import HttpResponse def sendSimpleEmail(request,emailto): res = send_mail("hello paul", "comment tu vas?", "paul@polo.com", [emailto]) return HttpResponse('%s'%res) Here is the details of the parameters of send_mail βˆ’ subject βˆ’ E-mail subject. subject βˆ’ E-mail subject. message βˆ’ E-mail body. message βˆ’ E-mail body. from_email βˆ’ E-mail from. from_email βˆ’ E-mail from. recipient_list βˆ’ List of receivers’ e-mail address. recipient_list βˆ’ List of receivers’ e-mail address. fail_silently βˆ’ Bool, if false send_mail will raise an exception in case of error. fail_silently βˆ’ Bool, if false send_mail will raise an exception in case of error. auth_user βˆ’ User login if not set in settings.py. auth_user βˆ’ User login if not set in settings.py. auth_password βˆ’ User password if not set in settings.py. auth_password βˆ’ User password if not set in settings.py. connection βˆ’ E-mail backend. connection βˆ’ E-mail backend. html_message βˆ’ (new in Django 1.7) if present, the e-mail will be multipart/alternative. html_message βˆ’ (new in Django 1.7) if present, the e-mail will be multipart/alternative. Let's create a URL to access our view βˆ’ from django.conf.urls import patterns, url urlpatterns = paterns('myapp.views', url(r'^simpleemail/(?P<emailto> [\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/', 'sendSimpleEmail' , name = 'sendSimpleEmail'),) So when accessing /myapp/simpleemail/polo@gmail.com, you will get the following page βˆ’ The method returns the number of messages successfully delivered. This is same as send_mail but takes an extra parameter; datatuple, our sendMassEmail view will then be βˆ’ from django.core.mail import send_mass_mail from django.http import HttpResponse def sendMassEmail(request,emailto): msg1 = ('subject 1', 'message 1', 'polo@polo.com', [emailto1]) msg2 = ('subject 2', 'message 2', 'polo@polo.com', [emailto2]) res = send_mass_mail((msg1, msg2), fail_silently = False) return HttpResponse('%s'%res) Let's create a URL to access our view βˆ’ from django.conf.urls import patterns, url urlpatterns = paterns('myapp.views', url(r'^massEmail/(?P<emailto1> [\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/(?P<emailto2> [\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})', 'sendMassEmail' , name = 'sendMassEmail'),) When accessing /myapp/massemail/polo@gmail.com/sorex@gmail.com/, we get βˆ’ send_mass_mail parameters details are βˆ’ datatuples βˆ’ A tuple where each element is like (subject, message, from_email, recipient_list). datatuples βˆ’ A tuple where each element is like (subject, message, from_email, recipient_list). fail_silently βˆ’ Bool, if false send_mail will raise an exception in case of error. fail_silently βˆ’ Bool, if false send_mail will raise an exception in case of error. auth_user βˆ’ User login if not set in settings.py. auth_user βˆ’ User login if not set in settings.py. auth_password βˆ’ User password if not set in settings.py. auth_password βˆ’ User password if not set in settings.py. connection βˆ’ E-mail backend. connection βˆ’ E-mail backend. As you can see in the above image, two messages were sent successfully. Note βˆ’ In this example we are using Python smtp debuggingserver, that you can launch using βˆ’ $python -m smtpd -n -c DebuggingServer localhost:1025 This means all your sent e-mails will be printed on stdout, and the dummy server is running on localhost:1025. Sending e-mails to admins and managers using mail_admins and mail_managers methods These methods send e-mails to site administrators as defined in the ADMINS option of the settings.py file, and to site managers as defined in MANAGERS option of the settings.py file. Let's assume our ADMINS and MANAGERS options look like βˆ’ ADMINS = (('polo', 'polo@polo.com'),) MANAGERS = (('popoli', 'popoli@polo.com'),) from django.core.mail import mail_admins from django.http import HttpResponse def sendAdminsEmail(request): res = mail_admins('my subject', 'site is going down.') return HttpResponse('%s'%res) The above code will send an e-mail to every admin defined in the ADMINS section. from django.core.mail import mail_managers from django.http import HttpResponse def sendManagersEmail(request): res = mail_managers('my subject 2', 'Change date on the site.') return HttpResponse('%s'%res) The above code will send an e-mail to every manager defined in the MANAGERS section. Parameters details βˆ’ Subject βˆ’ E-mail subject. Subject βˆ’ E-mail subject. message βˆ’ E-mail body. message βˆ’ E-mail body. fail_silently βˆ’ Bool, if false send_mail will raise an exception in case of error. fail_silently βˆ’ Bool, if false send_mail will raise an exception in case of error. connection βˆ’ E-mail backend. connection βˆ’ E-mail backend. html_message βˆ’ (new in Django 1.7) if present, the e-mail will be multipart/alternative. html_message βˆ’ (new in Django 1.7) if present, the e-mail will be multipart/alternative. Sending HTML message in Django >= 1.7 is as easy as βˆ’ from django.core.mail import send_mail from django.http import HttpResponse res = send_mail("hello paul", "comment tu vas?", "paul@polo.com", ["polo@gmail.com"], html_message=") This will produce a multipart/alternative e-mail. But for Django < 1.7 sending HTML messages is done via the django.core.mail.EmailMessage class then calling 'send' on the object βˆ’ Let's create a "sendHTMLEmail" view to send an HTML e-mail. from django.core.mail import EmailMessage from django.http import HttpResponse def sendHTMLEmail(request , emailto): html_content = "<strong>Comment tu vas?</strong>" email = EmailMessage("my subject", html_content, "paul@polo.com", [emailto]) email.content_subtype = "html" res = email.send() return HttpResponse('%s'%res) Parameters details for the EmailMessage class creation βˆ’ Subject βˆ’ E-mail subject. Subject βˆ’ E-mail subject. message βˆ’ E-mail body in HTML. message βˆ’ E-mail body in HTML. from_email βˆ’ E-mail from. from_email βˆ’ E-mail from. to βˆ’ List of receivers’ e-mail address. to βˆ’ List of receivers’ e-mail address. bcc βˆ’ List of β€œBcc” receivers’ e-mail address. bcc βˆ’ List of β€œBcc” receivers’ e-mail address. connection βˆ’ E-mail backend. connection βˆ’ E-mail backend. Let's create a URL to access our view βˆ’ from django.conf.urls import patterns, url urlpatterns = paterns('myapp.views', url(r'^htmlemail/(?P<emailto> [\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/', 'sendHTMLEmail' , name = 'sendHTMLEmail'),) When accessing /myapp/htmlemail/polo@gmail.com, we get βˆ’ This is done by using the 'attach' method on the EmailMessage object. A view to send an e-mail with attachment will be βˆ’ from django.core.mail import EmailMessage from django.http import HttpResponse def sendEmailWithAttach(request, emailto): html_content = "Comment tu vas?" email = EmailMessage("my subject", html_content, "paul@polo.com", emailto]) email.content_subtype = "html" fd = open('manage.py', 'r') email.attach('manage.py', fd.read(), 'text/plain') res = email.send() return HttpResponse('%s'%res) Details on attach arguments βˆ’ filename βˆ’ The name of the file to attach. filename βˆ’ The name of the file to attach. content βˆ’ The content of the file to attach. content βˆ’ The content of the file to attach. mimetype βˆ’ The attachment's content mime type. mimetype βˆ’ The attachment's content mime type. In some cases, writing views, as we have seen earlier is really heavy. Imagine you need a static page or a listing page. Django offers an easy way to set those simple views that is called generic views. Unlike classic views, generic views are classes not functions. Django offers a set of classes for generic views in django.views.generic, and every generic view is one of those classes or a class that inherits from one of them. There are 10+ generic classes βˆ’ >>> import django.views.generic >>> dir(django.views.generic) ['ArchiveIndexView', 'CreateView', 'DateDetailView', 'DayArchiveView', 'DeleteView', 'DetailView', 'FormView', 'GenericViewError', 'ListView', 'MonthArchiveView', 'RedirectView', 'TemplateView', 'TodayArchiveView', 'UpdateView', 'View', 'WeekArchiveView', 'YearArchiveView', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'base', 'dates', 'detail', 'edit', 'list'] This you can use for your generic view. Let's look at some example to see how it works. Let's publish a static page from the β€œstatic.html” template. Our static.html βˆ’ <html> <body> This is a static page!!! </body> </html> If we did that the way we learned before, we would have to change the myapp/views.py to be βˆ’ from django.shortcuts import render def static(request): return render(request, 'static.html', {}) and myapp/urls.py to be βˆ’ from django.conf.urls import patterns, url urlpatterns = patterns("myapp.views", url(r'^static/', 'static', name = 'static'),) The best way is to use generic views. For that, our myapp/views.py will become βˆ’ from django.views.generic import TemplateView class StaticView(TemplateView): template_name = "static.html" And our myapp/urls.py we will be βˆ’ from myapp.views import StaticView from django.conf.urls import patterns urlpatterns = patterns("myapp.views", (r'^static/$', StaticView.as_view()),) When accessing /myapp/static you get βˆ’ For the same result we can also, do the following βˆ’ No change in the views.py Change the url.py file to be βˆ’ from django.views.generic import TemplateView from django.conf.urls import patterns, url urlpatterns = patterns("myapp.views", url(r'^static/',TemplateView.as_view(template_name = 'static.html')),) As you can see, you just need to change the url.py file in the second method. We are going to list all entries in our Dreamreal model. Doing so is made easy by using the ListView generic view class. Edit the url.py file and update it as βˆ’ from django.views.generic import ListView from django.conf.urls import patterns, url urlpatterns = patterns( "myapp.views", url(r'^dreamreals/', ListView.as_view(model = Dreamreal, template_name = "dreamreal_list.html")), ) Important to note at this point is that the variable pass by the generic view to the template is object_list. If you want to name it yourself, you will need to add a context_object_name argument to the as_view method. Then the url.py will become βˆ’ from django.views.generic import ListView from django.conf.urls import patterns, url urlpatterns = patterns("myapp.views", url(r'^dreamreals/', ListView.as_view( template_name = "dreamreal_list.html")), model = Dreamreal, context_object_name = ”dreamreals_objects” ,) The associated template will then be βˆ’ {% extends "main_template.html" %} {% block content %} Dreamreals:<p> {% for dr in object_list %} {{dr.name}}</p> {% endfor %} {% endblock %} Accessing /myapp/dreamreals/ will produce the following page βˆ’ Creating forms in Django, is really similar to creating a model. Here again, we just need to inherit from Django class and the class attributes will be the form fields. Let's add a forms.py file in myapp folder to contain our app forms. We will create a login form. myapp/forms.py #-*- coding: utf-8 -*- from django import forms class LoginForm(forms.Form): user = forms.CharField(max_length = 100) password = forms.CharField(widget = forms.PasswordInput()) As seen above, the field type can take "widget" argument for html rendering; in our case, we want the password to be hidden, not displayed. Many others widget are present in Django: DateInput for dates, CheckboxInput for checkboxes, etc. There are two kinds of HTTP requests, GET and POST. In Django, the request object passed as parameter to your view has an attribute called "method" where the type of the request is set, and all data passed via POST can be accessed via the request.POST dictionary. Let's create a login view in our myapp/views.py βˆ’ #-*- coding: utf-8 -*- from myapp.forms import LoginForm def login(request): username = "not logged in" if request.method == "POST": #Get the posted form MyLoginForm = LoginForm(request.POST) if MyLoginForm.is_valid(): username = MyLoginForm.cleaned_data['username'] else: MyLoginForm = Loginform() return render(request, 'loggedin.html', {"username" : username}) The view will display the result of the login form posted through the loggedin.html. To test it, we will first need the login form template. Let's call it login.html. <html> <body> <form name = "form" action = "{% url "myapp.views.login" %}" method = "POST" >{% csrf_token %} <div style = "max-width:470px;"> <center> <input type = "text" style = "margin-left:20%;" placeholder = "Identifiant" name = "username" /> </center> </div> <br> <div style = "max-width:470px;"> <center> <input type = "password" style = "margin-left:20%;" placeholder = "password" name = "password" /> </center> </div> <br> <div style = "max-width:470px;"> <center> <button style = "border:0px; background-color:#4285F4; margin-top:8%; height:35px; width:80%;margin-left:19%;" type = "submit" value = "Login" > <strong>Login</strong> </button> </center> </div> </form> </body> </html> The template will display a login form and post the result to our login view above. You have probably noticed the tag in the template, which is just to prevent Cross-site Request Forgery (CSRF) attack on your site. {% csrf_token %} Once we have the login template, we need the loggedin.html template that will be rendered after form treatment. <html> <body> You are : <strong>{{username}}</strong> </body> </html> Now, we just need our pair of URLs to get started: myapp/urls.py from django.conf.urls import patterns, url from django.views.generic import TemplateView urlpatterns = patterns('myapp.views', url(r'^connection/',TemplateView.as_view(template_name = 'login.html')), url(r'^login/', 'login', name = 'login')) When accessing "/myapp/connection", we will get the following login.html template rendered βˆ’ On the form post, the form is valid. In our case make sure to fill the two fields and you will get βˆ’ In case your username is polo, and you forgot the password. You will get the following message βˆ’ In the above example, when validating the form βˆ’ MyLoginForm.is_valid() We only used Django self-form validation engine, in our case just making sure the fields are required. Now let’s try to make sure the user trying to login is present in our DB as Dreamreal entry. For this, change the myapp/forms.py to βˆ’ #-*- coding: utf-8 -*- from django import forms from myapp.models import Dreamreal class LoginForm(forms.Form): user = forms.CharField(max_length = 100) password = forms.CharField(widget = forms.PasswordInput()) def clean_message(self): username = self.cleaned_data.get("username") dbuser = Dreamreal.objects.filter(name = username) if not dbuser: raise forms.ValidationError("User does not exist in our db!") return username Now, after calling the "is_valid" method, we will get the correct output, only if the user is in our database. If you want to check a field of your form, just add a method starting by "clean_" then your field name to your form class. Raising a forms.ValidationError is important. It is generally useful for a web app to be able to upload files (profile picture, songs, pdf, words.....). Let's discuss how to upload files in this chapter. Before starting to play with an image, make sure you have the Python Image Library (PIL) installed. Now to illustrate uploading an image, let's create a profile form, in our myapp/forms.py βˆ’ #-*- coding: utf-8 -*- from django import forms class ProfileForm(forms.Form): name = forms.CharField(max_length = 100) picture = forms.ImageFields() As you can see, the main difference here is just the forms.ImageField. ImageField will make sure the uploaded file is an image. If not, the form validation will fail. Now let's create a "Profile" model to save our uploaded profile. This is done in myapp/models.py βˆ’ from django.db import models class Profile(models.Model): name = models.CharField(max_length = 50) picture = models.ImageField(upload_to = 'pictures') class Meta: db_table = "profile" As you can see for the model, the ImageField takes a compulsory argument: upload_to. This represents the place on the hard drive where your images will be saved. Note that the parameter will be added to the MEDIA_ROOT option defined in your settings.py file. Now that we have the Form and the Model, let's create the view, in myapp/views.py βˆ’ #-*- coding: utf-8 -*- from myapp.forms import ProfileForm from myapp.models import Profile def SaveProfile(request): saved = False if request.method == "POST": #Get the posted form MyProfileForm = ProfileForm(request.POST, request.FILES) if MyProfileForm.is_valid(): profile = Profile() profile.name = MyProfileForm.cleaned_data["name"] profile.picture = MyProfileForm.cleaned_data["picture"] profile.save() saved = True else: MyProfileForm = Profileform() return render(request, 'saved.html', locals()) The part not to miss is, there is a change when creating a ProfileForm, we added a second parameters: request.FILES. If not passed the form validation will fail, giving a message that says the picture is empty. Now, we just need the saved.html template and the profile.html template, for the form and the redirection page βˆ’ myapp/templates/saved.html βˆ’ <html> <body> {% if saved %} <strong>Your profile was saved.</strong> {% endif %} {% if not saved %} <strong>Your profile was not saved.</strong> {% endif %} </body> </html> myapp/templates/profile.html βˆ’ <html> <body> <form name = "form" enctype = "multipart/form-data" action = "{% url "myapp.views.SaveProfile" %}" method = "POST" >{% csrf_token %} <div style = "max-width:470px;"> <center> <input type = "text" style = "margin-left:20%;" placeholder = "Name" name = "name" /> </center> </div> <br> <div style = "max-width:470px;"> <center> <input type = "file" style = "margin-left:20%;" placeholder = "Picture" name = "picture" /> </center> </div> <br> <div style = "max-width:470px;"> <center> <button style = "border:0px;background-color:#4285F4; margin-top:8%; height:35px; width:80%; margin-left:19%;" type = "submit" value = "Login" > <strong>Login</strong> </button> </center> </div> </form> </body> </html> Next, we need our pair of URLs to get started: myapp/urls.py from django.conf.urls import patterns, url from django.views.generic import TemplateView urlpatterns = patterns( 'myapp.views', url(r'^profile/',TemplateView.as_view( template_name = 'profile.html')), url(r'^saved/', 'SaveProfile', name = 'saved') ) When accessing "/myapp/profile", we will get the following profile.html template rendered βˆ’ And on form post, the saved template will be rendered βˆ’ We have a sample for image, but if you want to upload another type of file, not just image, just replace the ImageField in both Model and Form with FileField. So far, in our examples, we have used the Django dev web server. But this server is just for testing and is not fit for production environment. Once in production, you need a real server like Apache, Nginx, etc. Let's discuss Apache in this chapter. Serving Django applications via Apache is done by using mod_wsgi. So the first thing is to make sure you have Apache and mod_wsgi installed. Remember, when we created our project and we looked at the project structure, it looked like βˆ’ myproject/ manage.py myproject/ __init__.py settings.py urls.py wsgi.py The wsgi.py file is the one taking care of the link between Django and Apache. Let's say we want to share our project (myproject) with Apache. We just need to set Apache to access our folder. Assume we put our myproject folder in the default "/var/www/html". At this stage, accessing the project will be done via 127.0.0.1/myproject. This will result in Apache just listing the folder as shown in the following snapshot. As seen, Apache is not handling Django stuff. For this to be taken care of, we need to configure Apache in httpd.conf. So open the httpd.conf and add the following line βˆ’ WSGIScriptAlias / /var/www/html/myproject/myproject/wsgi.py WSGIPythonPath /var/www/html/myproject/ <Directory /var/www/html/myproject/> <Files wsgi.py> Order deny,allow Allow from all </Files> </Directory> If you can access the login page as 127.0.0.1/myapp/connection, you will get to see the following page βˆ’ Sometimes you might want to store some data on a per-site-visitor basis as per the requirements of your web application. Always keep in mind, that cookies are saved on the client side and depending on your client browser security level, setting cookies can at times work and at times might not. To illustrate cookies handling in Django, let's create a system using the login system we created before. The system will keep you logged in for X minute of time, and beyond that time, you will be out of the app. For this, you will need to set up two cookies, last_connection and username. At first, let's change our login view to store our username and last_connection cookies βˆ’ from django.template import RequestContext def login(request): username = "not logged in" if request.method == "POST": #Get the posted form MyLoginForm = LoginForm(request.POST) if MyLoginForm.is_valid(): username = MyLoginForm.cleaned_data['username'] else: MyLoginForm = LoginForm() response = render_to_response(request, 'loggedin.html', {"username" : username}, context_instance = RequestContext(request)) response.set_cookie('last_connection', datetime.datetime.now()) response.set_cookie('username', datetime.datetime.now()) return response As seen in the view above, setting cookie is done by the set_cookie method called on the response not the request, and also note that all cookies values are returned as string. Let’s now create a formView for the login form, where we won’t display the form if cookie is set and is not older than 10 second βˆ’ def formView(request): if 'username' in request.COOKIES and 'last_connection' in request.COOKIES: username = request.COOKIES['username'] last_connection = request.COOKIES['last_connection'] last_connection_time = datetime.datetime.strptime(last_connection[:-7], "%Y-%m-%d %H:%M:%S") if (datetime.datetime.now() - last_connection_time).seconds < 10: return render(request, 'loggedin.html', {"username" : username}) else: return render(request, 'login.html', {}) else: return render(request, 'login.html', {}) As you can see in the formView above accessing the cookie you set, is done via the COOKIES attribute (dict) of the request. Now let’s change the url.py file to change the URL so it pairs with our new view βˆ’ from django.conf.urls import patterns, url from django.views.generic import TemplateView urlpatterns = patterns('myapp.views', url(r'^connection/','formView', name = 'loginform'), url(r'^login/', 'login', name = 'login')) When accessing /myapp/connection, you will get the following page βˆ’ And you will get redirected to the following screen on submit βˆ’ Now, if you try to access /myapp/connection again in the 10 seconds range, you will get redirected to the second screen directly. And if you access /myapp/connection again out of this range you will get the login form (screen 1). As discussed earlier, we can use client side cookies to store a lot of useful data for the web app. We have seen before that we can use client side cookies to store various data useful for our web app. This leads to lot of security holes depending on the importance of the data you want to save. For security reasons, Django has a session framework for cookies handling. Sessions are used to abstract the receiving and sending of cookies, data is saved on server side (like in database), and the client side cookie just has a session ID for identification. Sessions are also useful to avoid cases where the user browser is set to β€˜not accept’ cookies. In Django, enabling session is done in your project settings.py, by adding some lines to the MIDDLEWARE_CLASSES and the INSTALLED_APPS options. This should be done while creating the project, but it's always good to know, so MIDDLEWARE_CLASSES should have βˆ’ 'django.contrib.sessions.middleware.SessionMiddleware' And INSTALLED_APPS should have βˆ’ 'django.contrib.sessions' By default, Django saves session information in database (django_session table or collection), but you can configure the engine to store information using other ways like: in file or in cache. When session is enabled, every request (first argument of any view in Django) has a session (dict) attribute. Let's create a simple sample to see how to create and save sessions. We have built a simple login system before (see Django form processing chapter and Django Cookies Handling chapter). Let us save the username in a cookie so, if not signed out, when accessing our login page you won’t see the login form. Basically, let's make our login system we used in Django Cookies handling more secure, by saving cookies server side. For this, first lets change our login view to save our username cookie server side βˆ’ def login(request): username = 'not logged in' if request.method == 'POST': MyLoginForm = LoginForm(request.POST) if MyLoginForm.is_valid(): username = MyLoginForm.cleaned_data['username'] request.session['username'] = username else: MyLoginForm = LoginForm() return render(request, 'loggedin.html', {"username" : username} Then let us create formView view for the login form, where we won’t display the form if cookie is set βˆ’ def formView(request): if request.session.has_key('username'): username = request.session['username'] return render(request, 'loggedin.html', {"username" : username}) else: return render(request, 'login.html', {}) Now let us change the url.py file to change the url so it pairs with our new view βˆ’ from django.conf.urls import patterns, url from django.views.generic import TemplateView urlpatterns = patterns('myapp.views', url(r'^connection/','formView', name = 'loginform'), url(r'^login/', 'login', name = 'login')) When accessing /myapp/connection, you will get to see the following page βˆ’ And you will get redirected to the following page βˆ’ Now if you try to access /myapp/connection again, you will get redirected to the second screen directly. Let's create a simple logout view that erases our cookie. def logout(request): try: del request.session['username'] except: pass return HttpResponse("<strong>You are logged out.</strong>") And pair it with a logout URL in myapp/url.py url(r'^logout/', 'logout', name = 'logout'), Now, if you access /myapp/logout, you will get the following page βˆ’ If you access /myapp/connection again, you will get the login form (screen 1). We have seen how to store and access a session, but it's good to know that the session attribute of the request have some other useful actions like βˆ’ set_expiry (value) βˆ’ Sets the expiration time for the session. set_expiry (value) βˆ’ Sets the expiration time for the session. get_expiry_age() βˆ’ Returns the number of seconds until this session expires. get_expiry_age() βˆ’ Returns the number of seconds until this session expires. get_expiry_date() βˆ’ Returns the date this session will expire. get_expiry_date() βˆ’ Returns the date this session will expire. clear_expired() βˆ’ Removes expired sessions from the session store. clear_expired() βˆ’ Removes expired sessions from the session store. get_expire_at_browser_close() βˆ’ Returns either True or False, depending on whether the user’s session cookies have expired when the user’s web browser is closed. get_expire_at_browser_close() βˆ’ Returns either True or False, depending on whether the user’s session cookies have expired when the user’s web browser is closed. To cache something is to save the result of an expensive calculation, so that you don’t perform it the next time you need it. Following is a pseudo code that explains how caching works βˆ’ given a URL, try finding that page in the cache if the page is in the cache: return the cached page else: generate the page save the generated page in the cache (for next time) return the generated page Django comes with its own caching system that lets you save your dynamic pages, to avoid calculating them again when needed. The good point in Django Cache framework is that you can cache βˆ’ The output of a specific view. A part of a template. Your entire site. To use cache in Django, first thing to do is to set up where the cache will stay. The cache framework offers different possibilities - cache can be saved in database, on file system or directly in memory. Setting is done in the settings.py file of your project. Just add the following in the project settings.py file βˆ’ CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'my_table_name', } } For this to work and to complete the setting, we need to create the cache table 'my_table_name'. For this, you need to do the following βˆ’ python manage.py createcachetable Just add the following in the project settings.py file βˆ’ CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': '/var/tmp/django_cache', } } This is the most efficient way of caching, to use it you can use one of the following options depending on the Python binding library you choose for the memory cache βˆ’ CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } Or CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': 'unix:/tmp/memcached.sock', } } The simplest way of using cache in Django is to cache the entire site. This is done by editing the MIDDLEWARE_CLASSES option in the project settings.py. The following need to be added to the option βˆ’ MIDDLEWARE_CLASSES += ( 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', ) Note that the order is important here, Update should come before Fetch middleware. Then in the same file, you need to set βˆ’ CACHE_MIDDLEWARE_ALIAS – The cache alias to use for storage. CACHE_MIDDLEWARE_SECONDS – The number of seconds each page should be cached. If you don’t want to cache the entire site you can cache a specific view. This is done by using the cache_page decorator that comes with Django. Let us say we want to cache the result of the viewArticles view βˆ’ from django.views.decorators.cache import cache_page @cache_page(60 * 15) def viewArticles(request, year, month): text = "Displaying articles of : %s/%s"%(year, month) return HttpResponse(text) As you can see cache_page takes the number of seconds you want the view result to be cached as parameter. In our example above, the result will be cached for 15 minutes. Note βˆ’ As we have seen before the above view was map to βˆ’ urlpatterns = patterns('myapp.views', url(r'^articles/(?P<month>\d{2})/(?P<year>\d{4})/', 'viewArticles', name = 'articles'),) Since the URL is taking parameters, each different call will be cached separately. For example, request to /myapp/articles/02/2007 will be cached separately to /myapp/articles/03/2008. Caching a view can also directly be done in the url.py file. Then the following has the same result as the above. Just edit your myapp/url.py file and change the related mapped URL (above) to be βˆ’ urlpatterns = patterns('myapp.views', url(r'^articles/(?P<month>\d{2})/(?P<year>\d{4})/', cache_page(60 * 15)('viewArticles'), name = 'articles'),) And, of course, it's no longer needed in myapp/views.py. You can also cache parts of a template, this is done by using the cache tag. Let's take our hello.html template βˆ’ {% extends "main_template.html" %} {% block title %}My Hello Page{% endblock %} {% block content %} Hello World!!!<p>Today is {{today}}</p> We are {% if today.day == 1 %} the first day of month. {% elif today.day == 30 %} the last day of month. {% else %} I don't know. {%endif%} <p> {% for day in days_of_week %} {{day}} </p> {% endfor %} {% endblock %} And to cache the content block, our template will become βˆ’ {% load cache %} {% extends "main_template.html" %} {% block title %}My Hello Page{% endblock %} {% cache 500 content %} {% block content %} Hello World!!!<p>Today is {{today}}</p> We are {% if today.day == 1 %} the first day of month. {% elif today.day == 30 %} the last day of month. {% else %} I don't know. {%endif%} <p> {% for day in days_of_week %} {{day}} </p> {% endfor %} {% endblock %} {% endcache %} As you can see above, the cache tag will take 2 parameters βˆ’ the time you want the block to be cached (in seconds) and the name to be given to the cache fragment. Before starting, note that the Django Comments framework is deprecated, since the 1.5 version. Now you can use external feature for doing so, but if you still want to use it, it's still included in version 1.6 and 1.7. Starting version 1.8 it's absent but you can still get the code on a different GitHub account. The comments framework makes it easy to attach comments to any model in your app. To start using the Django comments framework βˆ’ Edit the project settings.py file and add 'django.contrib.sites', and 'django.contrib.comments', to INSTALLED_APPS option βˆ’ INSTALLED_APPS += ('django.contrib.sites', 'django.contrib.comments',) Get the site id βˆ’ >>> from django.contrib.sites.models import Site >>> Site().save() >>> Site.objects.all()[0].id u'56194498e13823167dd43c64' Set the id you get in the settings.py file βˆ’ SITE_ID = u'56194498e13823167dd43c64' Sync db, to create all the comments table or collection βˆ’ python manage.py syncdb Add the comment app’s URLs to your project’s urls.py βˆ’ from django.conf.urls import include url(r'^comments/', include('django.contrib.comments.urls')), Now that we have the framework installed, let's change our hello templates to tracks comments on our Dreamreal model. We will list, save comments for a specific Dreamreal entry whose name will be passed as parameter to the /myapp/hello URL. class Dreamreal(models.Model): website = models.CharField(max_length = 50) mail = models.CharField(max_length = 50) name = models.CharField(max_length = 50) phonenumber = models.IntegerField() class Meta: db_table = "dreamreal" def hello(request, Name): today = datetime.datetime.now().date() daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] dreamreal = Dreamreal.objects.get(name = Name) return render(request, 'hello.html', locals()) {% extends "main_template.html" %} {% load comments %} {% block title %}My Hello Page{% endblock %} {% block content %} <p> Our Dreamreal Entry: <p><strong>Name :</strong> {{dreamreal.name}}</p> <p><strong>Website :</strong> {{dreamreal.website}}</p> <p><strong>Phone :</strong> {{dreamreal.phonenumber}}</p> <p><strong>Number of comments :<strong> {% get_comment_count for dreamreal as comment_count %} {{ comment_count }}</p> <p>List of comments :</p> {% render_comment_list for dreamreal %} </p> {% render_comment_form for dreamreal %} {% endblock %} Finally the mapping URL to our hello view βˆ’ url(r'^hello/(?P<Name>\w+)/', 'hello', name = 'hello'), Now, In our template (hello.html), load the comments framework with βˆ’ {% load comments %} In our template (hello.html), load the comments framework with βˆ’ {% load comments %} We get the number of comments for the Dreamreal object pass by the view βˆ’ {% get_comment_count for dreamreal as comment_count %} We get the number of comments for the Dreamreal object pass by the view βˆ’ {% get_comment_count for dreamreal as comment_count %} We get the list of comments for the objects βˆ’ {% render_comment_list for dreamreal %} We get the list of comments for the objects βˆ’ {% render_comment_list for dreamreal %} We display the default comments form βˆ’ {% render_comment_form for dreamreal %} We display the default comments form βˆ’ {% render_comment_form for dreamreal %} When accessing /myapp/hello/steve you will get the comments info for the Dreamreal entry whose name is Steve. Accessing that URL will get you βˆ’ On posting a comment, you will get redirected to the following page βˆ’ If you go to /myapp/hello/steve again, you will get to see the following page βˆ’ As you can see, the number of comments is 1 now and you have the comment under the list of comments line. Django comes with a syndication feed generating framework. With it you can create RSS or Atom feeds just by subclassing django.contrib.syndication.views.Feed class. Let's create a feed for the latest comments done on the app (Also see Django - Comments Framework chapter). For this, let's create a myapp/feeds.py and define our feed (You can put your feeds classes anywhere you want in your code structure). from django.contrib.syndication.views import Feed from django.contrib.comments import Comment from django.core.urlresolvers import reverse class DreamrealCommentsFeed(Feed): title = "Dreamreal's comments" link = "/drcomments/" description = "Updates on new comments on Dreamreal entry." def items(self): return Comment.objects.all().order_by("-submit_date")[:5] def item_title(self, item): return item.user_name def item_description(self, item): return item.comment def item_link(self, item): return reverse('comment', kwargs = {'object_pk':item.pk}) In our feed class, title, link, and description attributes correspond to the standard RSS <title>, <link> and <description> elements. In our feed class, title, link, and description attributes correspond to the standard RSS <title>, <link> and <description> elements. The items method, return the elements that should go in the feed as item element. In our case the last five comments. The items method, return the elements that should go in the feed as item element. In our case the last five comments. The item_title method, will get what will go as title for our feed item. In our case the title, will be the user name. The item_title method, will get what will go as title for our feed item. In our case the title, will be the user name. The item_description method, will get what will go as description for our feed item. In our case the comment itself. The item_description method, will get what will go as description for our feed item. In our case the comment itself. The item_link method will build the link to the full item. In our case it will get you to the comment. The item_link method will build the link to the full item. In our case it will get you to the comment. Now that we have our feed, let's add a comment view in views.py to display our comment βˆ’ from django.contrib.comments import Comment def comment(request, object_pk): mycomment = Comment.objects.get(object_pk = object_pk) text = '<strong>User :</strong> %s <p>'%mycomment.user_name</p> text += '<strong>Comment :</strong> %s <p>'%mycomment.comment</p> return HttpResponse(text) We also need some URLs in our myapp urls.py for mapping βˆ’ from myapp.feeds import DreamrealCommentsFeed from django.conf.urls import patterns, url urlpatterns += patterns('', url(r'^latest/comments/', DreamrealCommentsFeed()), url(r'^comment/(?P\w+)/', 'comment', name = 'comment'), ) When accessing /myapp/latest/comments/ you will get our feed βˆ’ Then clicking on one of the usernames will get you to: /myapp/comment/comment_id as defined in our comment view before and you will get βˆ’ Thus, defining a RSS feed is just a matter of sub-classing the Feed class and making sure the URLs (one for accessing the feed and one for accessing the feed elements) are defined. Just as comment, this can be attached to any model in your app. Ajax essentially is a combination of technologies that are integrated together to reduce the number of page loads. We generally use Ajax to ease end-user experience. Using Ajax in Django can be done by directly using an Ajax library like JQuery or others. Let's say you want to use JQuery, then you need to download and serve the library on your server through Apache or others. Then use it in your template, just like you might do while developing any Ajax-based application. Another way of using Ajax in Django is to use the Django Ajax framework. The most commonly used is django-dajax which is a powerful tool to easily and super-quickly develop asynchronous presentation logic in web applications, using Python and almost no JavaScript source code. It supports four of the most popular Ajax frameworks: Prototype, jQuery, Dojo and MooTools. First thing to do is to install django-dajax. This can be done using easy_install or pip βˆ’ $ pip install django_dajax $ easy_install django_dajax This will automatically install django-dajaxice, required by django-dajax. We then need to configure both dajax and dajaxice. Add dajax and dajaxice in your project settings.py in INSTALLED_APPS option βˆ’ INSTALLED_APPS += ( 'dajaxice', 'dajax' ) Make sure in the same settings.py file, you have the following βˆ’ TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', 'django.template.loaders.eggs.Loader', ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', 'django.core.context_processors.static', 'django.core.context_processors.request', 'django.contrib.messages.context_processors.messages' ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'dajaxice.finders.DajaxiceFinder', ) DAJAXICE_MEDIA_PREFIX = 'dajaxice' Now go to the myapp/url.py file and make sure you have the following to set dajax URLs and to load dajax statics js files βˆ’ from dajaxice.core import dajaxice_autodiscover, dajaxice_config from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf import settings Then dajax urls: urlpatterns += patterns('', url(r'^%s/' % settings.DAJAXICE_MEDIA_PREFIX, include('dajaxice.urls')),) urlpatterns += staticfiles_urlpatterns() Let us create a simple form based on our Dreamreal model to store it, using Ajax (means no refresh). At first, we need our Dreamreal form in myapp/form.py. class DreamrealForm(forms.Form): website = forms.CharField(max_length = 100) name = forms.CharField(max_length = 100) phonenumber = forms.CharField(max_length = 50) email = forms.CharField(max_length = 100) Then we need an ajax.py file in our application: myapp/ajax.py. That's where is our logic, that's where we put the function that will be saving our form then return the popup βˆ’ from dajaxice.utils import deserialize_form from myapp.form import DreamrealForm from dajax.core import Dajax from myapp.models import Dreamreal @dajaxice_register def send_form(request, form): dajax = Dajax() form = DreamrealForm(deserialize_form(form)) if form.is_valid(): dajax.remove_css_class('#my_form input', 'error') dr = Dreamreal() dr.website = form.cleaned_data.get('website') dr.name = form.cleaned_data.get('name') dr.phonenumber = form.cleaned_data.get('phonenumber') dr.save() dajax.alert("Dreamreal Entry %s was successfully saved." % form.cleaned_data.get('name')) else: dajax.remove_css_class('#my_form input', 'error') for error in form.errors: dajax.add_css_class('#id_%s' % error, 'error') return dajax.json() Now let's create the dreamreal.html template, which has our form βˆ’ <html> <head></head> <body> <form action = "" method = "post" id = "my_form" accept-charset = "utf-8"> {{ form.as_p }} <p><input type = "button" value = "Send" onclick = "send_form();"></p> </form> </body> </html> Add the view that goes with the template in myapp/views.py βˆ’ def dreamreal(request): form = DreamrealForm() return render(request, 'dreamreal.html', locals()) Add the corresponding URL in myapp/urls.py βˆ’ url(r'^dreamreal/', 'dreamreal', name = 'dreamreal'), Now let's add the necessary in our template to make the Ajax work βˆ’ At the top of the file add βˆ’ {% load static %} {% load dajaxice_templatetags %} And in the <head> section of our dreamreal.html template add βˆ’ We are using the JQuery library for this example, so add βˆ’ <script src = "{% static '/static/jquery-1.11.3.min.js' %}" type = "text/javascript" charset = "utf-8"></script> <script src = "{% static '/static/dajax/jquery.dajax.core.js' %}"></script> The Ajax function that will be called on click βˆ’ <script> function send_form(){ Dajaxice.myapp.send_form(Dajax.process,{'form':$('#my_form').serialize(true)}); } </script> Note that you need the β€œjquery-1.11.3.min.js” in your static files directory, and also the jquery.dajax.core.js. To make sure all dajax static files are served under your static directory, run βˆ’ $python manage.py collectstatic Note βˆ’ Sometimes the jquery.dajax.core.js can be missing, if that happens, just download the source and take that file and put it under your static folder. You will get to see the following screen, upon accessing /myapp/dreamreal/ βˆ’ On submit, you will get the following screen βˆ’ 39 Lectures 3.5 hours John Elder 36 Lectures 2.5 hours John Elder 28 Lectures 2 hours John Elder 20 Lectures 1 hours John Elder 35 Lectures 3 hours John Elder 79 Lectures 10 hours Rathan Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 2228, "s": 2045, "text": "Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. Django makes it easier to build better web apps quickly and with less code." }, { "code": null, "e": 2338, "s": 2228, "text": "Note βˆ’ Django is a registered trademark of the Django Software Foundation, and is licensed under BSD License." }, { "code": null, "e": 2455, "s": 2338, "text": "2003 βˆ’ Started by Adrian Holovaty and Simon Willison as an internal project at the Lawrence Journal-World newspaper." }, { "code": null, "e": 2572, "s": 2455, "text": "2003 βˆ’ Started by Adrian Holovaty and Simon Willison as an internal project at the Lawrence Journal-World newspaper." }, { "code": null, "e": 2662, "s": 2572, "text": "2005 βˆ’ Released July 2005 and named it Django, after the jazz guitarist Django Reinhardt." }, { "code": null, "e": 2752, "s": 2662, "text": "2005 βˆ’ Released July 2005 and named it Django, after the jazz guitarist Django Reinhardt." }, { "code": null, "e": 2811, "s": 2752, "text": "2005 βˆ’ Mature enough to handle several high-traffic sites." }, { "code": null, "e": 2870, "s": 2811, "text": "2005 βˆ’ Mature enough to handle several high-traffic sites." }, { "code": null, "e": 2953, "s": 2870, "text": "Current βˆ’ Django is now an open source project with contributors across the world." }, { "code": null, "e": 3036, "s": 2953, "text": "Current βˆ’ Django is now an open source project with contributors across the world." }, { "code": null, "e": 3090, "s": 3036, "text": "Django comes with the following design philosophies βˆ’" }, { "code": null, "e": 3181, "s": 3090, "text": "Loosely Coupled βˆ’ Django aims to make each element of its stack independent of the others." }, { "code": null, "e": 3272, "s": 3181, "text": "Loosely Coupled βˆ’ Django aims to make each element of its stack independent of the others." }, { "code": null, "e": 3328, "s": 3272, "text": "Less Coding βˆ’ Less code so in turn a quick development." }, { "code": null, "e": 3384, "s": 3328, "text": "Less Coding βˆ’ Less code so in turn a quick development." }, { "code": null, "e": 3512, "s": 3384, "text": "Don't Repeat Yourself (DRY) βˆ’ Everything should be developed only in exactly one place instead of repeating it again and again." }, { "code": null, "e": 3640, "s": 3512, "text": "Don't Repeat Yourself (DRY) βˆ’ Everything should be developed only in exactly one place instead of repeating it again and again." }, { "code": null, "e": 3737, "s": 3640, "text": "Fast Development βˆ’ Django's philosophy is to do all it can to facilitate hyper-fast development." }, { "code": null, "e": 3834, "s": 3737, "text": "Fast Development βˆ’ Django's philosophy is to do all it can to facilitate hyper-fast development." }, { "code": null, "e": 3974, "s": 3834, "text": "Clean Design βˆ’ Django strictly maintains a clean design throughout its own code and makes it easy to follow best web-development practices." }, { "code": null, "e": 4114, "s": 3974, "text": "Clean Design βˆ’ Django strictly maintains a clean design throughout its own code and makes it easy to follow best web-development practices." }, { "code": null, "e": 4185, "s": 4114, "text": "Here are few advantages of using Django which can be listed out here βˆ’" }, { "code": null, "e": 4528, "s": 4185, "text": "Object-Relational Mapping (ORM) Support βˆ’ Django provides a bridge between the data model and the database engine, and supports a large set of database systems including MySQL, Oracle, Postgres, etc. Django also supports NoSQL database through Django-nonrel fork. For now, the only NoSQL databases supported are MongoDB and google app engine." }, { "code": null, "e": 4871, "s": 4528, "text": "Object-Relational Mapping (ORM) Support βˆ’ Django provides a bridge between the data model and the database engine, and supports a large set of database systems including MySQL, Oracle, Postgres, etc. Django also supports NoSQL database through Django-nonrel fork. For now, the only NoSQL databases supported are MongoDB and google app engine." }, { "code": null, "e": 5055, "s": 4871, "text": "Multilingual Support βˆ’ Django supports multilingual websites through its built-in internationalization system. So you can develop your website, which would support multiple languages." }, { "code": null, "e": 5239, "s": 5055, "text": "Multilingual Support βˆ’ Django supports multilingual websites through its built-in internationalization system. So you can develop your website, which would support multiple languages." }, { "code": null, "e": 5340, "s": 5239, "text": "Framework Support βˆ’ Django has built-in support for Ajax, RSS, Caching and various other frameworks." }, { "code": null, "e": 5441, "s": 5340, "text": "Framework Support βˆ’ Django has built-in support for Ajax, RSS, Caching and various other frameworks." }, { "code": null, "e": 5544, "s": 5441, "text": "Administration GUI βˆ’ Django provides a nice ready-to-use user interface for administrative activities." }, { "code": null, "e": 5647, "s": 5544, "text": "Administration GUI βˆ’ Django provides a nice ready-to-use user interface for administrative activities." }, { "code": null, "e": 5778, "s": 5647, "text": "Development Environment βˆ’ Django comes with a lightweight web server to facilitate end-to-end application development and testing." }, { "code": null, "e": 5909, "s": 5778, "text": "Development Environment βˆ’ Django comes with a lightweight web server to facilitate end-to-end application development and testing." }, { "code": null, "e": 6183, "s": 5909, "text": "As you already know, Django is a Python web framework. And like most modern framework, Django supports the MVC pattern. First let's see what is the Model-View-Controller (MVC) pattern, and then we will look at Django’s specificity for the Model-View-Template (MVT) pattern." }, { "code": null, "e": 6429, "s": 6183, "text": "When talking about applications that provides UI (web or desktop), we usually talk about MVC architecture. And as the name suggests, MVC pattern is based on three components: Model, View, and Controller. Check our MVC tutorial here to know more." }, { "code": null, "e": 6776, "s": 6429, "text": "The Model-View-Template (MVT) is slightly different from MVC. In fact the main difference between the two patterns is that Django itself takes care of the Controller part (Software Code that controls the interactions between the Model and View), leaving us with the template. The template is a HTML file mixed with Django Template Language (DTL)." }, { "code": null, "e": 6908, "s": 6776, "text": "The following diagram illustrates how each of the components of the MVT pattern interacts with each other to serve a user request βˆ’" }, { "code": null, "e": 7046, "s": 6908, "text": "The developer provides the Model, the view and the template then just maps it to a URL and Django does the magic to serve it to the user." }, { "code": null, "e": 7265, "s": 7046, "text": "Django development environment consists of installing and setting up Python, Django, and a Database System. Since Django deals with web application, it's worth mentioning that you would need a web server setup as well." }, { "code": null, "e": 7476, "s": 7265, "text": "Django is written in 100% pure Python code, so you'll need to install Python on your system. Latest Django version requires Python 2.6.5 or higher for the 2.6.x branch or higher than 2.7.3 for the 2.7.x branch." }, { "code": null, "e": 7705, "s": 7476, "text": "If you're on one of the latest Linux or Mac OS X distribution, you probably already have Python installed. You can verify it by typing python command at a command prompt. If you see something like this, then Python is installed." }, { "code": null, "e": 7811, "s": 7705, "text": "$ python\nPython 2.7.5 (default, Jun 17 2014, 18:11:42)\n[GCC 4.8.2 20140120 (Red Hat 4.8.2-16)] on linux2\n" }, { "code": null, "e": 7926, "s": 7811, "text": "Otherwise, you can download and install the latest version of Python from the link http://www.python.org/download." }, { "code": null, "e": 8167, "s": 7926, "text": "Installing Django is very easy, but the steps required for its installation depends on your operating system. Since Python is a platform-independent language, Django has one package that works everywhere regardless of your operating system." }, { "code": null, "e": 8266, "s": 8167, "text": "You can download the latest version of Django from the link http://www.djangoproject.com/download." }, { "code": null, "e": 8349, "s": 8266, "text": "You have two ways of installing Django if you are running Linux or Mac OS system βˆ’" }, { "code": null, "e": 8434, "s": 8349, "text": "You can use the package manager of your OS, or use easy_install or pip if installed." }, { "code": null, "e": 8519, "s": 8434, "text": "You can use the package manager of your OS, or use easy_install or pip if installed." }, { "code": null, "e": 8589, "s": 8519, "text": "Install it manually using the official archive you downloaded before." }, { "code": null, "e": 8659, "s": 8589, "text": "Install it manually using the official archive you downloaded before." }, { "code": null, "e": 8853, "s": 8659, "text": "We will cover the second option as the first one depends on your OS distribution. If you have decided to follow the first option, just be careful about the version of Django you are installing." }, { "code": null, "e": 8953, "s": 8853, "text": "Let's say you got your archive from the link above, it should be something like Django-x.xx.tar.gz:" }, { "code": null, "e": 8974, "s": 8953, "text": "Extract and install." }, { "code": null, "e": 9053, "s": 8974, "text": "$ tar xzvf Django-x.xx.tar.gz\n$ cd Django-x.xx\n$ sudo python setup.py install\n" }, { "code": null, "e": 9110, "s": 9053, "text": "You can test your installation by running this command βˆ’" }, { "code": null, "e": 9139, "s": 9110, "text": "$ django-admin.py --version\n" }, { "code": null, "e": 9227, "s": 9139, "text": "If you see the current version of Django printed on the screen, then everything is set." }, { "code": null, "e": 9307, "s": 9227, "text": "Note βˆ’ For some version of Django it will be django-admin the \".py\" is removed." }, { "code": null, "e": 9385, "s": 9307, "text": "We assume you have your Django archive and python installed on your computer." }, { "code": null, "e": 9411, "s": 9385, "text": "First, PATH verification." }, { "code": null, "e": 9637, "s": 9411, "text": "On some version of windows (windows 7) you might need to make sure the Path system variable has the path the following C:\\Python27\\;C:\\Python27\\Lib\\site-packages\\django\\bin\\ in it, of course depending on your Python version." }, { "code": null, "e": 9671, "s": 9637, "text": "Then, extract and install Django." }, { "code": null, "e": 9694, "s": 9671, "text": "c:\\>cd c:\\Django-x.xx\n" }, { "code": null, "e": 9823, "s": 9694, "text": "Next, install Django by running the following command for which you will need administrative privileges in windows shell \"cmd\" βˆ’" }, { "code": null, "e": 9863, "s": 9823, "text": "c:\\Django-x.xx>python setup.py install\n" }, { "code": null, "e": 9945, "s": 9863, "text": "To test your installation, open a command prompt and type the following command βˆ’" }, { "code": null, "e": 9976, "s": 9945, "text": "c:\\>django-admin.py --version\n" }, { "code": null, "e": 10060, "s": 9976, "text": "If you see the current version of Django printed on screen, then everything is set." }, { "code": null, "e": 10063, "s": 10060, "text": "OR" }, { "code": null, "e": 10108, "s": 10063, "text": "Launch a \"cmd\" prompt and type python then βˆ’" }, { "code": null, "e": 10170, "s": 10108, "text": "c:\\> python\n>>> import django\n>>> print django.get_version()\n" }, { "code": null, "e": 10271, "s": 10170, "text": "Django supports several major database engines and you can set up any of them based on your comfort." }, { "code": null, "e": 10301, "s": 10271, "text": "MySQL (http://www.mysql.com/)" }, { "code": null, "e": 10341, "s": 10301, "text": "PostgreSQL (http://www.postgresql.org/)" }, { "code": null, "e": 10375, "s": 10341, "text": "SQLite 3 (http://www.sqlite.org/)" }, { "code": null, "e": 10407, "s": 10375, "text": "Oracle (http://www.oracle.com/)" }, { "code": null, "e": 10463, "s": 10407, "text": "MongoDb (https://django-mongodb-engine.readthedocs.org)" }, { "code": null, "e": 10549, "s": 10463, "text": "GoogleAppEngine Datastore (https://cloud.google.com/appengine/articles/django-nonrel)" }, { "code": null, "e": 10648, "s": 10549, "text": "You can refer to respective documentation to installing and configuring a database of your choice." }, { "code": null, "e": 10691, "s": 10648, "text": "Note βˆ’ Number 5 and 6 are NoSQL databases." }, { "code": null, "e": 10890, "s": 10691, "text": "Django comes with a lightweight web server for developing and testing applications. This server is pre-configured to work with Django, and more importantly, it restarts whenever you modify the code." }, { "code": null, "e": 11068, "s": 10890, "text": "However, Django does support Apache and other popular web servers such as Lighttpd. We will discuss both the approaches in coming chapters while working with different examples." }, { "code": null, "e": 11538, "s": 11068, "text": "Now that we have installed Django, let's start using it. In Django, every web app you want to create is called a project; and a project is a sum of applications. An application is a set of code files relying on the MVT pattern. As example let's say we want to build a website, the website is our project and, the forum, news, contact engine are applications. This structure makes it easier to move an application between projects since every application is independent." }, { "code": null, "e": 11695, "s": 11538, "text": "Whether you are on Windows or Linux, just get a terminal or a cmd prompt and navigate to the place you want your project to be created, then use this code βˆ’" }, { "code": null, "e": 11734, "s": 11695, "text": "$ django-admin startproject myproject\n" }, { "code": null, "e": 11803, "s": 11734, "text": "This will create a \"myproject\" folder with the following structure βˆ’" }, { "code": null, "e": 11906, "s": 11803, "text": "myproject/\n manage.py\n myproject/\n __init__.py\n settings.py\n urls.py\n wsgi.py\n" }, { "code": null, "e": 11997, "s": 11906, "text": "The β€œmyproject” folder is just your project container, it actually contains two elements βˆ’" }, { "code": null, "e": 12235, "s": 11997, "text": "manage.py βˆ’ This file is kind of your project local django-admin for interacting with your project via command line (start the development server, sync db...). To get a full list of command accessible via manage.py you can use the code βˆ’" }, { "code": null, "e": 12473, "s": 12235, "text": "manage.py βˆ’ This file is kind of your project local django-admin for interacting with your project via command line (start the development server, sync db...). To get a full list of command accessible via manage.py you can use the code βˆ’" }, { "code": null, "e": 12498, "s": 12473, "text": "$ python manage.py help\n" }, { "code": null, "e": 12882, "s": 12498, "text": "The β€œmyproject” subfolder βˆ’ This folder is the actual python package of your project. It contains four files βˆ’\n\n__init__.py βˆ’ Just for python, treat this folder as package.\nsettings.py βˆ’ As the name indicates, your project settings.\nurls.py βˆ’ All links of your project and the function to call. A kind of ToC of your project.\nwsgi.py βˆ’ If you need to deploy your project over WSGI.\n\n" }, { "code": null, "e": 12993, "s": 12882, "text": "The β€œmyproject” subfolder βˆ’ This folder is the actual python package of your project. It contains four files βˆ’" }, { "code": null, "e": 13054, "s": 12993, "text": "__init__.py βˆ’ Just for python, treat this folder as package." }, { "code": null, "e": 13115, "s": 13054, "text": "__init__.py βˆ’ Just for python, treat this folder as package." }, { "code": null, "e": 13175, "s": 13115, "text": "settings.py βˆ’ As the name indicates, your project settings." }, { "code": null, "e": 13235, "s": 13175, "text": "settings.py βˆ’ As the name indicates, your project settings." }, { "code": null, "e": 13328, "s": 13235, "text": "urls.py βˆ’ All links of your project and the function to call. A kind of ToC of your project." }, { "code": null, "e": 13421, "s": 13328, "text": "urls.py βˆ’ All links of your project and the function to call. A kind of ToC of your project." }, { "code": null, "e": 13477, "s": 13421, "text": "wsgi.py βˆ’ If you need to deploy your project over WSGI." }, { "code": null, "e": 13533, "s": 13477, "text": "wsgi.py βˆ’ If you need to deploy your project over WSGI." }, { "code": null, "e": 13657, "s": 13533, "text": "Your project is set up in the subfolder myproject/settings.py. Following are some important options you might need to set βˆ’" }, { "code": null, "e": 13671, "s": 13657, "text": "DEBUG = True\n" }, { "code": null, "e": 13982, "s": 13671, "text": "This option lets you set if your project is in debug mode or not. Debug mode lets you get more information about your project's error. Never set it to β€˜True’ for a live project. However, this has to be set to β€˜True’ if you want the Django light server to serve static files. Do it only in the development mode." }, { "code": null, "e": 14171, "s": 13982, "text": "DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': 'database.sql',\n 'USER': '',\n 'PASSWORD': '',\n 'HOST': '',\n 'PORT': '',\n }\n}" }, { "code": null, "e": 14299, "s": 14171, "text": "Database is set in the β€˜Database’ dictionary. The example above is for SQLite engine. As stated earlier, Django also supports βˆ’" }, { "code": null, "e": 14332, "s": 14299, "text": "MySQL (django.db.backends.mysql)" }, { "code": null, "e": 14384, "s": 14332, "text": "PostGreSQL (django.db.backends.postgresql_psycopg2)" }, { "code": null, "e": 14432, "s": 14384, "text": "Oracle (django.db.backends.oracle) and NoSQL DB" }, { "code": null, "e": 14464, "s": 14432, "text": "MongoDB (django_mongodb_engine)" }, { "code": null, "e": 14547, "s": 14464, "text": "Before setting any new engine, make sure you have the correct db driver installed." }, { "code": null, "e": 14623, "s": 14547, "text": "You can also set others options like: TIME_ZONE, LANGUAGE_CODE, TEMPLATE..." }, { "code": null, "e": 14696, "s": 14623, "text": "Now that your project is created and configured make sure it's working βˆ’" }, { "code": null, "e": 14726, "s": 14696, "text": "$ python manage.py runserver\n" }, { "code": null, "e": 14796, "s": 14726, "text": "You will get something like the following on running the above code βˆ’" }, { "code": null, "e": 15009, "s": 14796, "text": "Validating models...\n\n0 errors found\nSeptember 03, 2015 - 11:41:50\nDjango version 1.6.11, using settings 'myproject.settings'\nStarting development server at http://127.0.0.1:8000/\nQuit the server with CONTROL-C.\n" }, { "code": null, "e": 15249, "s": 15009, "text": "A project is a sum of many applications. Every application has an objective and can be reused into another project, like the contact form on a website can be an application, and can be reused for others. See it as a module of your project." }, { "code": null, "e": 15356, "s": 15249, "text": "We assume you are in your project folder. In our main β€œmyproject” folder, the same folder then manage.py βˆ’" }, { "code": null, "e": 15391, "s": 15356, "text": "$ python manage.py startapp myapp\n" }, { "code": null, "e": 15508, "s": 15391, "text": "You just created myapp application and like project, Django create a β€œmyapp” folder with the application structure βˆ’" }, { "code": null, "e": 15580, "s": 15508, "text": "myapp/\n __init__.py\n admin.py\n models.py\n tests.py\n views.py\n" }, { "code": null, "e": 15653, "s": 15580, "text": "__init__.py βˆ’ Just to make sure python handles this folder as a package." }, { "code": null, "e": 15726, "s": 15653, "text": "__init__.py βˆ’ Just to make sure python handles this folder as a package." }, { "code": null, "e": 15805, "s": 15726, "text": "admin.py βˆ’ This file helps you make the app modifiable in the admin interface." }, { "code": null, "e": 15884, "s": 15805, "text": "admin.py βˆ’ This file helps you make the app modifiable in the admin interface." }, { "code": null, "e": 15949, "s": 15884, "text": "models.py βˆ’ This is where all the application models are stored." }, { "code": null, "e": 16014, "s": 15949, "text": "models.py βˆ’ This is where all the application models are stored." }, { "code": null, "e": 16060, "s": 16014, "text": "tests.py βˆ’ This is where your unit tests are." }, { "code": null, "e": 16106, "s": 16060, "text": "tests.py βˆ’ This is where your unit tests are." }, { "code": null, "e": 16159, "s": 16106, "text": "views.py βˆ’ This is where your application views are." }, { "code": null, "e": 16212, "s": 16159, "text": "views.py βˆ’ This is where your application views are." }, { "code": null, "e": 16423, "s": 16212, "text": "At this stage we have our \"myapp\" application, now we need to register it with our Django project \"myproject\". To do so, update INSTALLED_APPS tuple in the settings.py file of your project (add your app name) βˆ’" }, { "code": null, "e": 16636, "s": 16423, "text": "INSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'myapp',\n)" }, { "code": null, "e": 16850, "s": 16636, "text": "Django provides a ready-to-use user interface for administrative activities. We all know how an admin interface is important for a web project. Django automatically generates admin UI based on your project models." }, { "code": null, "e": 17063, "s": 16850, "text": "The Admin interface depends on the django.countrib module. To have it working you need to make sure some modules are imported in the INSTALLED_APPS and MIDDLEWARE_CLASSES tuples of the myproject/settings.py file." }, { "code": null, "e": 17103, "s": 17063, "text": "For INSTALLED_APPS make sure you have βˆ’" }, { "code": null, "e": 17316, "s": 17103, "text": "INSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'myapp',\n)" }, { "code": null, "e": 17341, "s": 17316, "text": "For MIDDLEWARE_CLASSES βˆ’" }, { "code": null, "e": 17703, "s": 17341, "text": "MIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)" }, { "code": null, "e": 17801, "s": 17703, "text": "Before launching your server, to access your Admin Interface, you need to initiate the database βˆ’" }, { "code": null, "e": 17829, "s": 17801, "text": "$ python manage.py migrate\n" }, { "code": null, "e": 18021, "s": 17829, "text": "syncdb will create necessary tables or collections depending on your db type, necessary for the admin interface to run. Even if you don't have a superuser, you will be prompted to create one." }, { "code": null, "e": 18128, "s": 18021, "text": "If you already have a superuser or have forgotten it, you can always create one using the following code βˆ’" }, { "code": null, "e": 18164, "s": 18128, "text": "$ python manage.py createsuperuser\n" }, { "code": null, "e": 18332, "s": 18164, "text": "Now to start the Admin Interface, we need to make sure we have configured a URL for our admin interface. Open the myproject/url.py and you should have something like βˆ’" }, { "code": null, "e": 18630, "s": 18332, "text": "from django.conf.urls import patterns, include, url\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'myproject.views.home', name = 'home'),\n # url(r'^blog/', include('blog.urls')),\n\n url(r'^admin/', include(admin.site.urls)),\n)" }, { "code": null, "e": 18655, "s": 18630, "text": "Now just run the server." }, { "code": null, "e": 18685, "s": 18655, "text": "$ python manage.py runserver\n" }, { "code": null, "e": 18757, "s": 18685, "text": "And your admin interface is accessible at: http://127.0.0.1:8000/admin/" }, { "code": null, "e": 18837, "s": 18757, "text": "Once connected with your superuser account, you will see the following screen βˆ’" }, { "code": null, "e": 19062, "s": 18837, "text": "That interface will let you administrate Django groups and users, and all registered models in your app. The interface gives you the ability to do at least the \"CRUD\" (Create, Read, Update, Delete) operations on your models." }, { "code": null, "e": 19420, "s": 19062, "text": "A view function, or β€œview” for short, is simply a Python function that takes a web request and returns a web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image, etc. Example: You use view to create web pages, note that you need to associate a view to a URL to see it as a web page." }, { "code": null, "e": 19482, "s": 19420, "text": "In Django, views have to be created in the app views.py file." }, { "code": null, "e": 19548, "s": 19482, "text": "We will create a simple view in myapp to say \"welcome to my app!\"" }, { "code": null, "e": 19573, "s": 19548, "text": "See the following view βˆ’" }, { "code": null, "e": 19705, "s": 19573, "text": "from django.http import HttpResponse\n\ndef hello(request):\n text = \"\"\"<h1>welcome to my app !</h1>\"\"\"\n return HttpResponse(text)" }, { "code": null, "e": 19938, "s": 19705, "text": "In this view, we use HttpResponse to render the HTML (as you have probably noticed we have the HTML hard coded in the view). To see this view as a page we just need to map it to a URL (this will be discussed in an upcoming chapter)." }, { "code": null, "e": 20137, "s": 19938, "text": "We used HttpResponse to render the HTML in the view before. This is not the best way to render pages. Django supports the MVT pattern so to make the precedent view, Django - MVT like, we will need βˆ’" }, { "code": null, "e": 20176, "s": 20137, "text": "A template: myapp/templates/hello.html" }, { "code": null, "e": 20210, "s": 20176, "text": "And now our view will look like βˆ’" }, { "code": null, "e": 20326, "s": 20210, "text": "from django.shortcuts import render\n\ndef hello(request):\n return render(request, \"myapp/template/hello.html\", {})" }, { "code": null, "e": 20361, "s": 20326, "text": "Views can also accept parameters βˆ’" }, { "code": null, "e": 20514, "s": 20361, "text": "from django.http import HttpResponse\n\ndef hello(request, number):\n text = \"<h1>welcome to my app number %s!</h1>\"% number\n return HttpResponse(text)" }, { "code": null, "e": 20677, "s": 20514, "text": "When linked to a URL, the page will display the number passed as a parameter. Note that the parameters will be passed via the URL (discussed in the next chapter)." }, { "code": null, "e": 20925, "s": 20677, "text": "Now that we have a working view as explained in the previous chapters. We want to access that view via a URL. Django has his own way for URL mapping and it's done by editing your project url.py file (myproject/url.py). The url.py file looks like βˆ’" }, { "code": null, "e": 21216, "s": 20925, "text": "from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n #Examples\n #url(r'^$', 'myproject.view.home', name = 'home'),\n #url(r'^blog/', include('blog.urls')),\n\n url(r'^admin', include(admin.site.urls)),\n)" }, { "code": null, "e": 21597, "s": 21216, "text": "When a user makes a request for a page on your web app, Django controller takes over to look for the corresponding view via the url.py file, and then return the HTML response or a 404 not found error, if not found. In url.py, the most important thing is the \"urlpatterns\" tuple. It’s where you define the mapping between URLs and views. A mapping is a tuple in URL patterns like βˆ’" }, { "code": null, "e": 21945, "s": 21597, "text": "from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n #Examples\n #url(r'^$', 'myproject.view.home', name = 'home'),\n #url(r'^blog/', include('blog.urls')),\n\n url(r'^admin', include(admin.site.urls)),\n url(r'^hello/', 'myapp.views.hello', name = 'hello'),\n)" }, { "code": null, "e": 22094, "s": 21945, "text": "The marked line maps the URL \"/home\" to the hello view created in myapp/view.py file. As you can see above a mapping is composed of three elements βˆ’" }, { "code": null, "e": 22299, "s": 22094, "text": "The pattern βˆ’ A regexp matching the URL you want to be resolved and map. Everything that can work with the python 're' module is eligible for the pattern (useful when you want to pass parameters via url)." }, { "code": null, "e": 22504, "s": 22299, "text": "The pattern βˆ’ A regexp matching the URL you want to be resolved and map. Everything that can work with the python 're' module is eligible for the pattern (useful when you want to pass parameters via url)." }, { "code": null, "e": 22575, "s": 22504, "text": "The python path to the view βˆ’ Same as when you are importing a module." }, { "code": null, "e": 22646, "s": 22575, "text": "The python path to the view βˆ’ Same as when you are importing a module." }, { "code": null, "e": 22842, "s": 22646, "text": "The name βˆ’ In order to perform URL reversing, you’ll need to use named URL patterns as done in the examples above. Once done, just start the server to access your view via :http://127.0.0.1/hello" }, { "code": null, "e": 23038, "s": 22842, "text": "The name βˆ’ In order to perform URL reversing, you’ll need to use named URL patterns as done in the examples above. Once done, just start the server to access your view via :http://127.0.0.1/hello" }, { "code": null, "e": 23498, "s": 23038, "text": "So far, we have created the URLs in β€œmyprojects/url.py” file, however as stated earlier about Django and creating an app, the best point was to be able to reuse applications in different projects. You can easily see what the problem is, if you are saving all your URLs in the β€œprojecturl.py” file. So best practice is to create an β€œurl.py” per application and to include it in our main projects url.py file (we included admin URLs for admin interface before)." }, { "code": null, "e": 23567, "s": 23498, "text": "We need to create an url.py file in myapp using the following code βˆ’" }, { "code": null, "e": 23702, "s": 23567, "text": "from django.conf.urls import patterns, include, url\n\nurlpatterns = patterns('', url(r'^hello/', 'myapp.views.hello', name = 'hello'),)" }, { "code": null, "e": 23755, "s": 23702, "text": "Then myproject/url.py will change to the following βˆ’" }, { "code": null, "e": 24089, "s": 23755, "text": "from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n #Examples\n #url(r'^$', 'myproject.view.home', name = 'home'),\n #url(r'^blog/', include('blog.urls')),\n\n url(r'^admin', include(admin.site.urls)),\n url(r'^myapp/', include('myapp.urls')),\n)" }, { "code": null, "e": 24279, "s": 24089, "text": "We have included all URLs from myapp application. The home.html that was accessed through β€œ/hello” is now β€œ/myapp/hello” which is a better and more understandable structure for the web app." }, { "code": null, "e": 24418, "s": 24279, "text": "Now let's imagine we have another view in myapp β€œmorning” and we want to map it in myapp/url.py, we will then change our myapp/url.py to βˆ’" }, { "code": null, "e": 24620, "s": 24418, "text": "from django.conf.urls import patterns, include, url\n\nurlpatterns = patterns('',\n url(r'^hello/', 'myapp.views.hello', name = 'hello'),\n url(r'^morning/', 'myapp.views.morning', name = 'morning'),\n)" }, { "code": null, "e": 24649, "s": 24620, "text": "This can be re-factored to βˆ’" }, { "code": null, "e": 24837, "s": 24649, "text": "from django.conf.urls import patterns, include, url\n\nurlpatterns = patterns('myapp.views',\n url(r'^hello/', 'hello', name = 'hello'),\n url(r'^morning/', 'morning', name = 'morning'),)" }, { "code": null, "e": 24966, "s": 24837, "text": "As you can see, we now use the first element of our urlpatterns tuple. This can be useful when you want to change your app name." }, { "code": null, "e": 25164, "s": 24966, "text": "We now know how to map URL, how to organize them, now let us see how to send parameters to views. A classic sample is the article example (you want to access an article via β€œ/articles/article_id”)." }, { "code": null, "e": 25305, "s": 25164, "text": "Passing parameters is done by capturing them with the regexp in the URL pattern. If we have a view like the following one in β€œmyapp/view.py”" }, { "code": null, "e": 25563, "s": 25305, "text": "from django.shortcuts import render\nfrom django.http import HttpResponse\n\ndef hello(request):\n return render(request, \"hello.html\", {})\n\ndef viewArticle(request, articleId):\n text = \"Displaying article Number : %s\"%articleId\n return HttpResponse(text)" }, { "code": null, "e": 25691, "s": 25563, "text": "We want to map it in myapp/url.py so we can access it via β€œ/myapp/article/articleId”, we need the following in β€œmyapp/url.py” βˆ’" }, { "code": null, "e": 25940, "s": 25691, "text": "from django.conf.urls import patterns, include, url\n\nurlpatterns = patterns('myapp.views',\n url(r'^hello/', 'hello', name = 'hello'),\n url(r'^morning/', 'morning', name = 'morning'),\n url(r'^article/(\\d+)/', 'viewArticle', name = 'article'),)" }, { "code": null, "e": 26106, "s": 25940, "text": "When Django will see the url: β€œ/myapp/article/42” it will pass the parameters '42' to the viewArticle view, and in your browser you should get the following result βˆ’" }, { "code": null, "e": 26271, "s": 26106, "text": "Note that the order of parameters is important here. Suppose we want the list of articles of a month of a year, let's add a viewArticles view. Our view.py becomes βˆ’" }, { "code": null, "e": 26656, "s": 26271, "text": "from django.shortcuts import render\nfrom django.http import HttpResponse\n\ndef hello(request):\n return render(request, \"hello.html\", {})\n\ndef viewArticle(request, articleId):\n text = \"Displaying article Number : %s\"%articleId\n return HttpResponse(text)\n\ndef viewArticles(request, month, year):\n text = \"Displaying articles of : %s/%s\"%(year, month)\n return HttpResponse(text)" }, { "code": null, "e": 26703, "s": 26656, "text": "The corresponding url.py file will look like βˆ’" }, { "code": null, "e": 27025, "s": 26703, "text": "from django.conf.urls import patterns, include, url\n\nurlpatterns = patterns('myapp.views',\n url(r'^hello/', 'hello', name = 'hello'),\n url(r'^morning/', 'morning', name = 'morning'),\n url(r'^article/(\\d+)/', 'viewArticle', name = 'article'),\n url(r'^articles/(\\d{2})/(\\d{4})', 'viewArticles', name = 'articles'),)" }, { "code": null, "e": 27183, "s": 27025, "text": "Now when you go to β€œ/myapp/articles/12/2006/” you will get 'Displaying articles of: 2006/12' but if you reverse the parameters you won’t get the same result." }, { "code": null, "e": 27295, "s": 27183, "text": "To avoid that, it is possible to link a URL parameter to the view parameter. For that, our url.py will become βˆ’" }, { "code": null, "e": 27621, "s": 27295, "text": "from django.conf.urls import patterns, include, url\n\nurlpatterns = patterns('myapp.views',\n url(r'^hello/', 'hello', name = 'hello'),\n url(r'^morning/', 'morning', name = 'morning'),\n url(r'^article/(\\d+)/', 'viewArticle', name = 'article'),\n url(r'^articles/(?P\\d{2})/(?P\\d{4})', 'viewArticles', name = 'articles'),)" }, { "code": null, "e": 27816, "s": 27621, "text": "Django makes it possible to separate python and HTML, the python goes in views and HTML goes in templates. To link the two, Django relies on the render function and the Django Template language." }, { "code": null, "e": 27855, "s": 27816, "text": "This function takes three parameters βˆ’" }, { "code": null, "e": 27886, "s": 27855, "text": "Request βˆ’ The initial request." }, { "code": null, "e": 27917, "s": 27886, "text": "Request βˆ’ The initial request." }, { "code": null, "e": 28036, "s": 27917, "text": "The path to the template βˆ’ This is the path relative to the TEMPLATE_DIRS option in the project settings.py variables." }, { "code": null, "e": 28155, "s": 28036, "text": "The path to the template βˆ’ This is the path relative to the TEMPLATE_DIRS option in the project settings.py variables." }, { "code": null, "e": 28349, "s": 28155, "text": "Dictionary of parameters βˆ’ A dictionary that contains all variables needed in the template. This variable can be created or you can use locals() to pass all local variable declared in the view." }, { "code": null, "e": 28543, "s": 28349, "text": "Dictionary of parameters βˆ’ A dictionary that contains all variables needed in the template. This variable can be created or you can use locals() to pass all local variable declared in the view." }, { "code": null, "e": 28643, "s": 28543, "text": "Django’s template engine offers a mini-language to define the user-facing layer of the application." }, { "code": null, "e": 28854, "s": 28643, "text": "A variable looks like this: {{variable}}. The template replaces the variable by the variable sent by the view in the third parameter of the render function. Let's change our hello.html to display today’s date βˆ’" }, { "code": null, "e": 28865, "s": 28854, "text": "hello.html" }, { "code": null, "e": 28955, "s": 28865, "text": "<html>\n \n <body>\n Hello World!!!<p>Today is {{today}}</p>\n </body>\n \n</html>" }, { "code": null, "e": 28986, "s": 28955, "text": "Then our view will change to βˆ’" }, { "code": null, "e": 29107, "s": 28986, "text": "def hello(request):\n today = datetime.datetime.now().date()\n return render(request, \"hello.html\", {\"today\" : today})" }, { "code": null, "e": 29182, "s": 29107, "text": "We will now get the following output after accessing the URL/myapp/hello βˆ’" }, { "code": null, "e": 29222, "s": 29182, "text": "Hello World!!!\nToday is Sept. 11, 2015\n" }, { "code": null, "e": 29519, "s": 29222, "text": "As you have probably noticed, if the variable is not a string, Django will use the __str__ method to display it; and with the same principle you can access an object attribute just like you do it in Python. For example: if we wanted to display the date year, my variable would be: {{today.year}}." }, { "code": null, "e": 29628, "s": 29519, "text": "They help you modify variables at display time. Filters structure looks like the following: {{var|filters}}." }, { "code": null, "e": 29644, "s": 29628, "text": "Some examples βˆ’" }, { "code": null, "e": 29753, "s": 29644, "text": "{{string|truncatewords:80}} βˆ’ This filter will truncate the string, so you will see only the first 80 words." }, { "code": null, "e": 29862, "s": 29753, "text": "{{string|truncatewords:80}} βˆ’ This filter will truncate the string, so you will see only the first 80 words." }, { "code": null, "e": 29915, "s": 29862, "text": "{{string|lower}} βˆ’ Converts the string to lowercase." }, { "code": null, "e": 29968, "s": 29915, "text": "{{string|lower}} βˆ’ Converts the string to lowercase." }, { "code": null, "e": 30059, "s": 29968, "text": "{{string|escape|linebreaks}} βˆ’ Escapes string contents, then converts line breaks to tags." }, { "code": null, "e": 30150, "s": 30059, "text": "{{string|escape|linebreaks}} βˆ’ Escapes string contents, then converts line breaks to tags." }, { "code": null, "e": 30195, "s": 30150, "text": "You can also set the default for a variable." }, { "code": null, "e": 30298, "s": 30195, "text": "Tags lets you perform the following operations: if condition, for loop, template inheritance and more." }, { "code": null, "e": 30367, "s": 30298, "text": "Just like in Python you can use if, else and elif in your template βˆ’" }, { "code": null, "e": 30669, "s": 30367, "text": "<html>\n <body>\n \n Hello World!!!<p>Today is {{today}}</p>\n We are\n {% if today.day == 1 %}\n \n the first day of month.\n {% elif today.day == 30 %}\n \n the last day of month.\n {% else %}\n \n I don't know.\n {%endif%}\n \n </body>\n</html>" }, { "code": null, "e": 30767, "s": 30669, "text": "In this new template, depending on the date of the day, the template will render a certain value." }, { "code": null, "e": 30906, "s": 30767, "text": "Just like 'if', we have the 'for' tag, that works exactly like in Python. Let's change our hello view to transmit a list to our template βˆ’" }, { "code": null, "e": 31126, "s": 30906, "text": "def hello(request):\n today = datetime.datetime.now().date()\n \n daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']\n return render(request, \"hello.html\", {\"today\" : today, \"days_of_week\" : daysOfWeek})" }, { "code": null, "e": 31178, "s": 31126, "text": "The template to display that list using {{ for }} βˆ’" }, { "code": null, "e": 31589, "s": 31178, "text": "<html>\n <body>\n \n Hello World!!!<p>Today is {{today}}</p>\n We are\n {% if today.day == 1 %}\n \n the first day of month.\n {% elif today.day == 30 %}\n \n the last day of month.\n {% else %}\n \n I don't know.\n {%endif%}\n \n <p>\n {% for day in days_of_week %}\n {{day}}\n </p>\n\t\t\n {% endfor %}\n \n </body>\n</html>" }, { "code": null, "e": 31624, "s": 31589, "text": "And we should get something like βˆ’" }, { "code": null, "e": 31713, "s": 31624, "text": "Hello World!!!\nToday is Sept. 11, 2015\nWe are I don't know.\nMon\nTue\nWed\nThu\nFri\nSat\nSun\n" }, { "code": null, "e": 31992, "s": 31713, "text": "A template system cannot be complete without template inheritance. Meaning when you are designing your templates, you should have a main template with holes that the child's template will fill according to his own need, like a page might need a special css for the selected tab." }, { "code": null, "e": 32067, "s": 31992, "text": "Let’s change the hello.html template to inherit from a main_template.html." }, { "code": null, "e": 32086, "s": 32067, "text": "main_template.html" }, { "code": null, "e": 32319, "s": 32086, "text": "<html>\n <head>\n \n <title>\n {% block title %}Page Title{% endblock %}\n </title>\n \n </head>\n\t\n <body>\n \n {% block content %}\n Body content\n {% endblock %}\n \n </body>\n</html>" }, { "code": null, "e": 32330, "s": 32319, "text": "hello.html" }, { "code": null, "e": 32697, "s": 32330, "text": "{% extends \"main_template.html\" %}\n{% block title %}My Hello Page{% endblock %}\n{% block content %}\n\nHello World!!!<p>Today is {{today}}</p>\nWe are\n{% if today.day == 1 %}\n\nthe first day of month.\n{% elif today.day == 30 %}\n\nthe last day of month.\n{% else %}\n\nI don't know.\n{%endif%}\n\n<p>\n {% for day in days_of_week %}\n {{day}}\n</p>\n\n{% endfor %}\n{% endblock %}" }, { "code": null, "e": 32847, "s": 32697, "text": "In the above example, on calling /myapp/hello we will still get the same result as before but now we rely on extends and block to refactor our code βˆ’" }, { "code": null, "e": 33134, "s": 32847, "text": "In the main_template.html we define blocks using the tag block. The title block will contain the page title and the content block will have the page main content. In home.html we use extends to inherit from the main_template.html then we fill the block define above (content and title)." }, { "code": null, "e": 33312, "s": 33134, "text": "The comment tag helps to define comments into templates, not HTML comments, they won’t appear in HTML page. It can be useful for documentation or just commenting a line of code." }, { "code": null, "e": 33530, "s": 33312, "text": "A model is a class that represents table or collection in our DB, and where every attribute of the class is a field of the table or collection. Models are defined in the app/models.py (in our example: myapp/models.py)" }, { "code": null, "e": 33585, "s": 33530, "text": "Following is a Dreamreal model created as an example βˆ’" }, { "code": null, "e": 33866, "s": 33585, "text": "from django.db import models\n\nclass Dreamreal(models.Model):\n\n website = models.CharField(max_length = 50)\n mail = models.CharField(max_length = 50)\n name = models.CharField(max_length = 50)\n phonenumber = models.IntegerField()\n\n class Meta:\n db_table = \"dreamreal\"" }, { "code": null, "e": 33916, "s": 33866, "text": "Every model inherits from django.db.models.Model." }, { "code": null, "e": 34004, "s": 33916, "text": "Our class has 4 attributes (3 CharField and 1 Integer), those will be the table fields." }, { "code": null, "e": 34238, "s": 34004, "text": "The Meta class with the db_table attribute lets us define the actual table or collection name. Django names the table or collection automatically: myapp_modelName. This class will let you force the name of the table to what you like." }, { "code": null, "e": 34388, "s": 34238, "text": "There is more field's type in django.db.models, you can learn more about them on https://docs.djangoproject.com/en/1.5/ref/models/fields/#field-types" }, { "code": null, "e": 34470, "s": 34388, "text": "After creating your model, you will need Django to generate the actual database βˆ’" }, { "code": null, "e": 34496, "s": 34470, "text": "$python manage.py syncdb\n" }, { "code": null, "e": 34615, "s": 34496, "text": "Let's create a \"crudops\" view to see how we can do CRUD operations on models. Our myapp/views.py will then look like βˆ’" }, { "code": null, "e": 34630, "s": 34615, "text": "myapp/views.py" }, { "code": null, "e": 35653, "s": 34630, "text": "from myapp.models import Dreamreal\nfrom django.http import HttpResponse\n\ndef crudops(request):\n #Creating an entry\n \n dreamreal = Dreamreal(\n website = \"www.polo.com\", mail = \"sorex@polo.com\", \n name = \"sorex\", phonenumber = \"002376970\"\n )\n \n dreamreal.save()\n \n #Read ALL entries\n objects = Dreamreal.objects.all()\n res ='Printing all Dreamreal entries in the DB : <br>'\n \n for elt in objects:\n res += elt.name+\"<br>\"\n \n #Read a specific entry:\n sorex = Dreamreal.objects.get(name = \"sorex\")\n res += 'Printing One entry <br>'\n res += sorex.name\n \n #Delete an entry\n res += '<br> Deleting an entry <br>'\n sorex.delete()\n \n #Update\n dreamreal = Dreamreal(\n website = \"www.polo.com\", mail = \"sorex@polo.com\", \n name = \"sorex\", phonenumber = \"002376970\"\n )\n \n dreamreal.save()\n res += 'Updating entry<br>'\n \n dreamreal = Dreamreal.objects.get(name = 'sorex')\n dreamreal.name = 'thierry'\n dreamreal.save()\n \n return HttpResponse(res)" }, { "code": null, "e": 35846, "s": 35653, "text": "Let's explore other manipulations we can do on Models. Note that the CRUD operations were done on instances of our model, now we will be working directly with the class representing our model." }, { "code": null, "e": 35903, "s": 35846, "text": "Let's create a 'datamanipulation' view in myapp/views.py" }, { "code": null, "e": 36287, "s": 35903, "text": "from myapp.models import Dreamreal\nfrom django.http import HttpResponse\n\ndef datamanipulation(request):\n res = ''\n \n #Filtering data:\n qs = Dreamreal.objects.filter(name = \"paul\")\n res += \"Found : %s results<br>\"%len(qs)\n \n #Ordering results\n qs = Dreamreal.objects.order_by(\"name\")\n \n for elt in qs:\n res += elt.name + '<br>'\n \n return HttpResponse(res)" }, { "code": null, "e": 36329, "s": 36287, "text": "Django ORM offers 3 ways to link models βˆ’" }, { "code": null, "e": 36562, "s": 36329, "text": "One of the first case we will see here is the one-to-many relationships. As you can see in the above example, Dreamreal company can have multiple online websites. Defining that relation is done by using django.db.models.ForeignKey βˆ’" }, { "code": null, "e": 36578, "s": 36562, "text": "myapp/models.py" }, { "code": null, "e": 37037, "s": 36578, "text": "from django.db import models\n\nclass Dreamreal(models.Model):\n website = models.CharField(max_length = 50)\n mail = models.CharField(max_length = 50)\n name = models.CharField(max_length = 50)\n phonenumber = models.IntegerField()\n online = models.ForeignKey('Online', default = 1)\n \n class Meta:\n db_table = \"dreamreal\"\n\nclass Online(models.Model):\n domain = models.CharField(max_length = 30)\n \n class Meta:\n db_table = \"online\"" }, { "code": null, "e": 37148, "s": 37037, "text": "As you can see in our updated myapp/models.py, we added the online model and linked it to our Dreamreal model." }, { "code": null, "e": 37209, "s": 37148, "text": "Let's check how all of this is working via manage.py shell βˆ’" }, { "code": null, "e": 37297, "s": 37209, "text": "First let’s create some companies (Dreamreal entries) for testing in our Django shell βˆ’" }, { "code": null, "e": 37722, "s": 37297, "text": "$python manage.py shell\n\n>>> from myapp.models import Dreamreal, Online\n>>> dr1 = Dreamreal()\n>>> dr1.website = 'company1.com'\n>>> dr1.name = 'company1'\n>>> dr1.mail = 'contact@company1'\n>>> dr1.phonenumber = '12345'\n>>> dr1.save()\n>>> dr2 = Dreamreal()\n>>> dr1.website = 'company2.com'\n>>> dr2.website = 'company2.com'\n>>> dr2.name = 'company2'\n>>> dr2.mail = 'contact@company2'\n>>> dr2.phonenumber = '56789'\n>>> dr2.save()" }, { "code": null, "e": 37748, "s": 37722, "text": "Now some hosted domains βˆ’" }, { "code": null, "e": 38040, "s": 37748, "text": ">>> on1 = Online()\n>>> on1.company = dr1\n>>> on1.domain = \"site1.com\"\n>>> on2 = Online()\n>>> on2.company = dr1\n>>> on2.domain = \"site2.com\"\n>>> on3 = Online()\n>>> on3.domain = \"site3.com\"\n>>> dr2 = Dreamreal.objects.all()[2]\n>>> on3.company = dr2\n>>> on1.save()\n>>> on2.save()\n>>> on3.save()" }, { "code": null, "e": 38135, "s": 38040, "text": "Accessing attribute of the hosting company (Dreamreal entry) from an online domain is simple βˆ’" }, { "code": null, "e": 38157, "s": 38135, "text": ">>> on1.company.name\n" }, { "code": null, "e": 38258, "s": 38157, "text": "And if we want to know all the online domain hosted by a Company in Dreamreal we will use the code βˆ’" }, { "code": null, "e": 38284, "s": 38258, "text": ">>> dr1.online_set.all()\n" }, { "code": null, "e": 38394, "s": 38284, "text": "To get a QuerySet, note that all manipulating method we have seen before (filter, all, exclude, order_by....)" }, { "code": null, "e": 38559, "s": 38394, "text": "You can also access the linked model attributes for filtering operations, let's say you want to get all online domains where the Dreamreal name contains 'company' βˆ’" }, { "code": null, "e": 38622, "s": 38559, "text": ">>> Online.objects.filter(company__name__contains = 'company'\n" }, { "code": null, "e": 38763, "s": 38622, "text": "Note βˆ’ That kind of query is just supported for SQL DB. It won’t work for non-relational DB where joins doesn’t exist and there are two '_'." }, { "code": null, "e": 39060, "s": 38763, "text": "But that's not the only way to link models, you also have OneToOneField, a link that guarantees that the relation between two objects is unique. If we used the OneToOneField in our example above, that would mean for every Dreamreal entry only one Online entry is possible and in the other way to." }, { "code": null, "e": 39176, "s": 39060, "text": "And the last one, the ManyToManyField for (n-n) relation between tables. Note, those are relevant for SQL based DB." }, { "code": null, "e": 39552, "s": 39176, "text": "Page redirection is needed for many reasons in web application. You might want to redirect a user to another page when a specific action occurs, or basically in case of error. For example, when a user logs in to your website, he is often redirected either to the main home page or to his personal dashboard. In Django, redirection is accomplished using the 'redirect' method." }, { "code": null, "e": 39655, "s": 39552, "text": "The 'redirect' method takes as argument: The URL you want to be redirected to as string A view's name." }, { "code": null, "e": 39705, "s": 39655, "text": "The myapp/views looks like the following so far βˆ’" }, { "code": null, "e": 40228, "s": 39705, "text": "def hello(request):\n today = datetime.datetime.now().date()\n daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']\n return render(request, \"hello.html\", {\"today\" : today, \"days_of_week\" : daysOfWeek})\n\t\ndef viewArticle(request, articleId):\n \"\"\" A view that display an article based on his ID\"\"\"\n text = \"Displaying article Number : %s\" %articleId\n return HttpResponse(text)\n\t\ndef viewArticles(request, year, month):\n text = \"Displaying articles of : %s/%s\"%(year, month)\n return HttpResponse(text)" }, { "code": null, "e": 40400, "s": 40228, "text": "Let's change the hello view to redirect to djangoproject.com and our viewArticle to redirect to our internal '/myapp/articles'. To do so the myapp/view.py will change to βˆ’" }, { "code": null, "e": 41046, "s": 40400, "text": "from django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nimport datetime\n\n# Create your views here.\ndef hello(request):\n today = datetime.datetime.now().date()\n daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']\n return redirect(\"https://www.djangoproject.com\")\n\t\ndef viewArticle(request, articleId):\n \"\"\" A view that display an article based on his ID\"\"\"\n text = \"Displaying article Number : %s\" %articleId\n return redirect(viewArticles, year = \"2045\", month = \"02\")\n\t\ndef viewArticles(request, year, month):\n text = \"Displaying articles of : %s/%s\"%(year, month)\n return HttpResponse(text)" }, { "code": null, "e": 41355, "s": 41046, "text": "In the above example, first we imported redirect from django.shortcuts and for redirection to the Django official website we just pass the full URL to the 'redirect' method as string, and for the second example (the viewArticle view) the 'redirect' method takes the view name and his parameters as arguments." }, { "code": null, "e": 41416, "s": 41355, "text": "Accessing /myapp/hello, will give you the following screen βˆ’" }, { "code": null, "e": 41486, "s": 41416, "text": "And accessing /myapp/article/42, will give you the following screen βˆ’" }, { "code": null, "e": 41727, "s": 41486, "text": "It is also possible to specify whether the 'redirect' is temporary or permanent by adding permanent = True parameter. The user will see no difference, but these are details that search engines take into account when ranking of your website." }, { "code": null, "e": 41813, "s": 41727, "text": "Also remember that 'name' parameter we defined in our url.py while mapping the URLs βˆ’" }, { "code": null, "e": 41889, "s": 41813, "text": "url(r'^articles/(?P\\d{2})/(?P\\d{4})/', 'viewArticles', name = 'articles'),\n" }, { "code": null, "e": 42020, "s": 41889, "text": "That name (here article) can be used as argument for the 'redirect' method, then our viewArticle redirection can be changed from βˆ’" }, { "code": null, "e": 42230, "s": 42020, "text": "def viewArticle(request, articleId):\n \"\"\" A view that display an article based on his ID\"\"\"\n text = \"Displaying article Number : %s\" %articleId\n return redirect(viewArticles, year = \"2045\", month = \"02\")" }, { "code": null, "e": 42235, "s": 42230, "text": "To βˆ’" }, { "code": null, "e": 42441, "s": 42235, "text": "def viewArticle(request, articleId):\n \"\"\" A view that display an article based on his ID\"\"\"\n text = \"Displaying article Number : %s\" %articleId\n return redirect(articles, year = \"2045\", month = \"02\")" }, { "code": null, "e": 42735, "s": 42441, "text": "Note βˆ’ There is also a function to generate URLs; it is used in the same way as redirect; the 'reverse' method (django.core.urlresolvers.reverse). This function does not return a HttpResponseRedirect object, but simply a string containing the URL to the view compiled with any passed argument." }, { "code": null, "e": 43004, "s": 42735, "text": "Django comes with a ready and easy-to-use light engine to send e-mail. Similar to Python you just need an import of smtplib. In Django you just need to import django.core.mail. To start sending e-mail, edit your project settings.py file and set the following options βˆ’" }, { "code": null, "e": 43030, "s": 43004, "text": "EMAIL_HOST βˆ’ smtp server." }, { "code": null, "e": 43056, "s": 43030, "text": "EMAIL_HOST βˆ’ smtp server." }, { "code": null, "e": 43112, "s": 43056, "text": "EMAIL_HOST_USER βˆ’ Login credential for the smtp server." }, { "code": null, "e": 43168, "s": 43112, "text": "EMAIL_HOST_USER βˆ’ Login credential for the smtp server." }, { "code": null, "e": 43231, "s": 43168, "text": "EMAIL_HOST_PASSWORD βˆ’ Password credential for the smtp server." }, { "code": null, "e": 43294, "s": 43231, "text": "EMAIL_HOST_PASSWORD βˆ’ Password credential for the smtp server." }, { "code": null, "e": 43325, "s": 43294, "text": "EMAIL_PORT βˆ’ smtp server port." }, { "code": null, "e": 43356, "s": 43325, "text": "EMAIL_PORT βˆ’ smtp server port." }, { "code": null, "e": 43407, "s": 43356, "text": "EMAIL_USE_TLS or _SSL βˆ’ True if secure connection." }, { "code": null, "e": 43458, "s": 43407, "text": "EMAIL_USE_TLS or _SSL βˆ’ True if secure connection." }, { "code": null, "e": 43521, "s": 43458, "text": "Let's create a \"sendSimpleEmail\" view to send a simple e-mail." }, { "code": null, "e": 43749, "s": 43521, "text": "from django.core.mail import send_mail\nfrom django.http import HttpResponse\n\ndef sendSimpleEmail(request,emailto):\n res = send_mail(\"hello paul\", \"comment tu vas?\", \"paul@polo.com\", [emailto])\n return HttpResponse('%s'%res)" }, { "code": null, "e": 43802, "s": 43749, "text": "Here is the details of the parameters of send_mail βˆ’" }, { "code": null, "e": 43828, "s": 43802, "text": "subject βˆ’ E-mail subject." }, { "code": null, "e": 43854, "s": 43828, "text": "subject βˆ’ E-mail subject." }, { "code": null, "e": 43877, "s": 43854, "text": "message βˆ’ E-mail body." }, { "code": null, "e": 43900, "s": 43877, "text": "message βˆ’ E-mail body." }, { "code": null, "e": 43926, "s": 43900, "text": "from_email βˆ’ E-mail from." }, { "code": null, "e": 43952, "s": 43926, "text": "from_email βˆ’ E-mail from." }, { "code": null, "e": 44004, "s": 43952, "text": "recipient_list βˆ’ List of receivers’ e-mail address." }, { "code": null, "e": 44056, "s": 44004, "text": "recipient_list βˆ’ List of receivers’ e-mail address." }, { "code": null, "e": 44139, "s": 44056, "text": "fail_silently βˆ’ Bool, if false send_mail will raise an exception in case of error." }, { "code": null, "e": 44222, "s": 44139, "text": "fail_silently βˆ’ Bool, if false send_mail will raise an exception in case of error." }, { "code": null, "e": 44272, "s": 44222, "text": "auth_user βˆ’ User login if not set in settings.py." }, { "code": null, "e": 44322, "s": 44272, "text": "auth_user βˆ’ User login if not set in settings.py." }, { "code": null, "e": 44379, "s": 44322, "text": "auth_password βˆ’ User password if not set in settings.py." }, { "code": null, "e": 44436, "s": 44379, "text": "auth_password βˆ’ User password if not set in settings.py." }, { "code": null, "e": 44465, "s": 44436, "text": "connection βˆ’ E-mail backend." }, { "code": null, "e": 44494, "s": 44465, "text": "connection βˆ’ E-mail backend." }, { "code": null, "e": 44583, "s": 44494, "text": "html_message βˆ’ (new in Django 1.7) if present, the e-mail will be multipart/alternative." }, { "code": null, "e": 44672, "s": 44583, "text": "html_message βˆ’ (new in Django 1.7) if present, the e-mail will be multipart/alternative." }, { "code": null, "e": 44712, "s": 44672, "text": "Let's create a URL to access our view βˆ’" }, { "code": null, "e": 44924, "s": 44712, "text": "from django.conf.urls import patterns, url\n\nurlpatterns = paterns('myapp.views', url(r'^simpleemail/(?P<emailto>\n [\\w.%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4})/', \n 'sendSimpleEmail' , name = 'sendSimpleEmail'),)" }, { "code": null, "e": 45011, "s": 44924, "text": "So when accessing /myapp/simpleemail/polo@gmail.com, you will get the following page βˆ’" }, { "code": null, "e": 45182, "s": 45011, "text": "The method returns the number of messages successfully delivered. This is same as send_mail but takes an extra parameter; datatuple, our sendMassEmail view will then be βˆ’" }, { "code": null, "e": 45526, "s": 45182, "text": "from django.core.mail import send_mass_mail\nfrom django.http import HttpResponse\n\ndef sendMassEmail(request,emailto):\n msg1 = ('subject 1', 'message 1', 'polo@polo.com', [emailto1])\n msg2 = ('subject 2', 'message 2', 'polo@polo.com', [emailto2])\n res = send_mass_mail((msg1, msg2), fail_silently = False)\n return HttpResponse('%s'%res)" }, { "code": null, "e": 45566, "s": 45526, "text": "Let's create a URL to access our view βˆ’" }, { "code": null, "e": 45826, "s": 45566, "text": "from django.conf.urls import patterns, url\n\nurlpatterns = paterns('myapp.views', url(r'^massEmail/(?P<emailto1>\n [\\w.%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4})/(?P<emailto2>\n [\\w.%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4})', 'sendMassEmail' , name = 'sendMassEmail'),)" }, { "code": null, "e": 45900, "s": 45826, "text": "When accessing /myapp/massemail/polo@gmail.com/sorex@gmail.com/, we get βˆ’" }, { "code": null, "e": 45940, "s": 45900, "text": "send_mass_mail parameters details are βˆ’" }, { "code": null, "e": 46036, "s": 45940, "text": "datatuples βˆ’ A tuple where each element is like (subject, message, from_email, recipient_list)." }, { "code": null, "e": 46132, "s": 46036, "text": "datatuples βˆ’ A tuple where each element is like (subject, message, from_email, recipient_list)." }, { "code": null, "e": 46215, "s": 46132, "text": "fail_silently βˆ’ Bool, if false send_mail will raise an exception in case of error." }, { "code": null, "e": 46298, "s": 46215, "text": "fail_silently βˆ’ Bool, if false send_mail will raise an exception in case of error." }, { "code": null, "e": 46348, "s": 46298, "text": "auth_user βˆ’ User login if not set in settings.py." }, { "code": null, "e": 46398, "s": 46348, "text": "auth_user βˆ’ User login if not set in settings.py." }, { "code": null, "e": 46455, "s": 46398, "text": "auth_password βˆ’ User password if not set in settings.py." }, { "code": null, "e": 46512, "s": 46455, "text": "auth_password βˆ’ User password if not set in settings.py." }, { "code": null, "e": 46541, "s": 46512, "text": "connection βˆ’ E-mail backend." }, { "code": null, "e": 46570, "s": 46541, "text": "connection βˆ’ E-mail backend." }, { "code": null, "e": 46642, "s": 46570, "text": "As you can see in the above image, two messages were sent successfully." }, { "code": null, "e": 46735, "s": 46642, "text": "Note βˆ’ In this example we are using Python smtp debuggingserver, that you can launch using βˆ’" }, { "code": null, "e": 46790, "s": 46735, "text": "$python -m smtpd -n -c DebuggingServer localhost:1025\n" }, { "code": null, "e": 46901, "s": 46790, "text": "This means all your sent e-mails will be printed on stdout, and the dummy server is running on localhost:1025." }, { "code": null, "e": 46984, "s": 46901, "text": "Sending e-mails to admins and managers using mail_admins and mail_managers methods" }, { "code": null, "e": 47224, "s": 46984, "text": "These methods send e-mails to site administrators as defined in the ADMINS option of the settings.py file, and to site managers as defined in MANAGERS option of the settings.py file. Let's assume our ADMINS and MANAGERS options look like βˆ’" }, { "code": null, "e": 47262, "s": 47224, "text": "ADMINS = (('polo', 'polo@polo.com'),)" }, { "code": null, "e": 47306, "s": 47262, "text": "MANAGERS = (('popoli', 'popoli@polo.com'),)" }, { "code": null, "e": 47506, "s": 47306, "text": "from django.core.mail import mail_admins\nfrom django.http import HttpResponse\n\ndef sendAdminsEmail(request):\n res = mail_admins('my subject', 'site is going down.')\n return HttpResponse('%s'%res)" }, { "code": null, "e": 47587, "s": 47506, "text": "The above code will send an e-mail to every admin defined in the ADMINS section." }, { "code": null, "e": 47800, "s": 47587, "text": "from django.core.mail import mail_managers\nfrom django.http import HttpResponse\n\ndef sendManagersEmail(request):\n res = mail_managers('my subject 2', 'Change date on the site.')\n return HttpResponse('%s'%res)" }, { "code": null, "e": 47885, "s": 47800, "text": "The above code will send an e-mail to every manager defined in the MANAGERS section." }, { "code": null, "e": 47906, "s": 47885, "text": "Parameters details βˆ’" }, { "code": null, "e": 47932, "s": 47906, "text": "Subject βˆ’ E-mail subject." }, { "code": null, "e": 47958, "s": 47932, "text": "Subject βˆ’ E-mail subject." }, { "code": null, "e": 47981, "s": 47958, "text": "message βˆ’ E-mail body." }, { "code": null, "e": 48004, "s": 47981, "text": "message βˆ’ E-mail body." }, { "code": null, "e": 48087, "s": 48004, "text": "fail_silently βˆ’ Bool, if false send_mail will raise an exception in case of error." }, { "code": null, "e": 48170, "s": 48087, "text": "fail_silently βˆ’ Bool, if false send_mail will raise an exception in case of error." }, { "code": null, "e": 48199, "s": 48170, "text": "connection βˆ’ E-mail backend." }, { "code": null, "e": 48228, "s": 48199, "text": "connection βˆ’ E-mail backend." }, { "code": null, "e": 48317, "s": 48228, "text": "html_message βˆ’ (new in Django 1.7) if present, the e-mail will be multipart/alternative." }, { "code": null, "e": 48406, "s": 48317, "text": "html_message βˆ’ (new in Django 1.7) if present, the e-mail will be multipart/alternative." }, { "code": null, "e": 48460, "s": 48406, "text": "Sending HTML message in Django >= 1.7 is as easy as βˆ’" }, { "code": null, "e": 48652, "s": 48460, "text": "from django.core.mail import send_mail\n\nfrom django.http import HttpResponse\n res = send_mail(\"hello paul\", \"comment tu vas?\", \"paul@polo.com\", \n [\"polo@gmail.com\"], html_message=\")" }, { "code": null, "e": 48702, "s": 48652, "text": "This will produce a multipart/alternative e-mail." }, { "code": null, "e": 48833, "s": 48702, "text": "But for Django < 1.7 sending HTML messages is done via the django.core.mail.EmailMessage class then calling 'send' on the object βˆ’" }, { "code": null, "e": 48893, "s": 48833, "text": "Let's create a \"sendHTMLEmail\" view to send an HTML e-mail." }, { "code": null, "e": 49233, "s": 48893, "text": "from django.core.mail import EmailMessage\nfrom django.http import HttpResponse\n\ndef sendHTMLEmail(request , emailto):\n html_content = \"<strong>Comment tu vas?</strong>\"\n email = EmailMessage(\"my subject\", html_content, \"paul@polo.com\", [emailto])\n email.content_subtype = \"html\"\n res = email.send()\n return HttpResponse('%s'%res)" }, { "code": null, "e": 49290, "s": 49233, "text": "Parameters details for the EmailMessage class creation βˆ’" }, { "code": null, "e": 49316, "s": 49290, "text": "Subject βˆ’ E-mail subject." }, { "code": null, "e": 49342, "s": 49316, "text": "Subject βˆ’ E-mail subject." }, { "code": null, "e": 49373, "s": 49342, "text": "message βˆ’ E-mail body in HTML." }, { "code": null, "e": 49404, "s": 49373, "text": "message βˆ’ E-mail body in HTML." }, { "code": null, "e": 49430, "s": 49404, "text": "from_email βˆ’ E-mail from." }, { "code": null, "e": 49456, "s": 49430, "text": "from_email βˆ’ E-mail from." }, { "code": null, "e": 49496, "s": 49456, "text": "to βˆ’ List of receivers’ e-mail address." }, { "code": null, "e": 49536, "s": 49496, "text": "to βˆ’ List of receivers’ e-mail address." }, { "code": null, "e": 49583, "s": 49536, "text": "bcc βˆ’ List of β€œBcc” receivers’ e-mail address." }, { "code": null, "e": 49630, "s": 49583, "text": "bcc βˆ’ List of β€œBcc” receivers’ e-mail address." }, { "code": null, "e": 49659, "s": 49630, "text": "connection βˆ’ E-mail backend." }, { "code": null, "e": 49688, "s": 49659, "text": "connection βˆ’ E-mail backend." }, { "code": null, "e": 49728, "s": 49688, "text": "Let's create a URL to access our view βˆ’" }, { "code": null, "e": 49934, "s": 49728, "text": "from django.conf.urls import patterns, url\n\nurlpatterns = paterns('myapp.views', url(r'^htmlemail/(?P<emailto>\n [\\w.%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4})/', \n 'sendHTMLEmail' , name = 'sendHTMLEmail'),)" }, { "code": null, "e": 49991, "s": 49934, "text": "When accessing /myapp/htmlemail/polo@gmail.com, we get βˆ’" }, { "code": null, "e": 50061, "s": 49991, "text": "This is done by using the 'attach' method on the EmailMessage object." }, { "code": null, "e": 50112, "s": 50061, "text": "A view to send an e-mail with attachment will be βˆ’" }, { "code": null, "e": 50532, "s": 50112, "text": "from django.core.mail import EmailMessage\nfrom django.http import HttpResponse\n\ndef sendEmailWithAttach(request, emailto):\n html_content = \"Comment tu vas?\"\n email = EmailMessage(\"my subject\", html_content, \"paul@polo.com\", emailto])\n email.content_subtype = \"html\"\n \n fd = open('manage.py', 'r')\n email.attach('manage.py', fd.read(), 'text/plain')\n \n res = email.send()\n return HttpResponse('%s'%res)" }, { "code": null, "e": 50562, "s": 50532, "text": "Details on attach arguments βˆ’" }, { "code": null, "e": 50605, "s": 50562, "text": "filename βˆ’ The name of the file to attach." }, { "code": null, "e": 50648, "s": 50605, "text": "filename βˆ’ The name of the file to attach." }, { "code": null, "e": 50693, "s": 50648, "text": "content βˆ’ The content of the file to attach." }, { "code": null, "e": 50738, "s": 50693, "text": "content βˆ’ The content of the file to attach." }, { "code": null, "e": 50785, "s": 50738, "text": "mimetype βˆ’ The attachment's content mime type." }, { "code": null, "e": 50832, "s": 50785, "text": "mimetype βˆ’ The attachment's content mime type." }, { "code": null, "e": 51035, "s": 50832, "text": "In some cases, writing views, as we have seen earlier is really heavy. Imagine you need a static page or a listing page. Django offers an easy way to set those simple views that is called generic views." }, { "code": null, "e": 51262, "s": 51035, "text": "Unlike classic views, generic views are classes not functions. Django offers a set of classes for generic views in django.views.generic, and every generic view is one of those classes or a class that inherits from one of them." }, { "code": null, "e": 51294, "s": 51262, "text": "There are 10+ generic classes βˆ’" }, { "code": null, "e": 51773, "s": 51294, "text": ">>> import django.views.generic\n>>> dir(django.views.generic)\n\n['ArchiveIndexView', 'CreateView', 'DateDetailView', 'DayArchiveView', \n 'DeleteView', 'DetailView', 'FormView', 'GenericViewError', 'ListView', \n 'MonthArchiveView', 'RedirectView', 'TemplateView', 'TodayArchiveView', \n 'UpdateView', 'View', 'WeekArchiveView', 'YearArchiveView', '__builtins__', \n '__doc__', '__file__', '__name__', '__package__', '__path__', 'base', 'dates', \n 'detail', 'edit', 'list']" }, { "code": null, "e": 51861, "s": 51773, "text": "This you can use for your generic view. Let's look at some example to see how it works." }, { "code": null, "e": 51922, "s": 51861, "text": "Let's publish a static page from the β€œstatic.html” template." }, { "code": null, "e": 51940, "s": 51922, "text": "Our static.html βˆ’" }, { "code": null, "e": 52009, "s": 51940, "text": "<html>\n <body> \n This is a static page!!! \n </body>\n</html>" }, { "code": null, "e": 52102, "s": 52009, "text": "If we did that the way we learned before, we would have to change the myapp/views.py to be βˆ’" }, { "code": null, "e": 52205, "s": 52102, "text": "from django.shortcuts import render\n\ndef static(request):\n return render(request, 'static.html', {})" }, { "code": null, "e": 52231, "s": 52205, "text": "and myapp/urls.py to be βˆ’" }, { "code": null, "e": 52359, "s": 52231, "text": "from django.conf.urls import patterns, url\n\nurlpatterns = patterns(\"myapp.views\", url(r'^static/', 'static', name = 'static'),)" }, { "code": null, "e": 52440, "s": 52359, "text": "The best way is to use generic views. For that, our myapp/views.py will become βˆ’" }, { "code": null, "e": 52552, "s": 52440, "text": "from django.views.generic import TemplateView\n\nclass StaticView(TemplateView):\n template_name = \"static.html\"" }, { "code": null, "e": 52587, "s": 52552, "text": "And our myapp/urls.py we will be βˆ’" }, { "code": null, "e": 52738, "s": 52587, "text": "from myapp.views import StaticView\nfrom django.conf.urls import patterns\n\nurlpatterns = patterns(\"myapp.views\", (r'^static/$', StaticView.as_view()),)" }, { "code": null, "e": 52777, "s": 52738, "text": "When accessing /myapp/static you get βˆ’" }, { "code": null, "e": 52829, "s": 52777, "text": "For the same result we can also, do the following βˆ’" }, { "code": null, "e": 52855, "s": 52829, "text": "No change in the views.py" }, { "code": null, "e": 52886, "s": 52855, "text": "Change the url.py file to be βˆ’" }, { "code": null, "e": 53088, "s": 52886, "text": "from django.views.generic import TemplateView\nfrom django.conf.urls import patterns, url\n\nurlpatterns = patterns(\"myapp.views\",\n url(r'^static/',TemplateView.as_view(template_name = 'static.html')),)" }, { "code": null, "e": 53166, "s": 53088, "text": "As you can see, you just need to change the url.py file in the second method." }, { "code": null, "e": 53327, "s": 53166, "text": "We are going to list all entries in our Dreamreal model. Doing so is made easy by using the ListView generic view class. Edit the url.py file and update it as βˆ’" }, { "code": null, "e": 53562, "s": 53327, "text": "from django.views.generic import ListView\nfrom django.conf.urls import patterns, url\n\nurlpatterns = patterns(\n \"myapp.views\", url(r'^dreamreals/', ListView.as_view(model = Dreamreal, \n template_name = \"dreamreal_list.html\")),\n)" }, { "code": null, "e": 53810, "s": 53562, "text": "Important to note at this point is that the variable pass by the generic view to the template is object_list. If you want to name it yourself, you will need to add a context_object_name argument to the as_view method. Then the url.py will become βˆ’" }, { "code": null, "e": 54094, "s": 53810, "text": "from django.views.generic import ListView\nfrom django.conf.urls import patterns, url\n\nurlpatterns = patterns(\"myapp.views\",\n url(r'^dreamreals/', ListView.as_view(\n template_name = \"dreamreal_list.html\")),\n model = Dreamreal, context_object_name = ”dreamreals_objects” ,)" }, { "code": null, "e": 54133, "s": 54094, "text": "The associated template will then be βˆ’" }, { "code": null, "e": 54275, "s": 54133, "text": "{% extends \"main_template.html\" %}\n{% block content %}\nDreamreals:<p>\n{% for dr in object_list %}\n{{dr.name}}</p>\n{% endfor %}\n{% endblock %}" }, { "code": null, "e": 54338, "s": 54275, "text": "Accessing /myapp/dreamreals/ will produce the following page βˆ’" }, { "code": null, "e": 54604, "s": 54338, "text": "Creating forms in Django, is really similar to creating a model. Here again, we just need to inherit from Django class and the class attributes will be the form fields. Let's add a forms.py file in myapp folder to contain our app forms. We will create a login form." }, { "code": null, "e": 54619, "s": 54604, "text": "myapp/forms.py" }, { "code": null, "e": 54803, "s": 54619, "text": "#-*- coding: utf-8 -*-\nfrom django import forms\n\nclass LoginForm(forms.Form):\n user = forms.CharField(max_length = 100)\n password = forms.CharField(widget = forms.PasswordInput())" }, { "code": null, "e": 55041, "s": 54803, "text": "As seen above, the field type can take \"widget\" argument for html rendering; in our case, we want the password to be hidden, not displayed. Many others widget are present in Django: DateInput for dates, CheckboxInput for checkboxes, etc." }, { "code": null, "e": 55305, "s": 55041, "text": "There are two kinds of HTTP requests, GET and POST. In Django, the request object passed as parameter to your view has an attribute called \"method\" where the type of the request is set, and all data passed via POST can be accessed via the request.POST dictionary." }, { "code": null, "e": 55355, "s": 55305, "text": "Let's create a login view in our myapp/views.py βˆ’" }, { "code": null, "e": 55779, "s": 55355, "text": "#-*- coding: utf-8 -*-\nfrom myapp.forms import LoginForm\n\ndef login(request):\n username = \"not logged in\"\n \n if request.method == \"POST\":\n #Get the posted form\n MyLoginForm = LoginForm(request.POST)\n \n if MyLoginForm.is_valid():\n username = MyLoginForm.cleaned_data['username']\n else:\n MyLoginForm = Loginform()\n\t\t\n return render(request, 'loggedin.html', {\"username\" : username})" }, { "code": null, "e": 55946, "s": 55779, "text": "The view will display the result of the login form posted through the loggedin.html. To test it, we will first need the login form template. Let's call it login.html." }, { "code": null, "e": 57057, "s": 55946, "text": "<html>\n <body>\n \n <form name = \"form\" action = \"{% url \"myapp.views.login\" %}\" \n method = \"POST\" >{% csrf_token %}\n \n <div style = \"max-width:470px;\">\n <center> \n <input type = \"text\" style = \"margin-left:20%;\" \n placeholder = \"Identifiant\" name = \"username\" />\n </center>\n </div>\n\t\t\t\n <br>\n \n <div style = \"max-width:470px;\">\n <center>\n <input type = \"password\" style = \"margin-left:20%;\" \n placeholder = \"password\" name = \"password\" />\n </center>\n </div>\n\t\t\t\n <br>\n \n <div style = \"max-width:470px;\">\n <center> \n \n <button style = \"border:0px; background-color:#4285F4; margin-top:8%;\n height:35px; width:80%;margin-left:19%;\" type = \"submit\" \n value = \"Login\" >\n <strong>Login</strong>\n </button>\n \n </center>\n </div>\n \n </form>\n \n </body>\n</html>" }, { "code": null, "e": 57272, "s": 57057, "text": "The template will display a login form and post the result to our login view above. You have probably noticed the tag in the template, which is just to prevent Cross-site Request Forgery (CSRF) attack on your site." }, { "code": null, "e": 57290, "s": 57272, "text": "{% csrf_token %}\n" }, { "code": null, "e": 57402, "s": 57290, "text": "Once we have the login template, we need the loggedin.html template that will be rendered after form treatment." }, { "code": null, "e": 57492, "s": 57402, "text": "<html>\n \n <body>\n You are : <strong>{{username}}</strong>\n </body>\n \n</html>" }, { "code": null, "e": 57557, "s": 57492, "text": "Now, we just need our pair of URLs to get started: myapp/urls.py" }, { "code": null, "e": 57806, "s": 57557, "text": "from django.conf.urls import patterns, url\nfrom django.views.generic import TemplateView\n\nurlpatterns = patterns('myapp.views',\n url(r'^connection/',TemplateView.as_view(template_name = 'login.html')),\n url(r'^login/', 'login', name = 'login'))" }, { "code": null, "e": 57899, "s": 57806, "text": "When accessing \"/myapp/connection\", we will get the following login.html template rendered βˆ’" }, { "code": null, "e": 58000, "s": 57899, "text": "On the form post, the form is valid. In our case make sure to fill the two fields and you will get βˆ’" }, { "code": null, "e": 58097, "s": 58000, "text": "In case your username is polo, and you forgot the password. You will get the following message βˆ’" }, { "code": null, "e": 58146, "s": 58097, "text": "In the above example, when validating the form βˆ’" }, { "code": null, "e": 58170, "s": 58146, "text": "MyLoginForm.is_valid()\n" }, { "code": null, "e": 58407, "s": 58170, "text": "We only used Django self-form validation engine, in our case just making sure the fields are required. Now let’s try to make sure the user trying to login is present in our DB as Dreamreal entry. For this, change the myapp/forms.py to βˆ’" }, { "code": null, "e": 58884, "s": 58407, "text": "#-*- coding: utf-8 -*-\nfrom django import forms\nfrom myapp.models import Dreamreal\n\nclass LoginForm(forms.Form):\n user = forms.CharField(max_length = 100)\n password = forms.CharField(widget = forms.PasswordInput())\n\n def clean_message(self):\n username = self.cleaned_data.get(\"username\")\n dbuser = Dreamreal.objects.filter(name = username)\n \n if not dbuser:\n raise forms.ValidationError(\"User does not exist in our db!\")\n return username" }, { "code": null, "e": 59164, "s": 58884, "text": "Now, after calling the \"is_valid\" method, we will get the correct output, only if the user is in our database. If you want to check a field of your form, just add a method starting by \"clean_\" then your field name to your form class. Raising a forms.ValidationError is important." }, { "code": null, "e": 59322, "s": 59164, "text": "It is generally useful for a web app to be able to upload files (profile picture, songs, pdf, words.....). Let's discuss how to upload files in this chapter." }, { "code": null, "e": 59513, "s": 59322, "text": "Before starting to play with an image, make sure you have the Python Image Library (PIL) installed. Now to illustrate uploading an image, let's create a profile form, in our myapp/forms.py βˆ’" }, { "code": null, "e": 59670, "s": 59513, "text": "#-*- coding: utf-8 -*-\nfrom django import forms\n\nclass ProfileForm(forms.Form):\n name = forms.CharField(max_length = 100)\n picture = forms.ImageFields()" }, { "code": null, "e": 59837, "s": 59670, "text": "As you can see, the main difference here is just the forms.ImageField. ImageField will make sure the uploaded file is an image. If not, the form validation will fail." }, { "code": null, "e": 59936, "s": 59837, "text": "Now let's create a \"Profile\" model to save our uploaded profile. This is done in myapp/models.py βˆ’" }, { "code": null, "e": 60137, "s": 59936, "text": "from django.db import models\n\nclass Profile(models.Model):\n name = models.CharField(max_length = 50)\n picture = models.ImageField(upload_to = 'pictures')\n\n class Meta:\n db_table = \"profile\"" }, { "code": null, "e": 60396, "s": 60137, "text": "As you can see for the model, the ImageField takes a compulsory argument: upload_to. This represents the place on the hard drive where your images will be saved. Note that the parameter will be added to the MEDIA_ROOT option defined in your settings.py file." }, { "code": null, "e": 60480, "s": 60396, "text": "Now that we have the Form and the Model, let's create the view, in myapp/views.py βˆ’" }, { "code": null, "e": 61081, "s": 60480, "text": "#-*- coding: utf-8 -*-\nfrom myapp.forms import ProfileForm\nfrom myapp.models import Profile\n\ndef SaveProfile(request):\n saved = False\n \n if request.method == \"POST\":\n #Get the posted form\n MyProfileForm = ProfileForm(request.POST, request.FILES)\n \n if MyProfileForm.is_valid():\n profile = Profile()\n profile.name = MyProfileForm.cleaned_data[\"name\"]\n profile.picture = MyProfileForm.cleaned_data[\"picture\"]\n profile.save()\n saved = True\n else:\n MyProfileForm = Profileform()\n\t\t\n return render(request, 'saved.html', locals())" }, { "code": null, "e": 61292, "s": 61081, "text": "The part not to miss is, there is a change when creating a ProfileForm, we added a second parameters: request.FILES. If not passed the form validation will fail, giving a message that says the picture is empty." }, { "code": null, "e": 61405, "s": 61292, "text": "Now, we just need the saved.html template and the profile.html template, for the form and the redirection page βˆ’" }, { "code": null, "e": 61434, "s": 61405, "text": "myapp/templates/saved.html βˆ’" }, { "code": null, "e": 61674, "s": 61434, "text": "<html>\n <body>\n \n {% if saved %}\n <strong>Your profile was saved.</strong>\n {% endif %}\n \n {% if not saved %}\n <strong>Your profile was not saved.</strong>\n {% endif %}\n \n </body>\n</html>" }, { "code": null, "e": 61705, "s": 61674, "text": "myapp/templates/profile.html βˆ’" }, { "code": null, "e": 62815, "s": 61705, "text": "<html>\n <body>\n \n <form name = \"form\" enctype = \"multipart/form-data\" \n action = \"{% url \"myapp.views.SaveProfile\" %}\" method = \"POST\" >{% csrf_token %}\n \n <div style = \"max-width:470px;\">\n <center> \n <input type = \"text\" style = \"margin-left:20%;\" \n placeholder = \"Name\" name = \"name\" />\n </center>\n </div>\n\t\t\t\n <br>\n \n <div style = \"max-width:470px;\">\n <center> \n <input type = \"file\" style = \"margin-left:20%;\" \n placeholder = \"Picture\" name = \"picture\" />\n </center>\n </div>\n\t\t\t\n <br>\n \n <div style = \"max-width:470px;\">\n <center> \n \n <button style = \"border:0px;background-color:#4285F4; margin-top:8%; \n height:35px; width:80%; margin-left:19%;\" type = \"submit\" value = \"Login\" >\n <strong>Login</strong>\n </button>\n \n </center>\n </div>\n \n </form>\n \n </body>\n</html>" }, { "code": null, "e": 62876, "s": 62815, "text": "Next, we need our pair of URLs to get started: myapp/urls.py" }, { "code": null, "e": 63136, "s": 62876, "text": "from django.conf.urls import patterns, url\nfrom django.views.generic import TemplateView\n\nurlpatterns = patterns(\n 'myapp.views', url(r'^profile/',TemplateView.as_view(\n template_name = 'profile.html')), url(r'^saved/', 'SaveProfile', name = 'saved')\n)" }, { "code": null, "e": 63228, "s": 63136, "text": "When accessing \"/myapp/profile\", we will get the following profile.html template rendered βˆ’" }, { "code": null, "e": 63284, "s": 63228, "text": "And on form post, the saved template will be rendered βˆ’" }, { "code": null, "e": 63443, "s": 63284, "text": "We have a sample for image, but if you want to upload another type of file, not just image, just replace the ImageField in both Model and Form with FileField." }, { "code": null, "e": 63693, "s": 63443, "text": "So far, in our examples, we have used the Django dev web server. But this server is just for testing and is not fit for production environment. Once in production, you need a real server like Apache, Nginx, etc. Let's discuss Apache in this chapter." }, { "code": null, "e": 63929, "s": 63693, "text": "Serving Django applications via Apache is done by using mod_wsgi. So the first thing is to make sure you have Apache and mod_wsgi installed. Remember, when we created our project and we looked at the project structure, it looked like βˆ’" }, { "code": null, "e": 64032, "s": 63929, "text": "myproject/\n manage.py\n myproject/\n __init__.py\n settings.py\n urls.py\n wsgi.py\n" }, { "code": null, "e": 64111, "s": 64032, "text": "The wsgi.py file is the one taking care of the link between Django and Apache." }, { "code": null, "e": 64453, "s": 64111, "text": "Let's say we want to share our project (myproject) with Apache. We just need to set Apache to access our folder. Assume we put our myproject folder in the default \"/var/www/html\". At this stage, accessing the project will be done via 127.0.0.1/myproject. This will result in Apache just listing the folder as shown in the following snapshot." }, { "code": null, "e": 64624, "s": 64453, "text": "As seen, Apache is not handling Django stuff. For this to be taken care of, we need to configure Apache in httpd.conf. So open the httpd.conf and add the following line βˆ’" }, { "code": null, "e": 64850, "s": 64624, "text": "WSGIScriptAlias / /var/www/html/myproject/myproject/wsgi.py\nWSGIPythonPath /var/www/html/myproject/\n\n<Directory /var/www/html/myproject/>\n <Files wsgi.py>\n Order deny,allow\n Allow from all\n </Files>\n</Directory>" }, { "code": null, "e": 64955, "s": 64850, "text": "If you can access the login page as 127.0.0.1/myapp/connection, you will get to see the following page βˆ’" }, { "code": null, "e": 65250, "s": 64955, "text": "Sometimes you might want to store some data on a per-site-visitor basis as per the requirements of your web application. Always keep in mind, that cookies are saved on the client side and depending on your client browser security level, setting cookies can at times work and at times might not." }, { "code": null, "e": 65463, "s": 65250, "text": "To illustrate cookies handling in Django, let's create a system using the login system we created before. The system will keep you logged in for X minute of time, and beyond that time, you will be out of the app." }, { "code": null, "e": 65540, "s": 65463, "text": "For this, you will need to set up two cookies, last_connection and username." }, { "code": null, "e": 65630, "s": 65540, "text": "At first, let's change our login view to store our username and last_connection cookies βˆ’" }, { "code": null, "e": 66251, "s": 65630, "text": "from django.template import RequestContext\n\ndef login(request):\n username = \"not logged in\"\n \n if request.method == \"POST\":\n #Get the posted form\n MyLoginForm = LoginForm(request.POST)\n \n if MyLoginForm.is_valid():\n username = MyLoginForm.cleaned_data['username']\n else:\n MyLoginForm = LoginForm()\n \n response = render_to_response(request, 'loggedin.html', {\"username\" : username}, \n context_instance = RequestContext(request))\n \n response.set_cookie('last_connection', datetime.datetime.now())\n response.set_cookie('username', datetime.datetime.now())\n\t\n return response" }, { "code": null, "e": 66428, "s": 66251, "text": "As seen in the view above, setting cookie is done by the set_cookie method called on the response not the request, and also note that all cookies values are returned as string." }, { "code": null, "e": 66559, "s": 66428, "text": "Let’s now create a formView for the login form, where we won’t display the form if cookie is set and is not older than 10 second βˆ’" }, { "code": null, "e": 67155, "s": 66559, "text": "def formView(request):\n if 'username' in request.COOKIES and 'last_connection' in request.COOKIES:\n username = request.COOKIES['username']\n \n last_connection = request.COOKIES['last_connection']\n last_connection_time = datetime.datetime.strptime(last_connection[:-7], \n \"%Y-%m-%d %H:%M:%S\")\n \n if (datetime.datetime.now() - last_connection_time).seconds < 10:\n return render(request, 'loggedin.html', {\"username\" : username})\n else:\n return render(request, 'login.html', {})\n\t\t\t\n else:\n return render(request, 'login.html', {})" }, { "code": null, "e": 67279, "s": 67155, "text": "As you can see in the formView above accessing the cookie you set, is done via the COOKIES attribute (dict) of the request." }, { "code": null, "e": 67362, "s": 67279, "text": "Now let’s change the url.py file to change the URL so it pairs with our new view βˆ’" }, { "code": null, "e": 67591, "s": 67362, "text": "from django.conf.urls import patterns, url\nfrom django.views.generic import TemplateView\n\nurlpatterns = patterns('myapp.views',\n url(r'^connection/','formView', name = 'loginform'),\n url(r'^login/', 'login', name = 'login'))" }, { "code": null, "e": 67659, "s": 67591, "text": "When accessing /myapp/connection, you will get the following page βˆ’" }, { "code": null, "e": 67723, "s": 67659, "text": "And you will get redirected to the following screen on submit βˆ’" }, { "code": null, "e": 67953, "s": 67723, "text": "Now, if you try to access /myapp/connection again in the 10 seconds range, you will get redirected to the second screen directly. And if you access /myapp/connection again out of this range you will get the login form (screen 1)." }, { "code": null, "e": 68249, "s": 67953, "text": "As discussed earlier, we can use client side cookies to store a lot of useful data for the web app. We have seen before that we can use client side cookies to store various data useful for our web app. This leads to lot of security holes depending on the importance of the data you want to save." }, { "code": null, "e": 68605, "s": 68249, "text": "For security reasons, Django has a session framework for cookies handling. Sessions are used to abstract the receiving and sending of cookies, data is saved on server side (like in database), and the client side cookie just has a session ID for identification. Sessions are also useful to avoid cases where the user browser is set to β€˜not accept’ cookies." }, { "code": null, "e": 68863, "s": 68605, "text": "In Django, enabling session is done in your project settings.py, by adding some lines to the MIDDLEWARE_CLASSES and the INSTALLED_APPS options. This should be done while creating the project, but it's always good to know, so MIDDLEWARE_CLASSES should have βˆ’" }, { "code": null, "e": 68919, "s": 68863, "text": "'django.contrib.sessions.middleware.SessionMiddleware'\n" }, { "code": null, "e": 68952, "s": 68919, "text": "And INSTALLED_APPS should have βˆ’" }, { "code": null, "e": 68979, "s": 68952, "text": "'django.contrib.sessions'\n" }, { "code": null, "e": 69172, "s": 68979, "text": "By default, Django saves session information in database (django_session table or collection), but you can configure the engine to store information using other ways like: in file or in cache." }, { "code": null, "e": 69282, "s": 69172, "text": "When session is enabled, every request (first argument of any view in Django) has a session (dict) attribute." }, { "code": null, "e": 69706, "s": 69282, "text": "Let's create a simple sample to see how to create and save sessions. We have built a simple login system before (see Django form processing chapter and Django Cookies Handling chapter). Let us save the username in a cookie so, if not signed out, when accessing our login page you won’t see the login form. Basically, let's make our login system we used in Django Cookies handling more secure, by saving cookies server side." }, { "code": null, "e": 69791, "s": 69706, "text": "For this, first lets change our login view to save our username cookie server side βˆ’" }, { "code": null, "e": 70184, "s": 69791, "text": "def login(request):\n username = 'not logged in'\n \n if request.method == 'POST':\n MyLoginForm = LoginForm(request.POST)\n \n if MyLoginForm.is_valid():\n username = MyLoginForm.cleaned_data['username']\n request.session['username'] = username\n else:\n MyLoginForm = LoginForm()\n\t\t\t\n return render(request, 'loggedin.html', {\"username\" : username}" }, { "code": null, "e": 70288, "s": 70184, "text": "Then let us create formView view for the login form, where we won’t display the form if cookie is set βˆ’" }, { "code": null, "e": 70526, "s": 70288, "text": "def formView(request):\n if request.session.has_key('username'):\n username = request.session['username']\n return render(request, 'loggedin.html', {\"username\" : username})\n else:\n return render(request, 'login.html', {})" }, { "code": null, "e": 70610, "s": 70526, "text": "Now let us change the url.py file to change the url so it pairs with our new view βˆ’" }, { "code": null, "e": 70839, "s": 70610, "text": "from django.conf.urls import patterns, url\nfrom django.views.generic import TemplateView\n\nurlpatterns = patterns('myapp.views',\n url(r'^connection/','formView', name = 'loginform'),\n url(r'^login/', 'login', name = 'login'))" }, { "code": null, "e": 70914, "s": 70839, "text": "When accessing /myapp/connection, you will get to see the following page βˆ’" }, { "code": null, "e": 70966, "s": 70914, "text": "And you will get redirected to the following page βˆ’" }, { "code": null, "e": 71071, "s": 70966, "text": "Now if you try to access /myapp/connection again, you will get redirected to the second screen directly." }, { "code": null, "e": 71129, "s": 71071, "text": "Let's create a simple logout view that erases our cookie." }, { "code": null, "e": 71281, "s": 71129, "text": "def logout(request):\n try:\n del request.session['username']\n except:\n pass\n return HttpResponse(\"<strong>You are logged out.</strong>\")" }, { "code": null, "e": 71327, "s": 71281, "text": "And pair it with a logout URL in myapp/url.py" }, { "code": null, "e": 71373, "s": 71327, "text": "url(r'^logout/', 'logout', name = 'logout'),\n" }, { "code": null, "e": 71441, "s": 71373, "text": "Now, if you access /myapp/logout, you will get the following page βˆ’" }, { "code": null, "e": 71520, "s": 71441, "text": "If you access /myapp/connection again, you will get the login form (screen 1)." }, { "code": null, "e": 71670, "s": 71520, "text": "We have seen how to store and access a session, but it's good to know that the session attribute of the request have some other useful actions like βˆ’" }, { "code": null, "e": 71733, "s": 71670, "text": "set_expiry (value) βˆ’ Sets the expiration time for the session." }, { "code": null, "e": 71796, "s": 71733, "text": "set_expiry (value) βˆ’ Sets the expiration time for the session." }, { "code": null, "e": 71873, "s": 71796, "text": "get_expiry_age() βˆ’ Returns the number of seconds until this session expires." }, { "code": null, "e": 71950, "s": 71873, "text": "get_expiry_age() βˆ’ Returns the number of seconds until this session expires." }, { "code": null, "e": 72013, "s": 71950, "text": "get_expiry_date() βˆ’ Returns the date this session will expire." }, { "code": null, "e": 72076, "s": 72013, "text": "get_expiry_date() βˆ’ Returns the date this session will expire." }, { "code": null, "e": 72143, "s": 72076, "text": "clear_expired() βˆ’ Removes expired sessions from the session store." }, { "code": null, "e": 72210, "s": 72143, "text": "clear_expired() βˆ’ Removes expired sessions from the session store." }, { "code": null, "e": 72372, "s": 72210, "text": "get_expire_at_browser_close() βˆ’ Returns either True or False, depending on whether the user’s session cookies have expired when the user’s web browser is closed." }, { "code": null, "e": 72534, "s": 72372, "text": "get_expire_at_browser_close() βˆ’ Returns either True or False, depending on whether the user’s session cookies have expired when the user’s web browser is closed." }, { "code": null, "e": 72721, "s": 72534, "text": "To cache something is to save the result of an expensive calculation, so that you don’t perform it the next time you need it. Following is a pseudo code that explains how caching works βˆ’" }, { "code": null, "e": 72937, "s": 72721, "text": "given a URL, try finding that page in the cache\n\nif the page is in the cache:\n return the cached page\nelse:\n generate the page\n save the generated page in the cache (for next time)\n return the generated page" }, { "code": null, "e": 73127, "s": 72937, "text": "Django comes with its own caching system that lets you save your dynamic pages, to avoid calculating them again when needed. The good point in Django Cache framework is that you can cache βˆ’" }, { "code": null, "e": 73158, "s": 73127, "text": "The output of a specific view." }, { "code": null, "e": 73180, "s": 73158, "text": "A part of a template." }, { "code": null, "e": 73198, "s": 73180, "text": "Your entire site." }, { "code": null, "e": 73460, "s": 73198, "text": "To use cache in Django, first thing to do is to set up where the cache will stay. The cache framework offers different possibilities - cache can be saved in database, on file system or directly in memory. Setting is done in the settings.py file of your project." }, { "code": null, "e": 73517, "s": 73460, "text": "Just add the following in the project settings.py file βˆ’" }, { "code": null, "e": 73650, "s": 73517, "text": "CACHES = {\n 'default': {\n 'BACKEND': 'django.core.cache.backends.db.DatabaseCache',\n 'LOCATION': 'my_table_name',\n }\n}" }, { "code": null, "e": 73788, "s": 73650, "text": "For this to work and to complete the setting, we need to create the cache table 'my_table_name'. For this, you need to do the following βˆ’" }, { "code": null, "e": 73823, "s": 73788, "text": "python manage.py createcachetable\n" }, { "code": null, "e": 73880, "s": 73823, "text": "Just add the following in the project settings.py file βˆ’" }, { "code": null, "e": 74029, "s": 73880, "text": "CACHES = {\n 'default': {\n 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',\n 'LOCATION': '/var/tmp/django_cache',\n }\n}" }, { "code": null, "e": 74197, "s": 74029, "text": "This is the most efficient way of caching, to use it you can use one of the following options depending on the Python binding library you choose for the memory cache βˆ’" }, { "code": null, "e": 74340, "s": 74197, "text": "CACHES = {\n 'default': {\n 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',\n 'LOCATION': '127.0.0.1:11211',\n }\n}" }, { "code": null, "e": 74343, "s": 74340, "text": "Or" }, { "code": null, "e": 74495, "s": 74343, "text": "CACHES = {\n 'default': {\n 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',\n 'LOCATION': 'unix:/tmp/memcached.sock',\n }\n}" }, { "code": null, "e": 74695, "s": 74495, "text": "The simplest way of using cache in Django is to cache the entire site. This is done by editing the MIDDLEWARE_CLASSES option in the project settings.py. The following need to be added to the option βˆ’" }, { "code": null, "e": 74876, "s": 74695, "text": "MIDDLEWARE_CLASSES += (\n 'django.middleware.cache.UpdateCacheMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.cache.FetchFromCacheMiddleware',\n)" }, { "code": null, "e": 74959, "s": 74876, "text": "Note that the order is important here, Update should come before Fetch middleware." }, { "code": null, "e": 75000, "s": 74959, "text": "Then in the same file, you need to set βˆ’" }, { "code": null, "e": 75139, "s": 75000, "text": "CACHE_MIDDLEWARE_ALIAS – The cache alias to use for storage.\nCACHE_MIDDLEWARE_SECONDS – The number of seconds each page should be cached.\n" }, { "code": null, "e": 75350, "s": 75139, "text": "If you don’t want to cache the entire site you can cache a specific view. This is done by using the cache_page decorator that comes with Django. Let us say we want to cache the result of the viewArticles view βˆ’" }, { "code": null, "e": 75552, "s": 75350, "text": "from django.views.decorators.cache import cache_page\n\n@cache_page(60 * 15)\n\ndef viewArticles(request, year, month):\n text = \"Displaying articles of : %s/%s\"%(year, month)\n return HttpResponse(text)" }, { "code": null, "e": 75722, "s": 75552, "text": "As you can see cache_page takes the number of seconds you want the view result to be cached as parameter. In our example above, the result will be cached for 15 minutes." }, { "code": null, "e": 75780, "s": 75722, "text": "Note βˆ’ As we have seen before the above view was map to βˆ’" }, { "code": null, "e": 75910, "s": 75780, "text": "urlpatterns = patterns('myapp.views',\n url(r'^articles/(?P<month>\\d{2})/(?P<year>\\d{4})/', 'viewArticles', name = 'articles'),)" }, { "code": null, "e": 76095, "s": 75910, "text": "Since the URL is taking parameters, each different call will be cached separately. For example, request to /myapp/articles/02/2007 will be cached separately to /myapp/articles/03/2008." }, { "code": null, "e": 76292, "s": 76095, "text": "Caching a view can also directly be done in the url.py file. Then the following has the same result as the above. Just edit your myapp/url.py file and change the related mapped URL (above) to be βˆ’" }, { "code": null, "e": 76447, "s": 76292, "text": "urlpatterns = patterns('myapp.views',\n url(r'^articles/(?P<month>\\d{2})/(?P<year>\\d{4})/', \n cache_page(60 * 15)('viewArticles'), name = 'articles'),)" }, { "code": null, "e": 76504, "s": 76447, "text": "And, of course, it's no longer needed in myapp/views.py." }, { "code": null, "e": 76618, "s": 76504, "text": "You can also cache parts of a template, this is done by using the cache tag. Let's take our hello.html template βˆ’" }, { "code": null, "e": 76985, "s": 76618, "text": "{% extends \"main_template.html\" %}\n{% block title %}My Hello Page{% endblock %}\n{% block content %}\n\nHello World!!!<p>Today is {{today}}</p>\nWe are\n{% if today.day == 1 %}\n\nthe first day of month.\n{% elif today.day == 30 %}\n\nthe last day of month.\n{% else %}\n\nI don't know.\n{%endif%}\n\n<p>\n {% for day in days_of_week %}\n {{day}}\n</p>\n\n{% endfor %}\n{% endblock %}" }, { "code": null, "e": 77044, "s": 76985, "text": "And to cache the content block, our template will become βˆ’" }, { "code": null, "e": 77467, "s": 77044, "text": "{% load cache %}\n{% extends \"main_template.html\" %}\n{% block title %}My Hello Page{% endblock %}\n{% cache 500 content %}\n{% block content %}\n\nHello World!!!<p>Today is {{today}}</p>\nWe are\n{% if today.day == 1 %}\n\nthe first day of month.\n{% elif today.day == 30 %}\n\nthe last day of month.\n{% else %}\n\nI don't know.\n{%endif%}\n\n<p>\n {% for day in days_of_week %}\n {{day}}\n</p>\n\n{% endfor %}\n{% endblock %}\n{% endcache %}" }, { "code": null, "e": 77630, "s": 77467, "text": "As you can see above, the cache tag will take 2 parameters βˆ’ the time you want the block to be cached (in seconds) and the name to be given to the cache fragment." }, { "code": null, "e": 77944, "s": 77630, "text": "Before starting, note that the Django Comments framework is deprecated, since the 1.5 version. Now you can use external feature for doing so, but if you still want to use it, it's still included in version 1.6 and 1.7. Starting version 1.8 it's absent but you can still get the code on a different GitHub account." }, { "code": null, "e": 78026, "s": 77944, "text": "The comments framework makes it easy to attach comments to any model in your app." }, { "code": null, "e": 78073, "s": 78026, "text": "To start using the Django comments framework βˆ’" }, { "code": null, "e": 78197, "s": 78073, "text": "Edit the project settings.py file and add 'django.contrib.sites', and 'django.contrib.comments', to INSTALLED_APPS option βˆ’" }, { "code": null, "e": 78268, "s": 78197, "text": "INSTALLED_APPS += ('django.contrib.sites', 'django.contrib.comments',)" }, { "code": null, "e": 78286, "s": 78268, "text": "Get the site id βˆ’" }, { "code": null, "e": 78410, "s": 78286, "text": ">>> from django.contrib.sites.models import Site\n>>> Site().save()\n>>> Site.objects.all()[0].id\nu'56194498e13823167dd43c64'" }, { "code": null, "e": 78455, "s": 78410, "text": "Set the id you get in the settings.py file βˆ’" }, { "code": null, "e": 78494, "s": 78455, "text": "SITE_ID = u'56194498e13823167dd43c64'\n" }, { "code": null, "e": 78552, "s": 78494, "text": "Sync db, to create all the comments table or collection βˆ’" }, { "code": null, "e": 78577, "s": 78552, "text": "python manage.py syncdb\n" }, { "code": null, "e": 78632, "s": 78577, "text": "Add the comment app’s URLs to your project’s urls.py βˆ’" }, { "code": null, "e": 78730, "s": 78632, "text": "from django.conf.urls import include\nurl(r'^comments/', include('django.contrib.comments.urls'))," }, { "code": null, "e": 78971, "s": 78730, "text": "Now that we have the framework installed, let's change our hello templates to tracks comments on our Dreamreal model. We will list, save comments for a specific Dreamreal entry whose name will be passed as parameter to the /myapp/hello URL." }, { "code": null, "e": 79222, "s": 78971, "text": "class Dreamreal(models.Model):\n\n website = models.CharField(max_length = 50)\n mail = models.CharField(max_length = 50)\n name = models.CharField(max_length = 50)\n phonenumber = models.IntegerField()\n\n class Meta:\n db_table = \"dreamreal\"" }, { "code": null, "e": 79456, "s": 79222, "text": "def hello(request, Name):\n today = datetime.datetime.now().date()\n daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']\n dreamreal = Dreamreal.objects.get(name = Name)\n return render(request, 'hello.html', locals())" }, { "code": null, "e": 80037, "s": 79456, "text": "{% extends \"main_template.html\" %}\n{% load comments %}\n{% block title %}My Hello Page{% endblock %}\n{% block content %}\n\n<p>\n Our Dreamreal Entry:\n <p><strong>Name :</strong> {{dreamreal.name}}</p>\n <p><strong>Website :</strong> {{dreamreal.website}}</p>\n <p><strong>Phone :</strong> {{dreamreal.phonenumber}}</p>\n <p><strong>Number of comments :<strong> \n {% get_comment_count for dreamreal as comment_count %} {{ comment_count }}</p>\n <p>List of comments :</p>\n {% render_comment_list for dreamreal %}\n</p>\n\n{% render_comment_form for dreamreal %}\n{% endblock %}" }, { "code": null, "e": 80081, "s": 80037, "text": "Finally the mapping URL to our hello view βˆ’" }, { "code": null, "e": 80138, "s": 80081, "text": "url(r'^hello/(?P<Name>\\w+)/', 'hello', name = 'hello'),\n" }, { "code": null, "e": 80143, "s": 80138, "text": "Now," }, { "code": null, "e": 80228, "s": 80143, "text": "In our template (hello.html), load the comments framework with βˆ’ {% load comments %}" }, { "code": null, "e": 80313, "s": 80228, "text": "In our template (hello.html), load the comments framework with βˆ’ {% load comments %}" }, { "code": null, "e": 80442, "s": 80313, "text": "We get the number of comments for the Dreamreal object pass by the view βˆ’ {% get_comment_count for dreamreal as comment_count %}" }, { "code": null, "e": 80571, "s": 80442, "text": "We get the number of comments for the Dreamreal object pass by the view βˆ’ {% get_comment_count for dreamreal as comment_count %}" }, { "code": null, "e": 80657, "s": 80571, "text": "We get the list of comments for the objects βˆ’ {% render_comment_list for dreamreal %}" }, { "code": null, "e": 80743, "s": 80657, "text": "We get the list of comments for the objects βˆ’ {% render_comment_list for dreamreal %}" }, { "code": null, "e": 80822, "s": 80743, "text": "We display the default comments form βˆ’ {% render_comment_form for dreamreal %}" }, { "code": null, "e": 80901, "s": 80822, "text": "We display the default comments form βˆ’ {% render_comment_form for dreamreal %}" }, { "code": null, "e": 81045, "s": 80901, "text": "When accessing /myapp/hello/steve you will get the comments info for the Dreamreal entry whose name is Steve. Accessing that URL will get you βˆ’" }, { "code": null, "e": 81115, "s": 81045, "text": "On posting a comment, you will get redirected to the following page βˆ’" }, { "code": null, "e": 81195, "s": 81115, "text": "If you go to /myapp/hello/steve again, you will get to see the following page βˆ’" }, { "code": null, "e": 81301, "s": 81195, "text": "As you can see, the number of comments is 1 now and you have the comment under the list of comments line." }, { "code": null, "e": 81466, "s": 81301, "text": "Django comes with a syndication feed generating framework. With it you can create RSS or Atom feeds just by subclassing django.contrib.syndication.views.Feed class." }, { "code": null, "e": 81709, "s": 81466, "text": "Let's create a feed for the latest comments done on the app (Also see Django - Comments Framework chapter). For this, let's create a myapp/feeds.py and define our feed (You can put your feeds classes anywhere you want in your code structure)." }, { "code": null, "e": 82316, "s": 81709, "text": "from django.contrib.syndication.views import Feed\nfrom django.contrib.comments import Comment\nfrom django.core.urlresolvers import reverse\n\nclass DreamrealCommentsFeed(Feed):\n title = \"Dreamreal's comments\"\n link = \"/drcomments/\"\n description = \"Updates on new comments on Dreamreal entry.\"\n\n def items(self):\n return Comment.objects.all().order_by(\"-submit_date\")[:5]\n\t\t\n def item_title(self, item):\n return item.user_name\n\t\t\n def item_description(self, item):\n return item.comment\n\t\t\n def item_link(self, item):\n return reverse('comment', kwargs = {'object_pk':item.pk})" }, { "code": null, "e": 82450, "s": 82316, "text": "In our feed class, title, link, and description attributes correspond to the standard RSS <title>, <link> and <description> elements." }, { "code": null, "e": 82584, "s": 82450, "text": "In our feed class, title, link, and description attributes correspond to the standard RSS <title>, <link> and <description> elements." }, { "code": null, "e": 82702, "s": 82584, "text": "The items method, return the elements that should go in the feed as item element. In our case the last five comments." }, { "code": null, "e": 82820, "s": 82702, "text": "The items method, return the elements that should go in the feed as item element. In our case the last five comments." }, { "code": null, "e": 82939, "s": 82820, "text": "The item_title method, will get what will go as title for our feed item. In our case the title, will be the user name." }, { "code": null, "e": 83058, "s": 82939, "text": "The item_title method, will get what will go as title for our feed item. In our case the title, will be the user name." }, { "code": null, "e": 83175, "s": 83058, "text": "The item_description method, will get what will go as description for our feed item. In our case the comment itself." }, { "code": null, "e": 83292, "s": 83175, "text": "The item_description method, will get what will go as description for our feed item. In our case the comment itself." }, { "code": null, "e": 83395, "s": 83292, "text": "The item_link method will build the link to the full item. In our case it will get you to the comment." }, { "code": null, "e": 83498, "s": 83395, "text": "The item_link method will build the link to the full item. In our case it will get you to the comment." }, { "code": null, "e": 83587, "s": 83498, "text": "Now that we have our feed, let's add a comment view in views.py to display our comment βˆ’" }, { "code": null, "e": 83888, "s": 83587, "text": "from django.contrib.comments import Comment\n\ndef comment(request, object_pk):\n mycomment = Comment.objects.get(object_pk = object_pk)\n text = '<strong>User :</strong> %s <p>'%mycomment.user_name</p>\n text += '<strong>Comment :</strong> %s <p>'%mycomment.comment</p>\n return HttpResponse(text)" }, { "code": null, "e": 83946, "s": 83888, "text": "We also need some URLs in our myapp urls.py for mapping βˆ’" }, { "code": null, "e": 84180, "s": 83946, "text": "from myapp.feeds import DreamrealCommentsFeed\nfrom django.conf.urls import patterns, url\n\nurlpatterns += patterns('',\n url(r'^latest/comments/', DreamrealCommentsFeed()),\n url(r'^comment/(?P\\w+)/', 'comment', name = 'comment'),\n)" }, { "code": null, "e": 84243, "s": 84180, "text": "When accessing /myapp/latest/comments/ you will get our feed βˆ’" }, { "code": null, "e": 84381, "s": 84243, "text": "Then clicking on one of the usernames will get you to: /myapp/comment/comment_id as defined in our comment view before and you will get βˆ’" }, { "code": null, "e": 84626, "s": 84381, "text": "Thus, defining a RSS feed is just a matter of sub-classing the Feed class and making sure the URLs (one for accessing the feed and one for accessing the feed elements) are defined. Just as comment, this can be attached to any model in your app." }, { "code": null, "e": 85103, "s": 84626, "text": "Ajax essentially is a combination of technologies that are integrated together to reduce the number of page loads. We generally use Ajax to ease end-user experience. Using Ajax in Django can be done by directly using an Ajax library like JQuery or others. Let's say you want to use JQuery, then you need to download and serve the library on your server through Apache or others. Then use it in your template, just like you might do while developing any Ajax-based application." }, { "code": null, "e": 85472, "s": 85103, "text": "Another way of using Ajax in Django is to use the Django Ajax framework. The most commonly used is django-dajax which is a powerful tool to easily and super-quickly develop asynchronous presentation logic in web applications, using Python and almost no JavaScript source code. It supports four of the most popular Ajax frameworks: Prototype, jQuery, Dojo and MooTools." }, { "code": null, "e": 85563, "s": 85472, "text": "First thing to do is to install django-dajax. This can be done using easy_install or pip βˆ’" }, { "code": null, "e": 85619, "s": 85563, "text": "$ pip install django_dajax\n$ easy_install django_dajax\n" }, { "code": null, "e": 85745, "s": 85619, "text": "This will automatically install django-dajaxice, required by django-dajax. We then need to configure both dajax and dajaxice." }, { "code": null, "e": 85823, "s": 85745, "text": "Add dajax and dajaxice in your project settings.py in INSTALLED_APPS option βˆ’" }, { "code": null, "e": 85871, "s": 85823, "text": "INSTALLED_APPS += (\n 'dajaxice',\n 'dajax'\n)" }, { "code": null, "e": 85936, "s": 85871, "text": "Make sure in the same settings.py file, you have the following βˆ’" }, { "code": null, "e": 86682, "s": 85936, "text": "TEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n 'django.template.loaders.eggs.Loader',\n)\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n 'django.contrib.auth.context_processors.auth',\n 'django.core.context_processors.debug',\n 'django.core.context_processors.i18n',\n 'django.core.context_processors.media',\n 'django.core.context_processors.static',\n 'django.core.context_processors.request',\n 'django.contrib.messages.context_processors.messages'\n)\n\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n 'dajaxice.finders.DajaxiceFinder',\n)\n\nDAJAXICE_MEDIA_PREFIX = 'dajaxice'" }, { "code": null, "e": 86806, "s": 86682, "text": "Now go to the myapp/url.py file and make sure you have the following to set dajax URLs and to load dajax statics js files βˆ’" }, { "code": null, "e": 87139, "s": 86806, "text": "from dajaxice.core import dajaxice_autodiscover, dajaxice_config\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\nfrom django.conf import settings\n\nThen dajax urls:\n\nurlpatterns += patterns('',\n url(r'^%s/' % settings.DAJAXICE_MEDIA_PREFIX, include('dajaxice.urls')),)\n\t\nurlpatterns += staticfiles_urlpatterns()" }, { "code": null, "e": 87240, "s": 87139, "text": "Let us create a simple form based on our Dreamreal model to store it, using Ajax (means no refresh)." }, { "code": null, "e": 87295, "s": 87240, "text": "At first, we need our Dreamreal form in myapp/form.py." }, { "code": null, "e": 87514, "s": 87295, "text": "class DreamrealForm(forms.Form):\n website = forms.CharField(max_length = 100)\n name = forms.CharField(max_length = 100)\n phonenumber = forms.CharField(max_length = 50)\n email = forms.CharField(max_length = 100)" }, { "code": null, "e": 87691, "s": 87514, "text": "Then we need an ajax.py file in our application: myapp/ajax.py. That's where is our logic, that's where we put the function that will be saving our form then return the popup βˆ’" }, { "code": null, "e": 88526, "s": 87691, "text": "from dajaxice.utils import deserialize_form\nfrom myapp.form import DreamrealForm\nfrom dajax.core import Dajax\nfrom myapp.models import Dreamreal\n\n@dajaxice_register\ndef send_form(request, form):\n dajax = Dajax()\n form = DreamrealForm(deserialize_form(form))\n \n if form.is_valid():\n dajax.remove_css_class('#my_form input', 'error')\n dr = Dreamreal()\n dr.website = form.cleaned_data.get('website')\n dr.name = form.cleaned_data.get('name')\n dr.phonenumber = form.cleaned_data.get('phonenumber')\n dr.save()\n \n dajax.alert(\"Dreamreal Entry %s was successfully saved.\" % \n form.cleaned_data.get('name'))\n else:\n dajax.remove_css_class('#my_form input', 'error')\n for error in form.errors:\n dajax.add_css_class('#id_%s' % error, 'error')\n\t\t\t\n return dajax.json()" }, { "code": null, "e": 88593, "s": 88526, "text": "Now let's create the dreamreal.html template, which has our form βˆ’" }, { "code": null, "e": 88857, "s": 88593, "text": "<html>\n <head></head>\n <body>\n \n <form action = \"\" method = \"post\" id = \"my_form\" accept-charset = \"utf-8\">\n {{ form.as_p }}\n <p><input type = \"button\" value = \"Send\" onclick = \"send_form();\"></p>\n </form>\n \n </body>\n</html>" }, { "code": null, "e": 88918, "s": 88857, "text": "Add the view that goes with the template in myapp/views.py βˆ’" }, { "code": null, "e": 89022, "s": 88918, "text": "def dreamreal(request):\n form = DreamrealForm()\n return render(request, 'dreamreal.html', locals())" }, { "code": null, "e": 89067, "s": 89022, "text": "Add the corresponding URL in myapp/urls.py βˆ’" }, { "code": null, "e": 89122, "s": 89067, "text": "url(r'^dreamreal/', 'dreamreal', name = 'dreamreal'),\n" }, { "code": null, "e": 89190, "s": 89122, "text": "Now let's add the necessary in our template to make the Ajax work βˆ’" }, { "code": null, "e": 89219, "s": 89190, "text": "At the top of the file add βˆ’" }, { "code": null, "e": 89270, "s": 89219, "text": "{% load static %}\n{% load dajaxice_templatetags %}" }, { "code": null, "e": 89333, "s": 89270, "text": "And in the <head> section of our dreamreal.html template add βˆ’" }, { "code": null, "e": 89392, "s": 89333, "text": "We are using the JQuery library for this example, so add βˆ’" }, { "code": null, "e": 89585, "s": 89392, "text": "<script src = \"{% static '/static/jquery-1.11.3.min.js' %}\" \n type = \"text/javascript\" charset = \"utf-8\"></script>\n<script src = \"{% static '/static/dajax/jquery.dajax.core.js' %}\"></script>" }, { "code": null, "e": 89634, "s": 89585, "text": "The Ajax function that will be called on click βˆ’" }, { "code": null, "e": 89770, "s": 89634, "text": "<script>\n\n function send_form(){\n Dajaxice.myapp.send_form(Dajax.process,{'form':$('#my_form').serialize(true)});\n }\n</script>" }, { "code": null, "e": 89965, "s": 89770, "text": "Note that you need the β€œjquery-1.11.3.min.js” in your static files directory, and also the jquery.dajax.core.js. To make sure all dajax static files are served under your static directory, run βˆ’" }, { "code": null, "e": 89998, "s": 89965, "text": "$python manage.py collectstatic\n" }, { "code": null, "e": 90154, "s": 89998, "text": "Note βˆ’ Sometimes the jquery.dajax.core.js can be missing, if that happens, just download the source and take that file and put it under your static folder." }, { "code": null, "e": 90231, "s": 90154, "text": "You will get to see the following screen, upon accessing /myapp/dreamreal/ βˆ’" }, { "code": null, "e": 90278, "s": 90231, "text": "On submit, you will get the following screen βˆ’" }, { "code": null, "e": 90313, "s": 90278, "text": "\n 39 Lectures \n 3.5 hours \n" }, { "code": null, "e": 90325, "s": 90313, "text": " John Elder" }, { "code": null, "e": 90360, "s": 90325, "text": "\n 36 Lectures \n 2.5 hours \n" }, { "code": null, "e": 90372, "s": 90360, "text": " John Elder" }, { "code": null, "e": 90405, "s": 90372, "text": "\n 28 Lectures \n 2 hours \n" }, { "code": null, "e": 90417, "s": 90405, "text": " John Elder" }, { "code": null, "e": 90450, "s": 90417, "text": "\n 20 Lectures \n 1 hours \n" }, { "code": null, "e": 90462, "s": 90450, "text": " John Elder" }, { "code": null, "e": 90495, "s": 90462, "text": "\n 35 Lectures \n 3 hours \n" }, { "code": null, "e": 90507, "s": 90495, "text": " John Elder" }, { "code": null, "e": 90541, "s": 90507, "text": "\n 79 Lectures \n 10 hours \n" }, { "code": null, "e": 90555, "s": 90541, "text": " Rathan Kumar" }, { "code": null, "e": 90562, "s": 90555, "text": " Print" }, { "code": null, "e": 90573, "s": 90562, "text": " Add Notes" } ]
Functions with R and rvest: A Laymen’s Guide | by peterjgensler | Towards Data Science
If there had to be one topic that was so hard to comprehend after using R, it has to be functions. Everything from writing a function, to learning how to debug a function has just never had some clear instructions on how to do so. In addition, there are tools that have come out that are meant to help with this task, but can seem rather hard to understand how to utilize when solving your problem. This blog intends to get you up and running with what functions are in R, how to utilize them for tasks, and easily debug them inside RStudio to troubleshoot what is exactly going on. Recently I had the opportunity of going to a Cider Festival, to learn and try new ciders.I’m not the biggest fan of cider’s, so naturally I opted to try almost every beer that was available, and wanted to compare what I tasted. If anyone were to ask about my taste buds, it would be that I love shandy’s, and wheat beer. None of the beer’s I tried were even remotely close to my liking, yet somehow tasted much better than I anticipated. It sure would be helpful to have a way to compare the beer’s I’ve tried to see just why I enjoyed an American Pale ale, and even a cask. Using rvest, we can easily scrape the necessary data about each beer from RateBeer to help compare them against each other to determine what similarities they may share. Before we get started, a few ground rules need to be established so that you get yourself on the right track for the task at hand. Interacting with the web via programming can very easily feel like uncharted terriority at first, almost like drinking your first beer: Where am I, and how did I end up here?But, fear not, as this blog will provide you the resources to not get lost navigating this abyss. In order to gain the most value from what is outlined within this blog, you will need the following tools: RStudio Visual Studio Code GitKraken Why do we need these you might ask? Equipping yourself with the right tools can sometimes be half the battle with r: it’s hard to figure out how to understand the problem at hand if you don’t have the necessary tools to solve the problem. In addition to these tools, I would strongly encourage you to think about using a sandbox environment, using Docker or RStudio Cloud, as R has had some pain points with encodings on different operating systems. If you would like more information on how to create your own custom sandbox environment for R, you can check out this blog for more information, or check out RStudio Cloud. https://medium.com/@peterjgensler/creating-sandbox-environments-for-r-with-docker-def54e3491a3 https://rstudio.cloud/ At a high level, there are two generic ways of obtaining data on the web: API’s β€” API is called Application Programming Interface Web Scraping- more of a brute-force approach Ok, so what exactly is an API, then? Should I be using it? β€œAn API is a messenger that takes requests, and then returns a response back to you” API’s are setup so you can easily interact with services. Let’s say I want to pull data on Fires in Minneapolis. data.world If I wanted, I could easily pull this data via data.world’s API: apidocs.data.world Web scraping, on the other hand is a much more brute-force way of obtaining data on the web. Not all sites have API’s to use, which means that it may be necessary to scrape to find. How would we go about checking if we can scrape a webpage? Simple, check the robots.txt file. Check out this video for more information on what a robots.txt file is used for: For our case, we are using the site RateBeer, so let’s look at their file to see if there are restrictions: https://www.ratebeer.com/robots.txt User-agent: Mediapartners-GoogleDisallow:User-agent: *Allow: / Looking at RateBeer’s robots.txt file, we can see that they allow scraping, as they disallow nothing, so we are OK to proceed. Grab a sandwich, get some coffee, and go watch this webinar from RStudio listed below. RStudio has two great webinars that cover API’s, and web-scraping in depth, we want part 2: www.rstudio.com The slides for the webinar can be found here: https://github.com/rstudio/webinars/blob/master/32-Web-Scraping/02-Web-Scraping.pdf After I watched the webinar listed above, I was so lost on all these topics, and rightfully so. Learning about the web technologies used to engineer websites is not a small task, and can be very hard when first getting started. If you want further resources to look to, I would strongly encourage you to view these slides from useR 2016 which are very similar, and do a good job of the getting the lay of the land: https://github.com/ropensci/user2016-tutorial/blob/master/03-scraping-data-without-an-api.pdf Most packages developed for web scraping with R are meant for scraping either HTML or CSS parts of a webpage, not Javascript content, which is rendered in the browser. Javascript is much more complex to scrape, and can be done with RSelenium, but is not for the faint of heart: github.com To get our data to work with, we first need to set up some functions to acquire our variables for each beer. Now, I have only picked three beers to keep this simple, but I hope this example illustrates how powerful a function can be when put to use. Lets take a look: In order to compare each beer, we first need to find a way to get attributes about each beer. Ratebeer provides us with basic statistics about each beer: As you can see above, we are interested in taking the descriptive statistics about each beer, but how would we go about finding what exactly links to that element? As there is no JavaScript on these webpages about each Beer, we can simply utilize tools to find the respective CSS or Xpath to the element we are interested in. The easiest way of going about this is Now, in order to pull the data from the website, we first need to download the webpage, and then attempt to select the element we are interested in via a CSS tag or an xpath to the element we are interested in.Unquestionably, this can be an excruciating process for two reasons: CSS tags should(but do not) work with rvest due to selectr having some issues(which drives finding the CSS tags): https://github.com/sjp/selectr/issues/7#issuecomment-344230855 Or, you have no idea if the path selected was the correct path for the element you want, which is more common than I’d like to admit Now, at first, this seems like an almost impossible task, but fear not. We can still use an xpath to select what we are interested in extracting for further use. Two tools are very useful for finding the correct xpath for the element that you wish to pull: Selectorgadget and the chrome developer tools. Selectorgadget is a point-and-click CSS selector, specifically for Chrome. Simply install the chrome extension, and then click on the elements you are interested it. This will select all elements that are related to that object.Next, select anything in yellow you do not want. There you go! More information on SelectorGadget can be found here: selectorgadget.com You can also find a well detailed walkthrough here if you need an additional example: cran.r-project.org If you have issues getting the correct xpath from SelectorGadget, you can also try using the Chrome developer tools, which are very user friendly. Simply click on View-Developer Tools, which will load up the developer tools. Next, click on the little mouse button to interact with the webpage. This will enable your cursor to show you what code is driving each element on the page. In the below screenshot, we can see that what we select with our mouse, and the respective code which is driving that particular element. Click on the blue area above, as indicated above. In this case, we are interested in the stats container, as it contains the metrics that we want to compare. This will lock you on that element so your cursor does not try to select HTML or CSS for other elements. Now right click on the area in the html code highlighted(red box), and then select copy->Copy XPath. This will allow you to get down to the most specific path for where that particular element lives on the page. Perfect! Now that we have the xpath for the element we can begin to start writing our function to extract data from the xpath. Let’s recap up to this point what we have accomplished. Up to this point, we first identified what exactly we wanted to accomplish: scrape basic statistics about each beer. We then found the necessary xpath, which identifies the element on the webpage we are interested in. Using rvest, we can write a script which allows us to Outlined in the slides from RStudio(links at the beginning of the talk), there are three β€œcore activities” that we need to accomplish for a given webpage in our function. Thinking about it, they make sense: Pull down a webpage Identify elements we want Extract & pull the element out Tidy up the element to make it useable There are three functions from the rvest package which allow us to perform these steps with ease. However, as we want to perform these steps on multiple URL’s we can set up our function like so: library(magrittr) #for pipeslibrary(dplyr) #for pull functionlibrary(rvest) #get html nodeslibrary(xml2) #pull html datalibrary(selectr) #for xpath elementlibrary(tibble)library(purrr) #for map functionslibrary(datapasta) #for recreating tibble's with ease#Sample Datasample_data <- tibble::tibble( name = c("pollyanna-eleanor-with-vanilla-beans","brickstone-apa","penrose-taproom-ipa","revolution-rev-pils"), link = c("https://www.ratebeer.com/beer/pollyanna-eleanor-with-vanilla-beans/390639/", "https://www.ratebeer.com/beer/brickstone-apa/99472/", "https://www.ratebeer.com/beer/penrose-taproom-ipa/361258/", "https://www.ratebeer.com/beer/revolution-rev-pils/360716/" ))#the function:get_beer_stats1 <- function(x){ read_html(x) %>% html_nodes(xpath = '//*[@id="container"]/div[2]/div[2]/div[2]') %>% html_text()} We could also write our function to be more explicit on when values change, making it easier to step through and debug in RStudio: get_beer_stats2 <- function(x){ url <- read_html(x) html_doc <- html_nodes(url, xpath = '//*[@id="container"]/div[2]/div[2]/div[2]') stats <- html_text(html_doc) return(stats)} Hold up, I thought we were supposed to make sure every action is precisely logged so them computer understands it? Don’t we need some sort of for-loop, that acts as a counter to increase after each URL? Why didn’t we use the dplyr::pull command to literally pull the vector out of the dataframe to iterate on first? One of the issues of working with purrr is understand how to think about the problem you are facing in the right mindset. Thinking about the problem, we can approach it from the following angles: I have a dataframe of URL’s, and I want to iterate over each row(or URL), and perform a given set of actions for each URL I have a dataframe with a column of URL’s and for each URL, I want to operate on each URL Treating my column of URL’s in my dataframe as a vector, I want to operate on each element in the vector You see, purr’s main workhorse function map, is designed to iterate over objects which contain a bunch of elements, which then allow you as the user to focus on writing a function that does some action. In R, most times these objects are either lists, list-columns, or simply a vector. In doing this, it allows you to have a workflow as such: Determine what you would like to do for a given element Turn that β€œrecipie” into a function Apply the recipe with purr over the object (and if necessary, create a new column to store the results in) Ok, now let’s apply the function we just created to our data, and see if it works: sample_data_rev <- sample_data %>% mutate(., beer_stats = map_chr(.x = link, .f = get_beer_stats1)) Before we move on, lets break down what is exactly happening. First, we pipe in the dataframe, and say we want to add a new column with mutate. Next, we create a new column defined as a character column using map_chr (or vector), and then apply our custom function. Now that our core function is defined, we can use RStudio to walk through our function if we wanted to see how values are changing. Simply enable debug mode by going to: Debug->On Error-> Error Inspector Next, simply wrap your function with debug like: debug(get_beer_stats1 <- function(x){ read_html(x) %>% html_nodes(xpath = '//*[@id="container"]/div[2]/div[2]/div[2]') %>% html_text()}) When you run your code that calls your function, you will enter into debug mode so you can view how values change in the code: sample_data_rev <- sample_data %>% mutate(., beer_stats = map_chr(.x = link, .f = get_beer_stats1)) Expanding on our example, lets say that we have URL’s that may cause some hiccups. How would we make an function which could hand these errors with ease? purr equips us with error handling functions to wrap our function in to gracefully handle errors. We can add error handling using the possibly function: sample_data_rev <- sample_data %>% mutate(., beer_stats = map_chr(.x = link, possibly(get_beer_stats1, otherwise= "NULL"))) Possibly is very similar to a try-catch, which allows us to wrap our created function with a different function for error handling. This can be a bit confusing at first glance, but makes sense once you have it setup properly. Before we move further, it may be worth noting that the following is what I will call β€œthe Abyss”, or Mordor. Beware that this is not for the faint of heart, so if you feel that you are ready, then proceed. Otherwise, go make a sandwich, and take a nap. For me, encoding in R has really reminded me of Mordor from Lord of the Rings. It just seems like some never ending pit that is almost near-death. Not to worry though, you are in good hands. Let’s go. So we have our data, and it should be all set for cleanup, right? Nope. Why is this the case? Earlier we mentioned that our workflow consisted of the following steps: Pull down a webpage Identify elements we want Extract & pull the element out Tidy up the element to make it useable Part of the issue with this workflow is that it assumes once we pull out the data from the webpage, it should be β€˜ready to go, right off the boat’, which unfortunately, is not the case with data from the web. You see, data from the web has to be encoded, and finding or even detecting encoding issues can be a real hassle, as you may not find out until much further downstream in your analysis process, like I did. Before we step in any further, I would encourage you to first read the following articles. This will help lay the foundation for understanding what exactly is wrong with our text data, and strategies to help detect the culprit: www.w3.org r4ds.had.co.nz To re-iterate, our computer (or machine, really), stores data in terms of bytes. These bytes are then encoded into different locales, such as UTF-8, or ANSI. Depending on how you have your platform(or machine’s) native encoding set up, R can cause you much grief with this. As a rule of thumb, it is always best to try to interface with UTF-8 whenever possible, as it causes the least pain points, regardless of what your platform’s native encoding may be. Finding out where the source of encoding issues arise can be a challenge, so the following tools will help: textclean package β€” used to detect issues with encoded text rvest β€” good for attempting to guess the encoding if you are unsure datapasta β€” good for easily recreating a tibble stringi- brute force way to view if the unicode matches what we are looking at, and clean it base::charToRaw β€” to view raw bytes of the string tools::showNonASCII and iconv to show non-ASCII chars Unicode inspector - https://apps.timwhitlock.info/unicode/inspect Unicode Table - http://www.utf8-chartable.de/ Our general workflow will be as such: Detect or identify issues with the text attempt to fix encoding Before we move on, I would strongly encourage you to make sure you can view whitespace in RStudio via Tools-Global Options-Code, and show whitespace characters. Also, go into Visual Studio Code, and do the same by going to View- Toggle Render Whitespace as well. Lets take a small bit of code to use for an example. Suppose you get this data: bad_data <- tibble::tribble( ~id, ~value, 390639, β€œRATINGS: 4 MEAN: 3.83/5.0 WEIGHTED AVG: 3.39/5 IBU: 35 EST. CALORIES: 204 ABV: 6.8%”, 99472, β€œRATINGS: 89 WEIGHTED AVG: 3.64/5 EST. CALORIES: 188 ABV: 6.25%”, 361258, β€œRATINGS: 8 MEAN: 3.7/5.0 WEIGHTED AVG: 3.45/5 IBU: 85 EST. CALORIES: 213 ABV: 7.1%”)> Encoding(bad_data$value)[1] "UTF-8" "UTF-8" "UTF-8" How would we detect if there is an issue with it? We can see from above that the data is encoded as UTF-8, so we should be fine then......right? Wasn’t that what the webpage told us it was encoded in? Yes, but looking deeper into the data, there appears to be some characters that diden’t get converted over correctly. So how exactly do we β€˜correct’ a bad UTF-8 file? Well, for starters, we could try re-create the dataframe using datapasta as below, and hope that we can see something datapasta::tribble_paste(bad_data) Lucky for us, when we do this, we can see that there is something that seems funny: Ok, so there’s some odd red spaces inside our data...what does that even mean RStudio?If we paste the output into a Visual Studio Code, we can see something a bit pecuilar: After looking at the above screenshot, something seems to be a bit off. Why is there no space where the blue arrows are? Seems a bit odd. Say we wanted to look at not just 3 beers, but hundreds, maybe thousands of beers, could this work? Sure, but there has to be a better method, and there is: #Truncated Outputtextclean::check_text(bad_data$value)=========NON ASCII=========The following observations were non ascii:1, 2, 3The following text is non ascii:1: RATINGS: 4 MEAN: 3.83/5.0 WEIGHTED AVG: 3.39/5 IBU: 35 EST. CALORIES: 204 ABV: 6.8%2: RATINGS: 89 WEIGHTED AVG: 3.64/5 EST. CALORIES: 188 ABV: 6.25%3: RATINGS: 8 MEAN: 3.7/5.0 WEIGHTED AVG: 3.45/5 IBU: 85 EST. CALORIES: 213 ABV: 7.1%*Suggestion: Consider running `replace_non_ascii` The textclean package is a derivative of the qdap package, which is designed to work with text data, but requires rJava to work properly. textclean is a port from the qdap ecosystem, and much lighter, thus allowing us to use it to detect issues with our text. As we can see above, there are plenty of errors, but this allows us to verify that non-ascii characters exist within our text, and hence causes us headaches if we don’t take care of them now. Now, if you are like me, attempting to get a grip on what exactly is going on in the string can be a bit of a challenge: how do we know where in the string these issues occur? Fortunately for us, base-r provides some excellent tools to help detect this: > iconv(bad_data$value[[2]], to = "ASCII", sub = "byte")[1] "RATINGS: 89<c2><a0><c2><a0> WEIGHTED AVG: 3.64/5<c2><a0><c2><a0> EST. CALORIES: 188<c2><a0><c2><a0> ABV: 6.25%"> tools::showNonASCII(x$value[[2]])1: RATINGS: 89<c2><a0><c2><a0> WEIGHTED AVG: 3.64/5<c2><a0><c2><a0> EST. CALORIES: 188<c2><a0><c2><a0> ABV: 6.25% The tools package and iconv in R both allow us to see that sure enough, there appears to be some odd characters indicated by the <>. If you want to get a better feel for what exactly these characters are, we can plug the raw output from datapasta’s tribble_paste into Tim Whitlock’s Unicode Inspector, and we can see that sure enough, we have a character called β€œNo Break Space” and the respective UTF-16 code. To verify, we can plug in that code with the prefix \u, and the code from above, and sure enough: str_detect(bad_data$value[[2]], β€œ\u00A0”) It works! Now we need to figure out how to repair the string.To repair the string, we could go about fixing it via rvest, textclean, or stringi: bad_data <- tibble::tribble( ~id, ~value, 390639, β€œRATINGS: 4 MEAN: 3.83/5.0 WEIGHTED AVG: 3.39/5 IBU: 35 EST. CALORIES: 204 ABV: 6.8%”, 99472, β€œRATINGS: 89 WEIGHTED AVG: 3.64/5 EST. CALORIES: 188 ABV: 6.25%”, 361258, β€œRATINGS: 8 MEAN: 3.7/5.0 WEIGHTED AVG: 3.45/5 IBU: 85 EST. CALORIES: 213 ABV: 7.1%”)#' for reference#' https://stackoverflow.com/questions/29265172/print-unicode-character-string-in-r#' stringi also uses mostly UTF-8, which is very comforting to know#'https://jangorecki.gitlab.io/data.table/library/stringi/html/stringi-encoding.htmlstr_detect(x$value, "\u00A0")ex1 <- textclean::replace_non_ascii(bad_data$value)ex2 <- rvest::repair_encoding(bad_data$value) textclean will eliminate the values it detects, while rvest will try to preserve the value. While rvest can (and does offer this capability), it doesn’t do the best job of cleaning the text data reliably. Instead, stringi offers us the function str_trans_general, which will allow us to keep our three spaces between each characters intact. This will allow us to use those spaces later on as delimiters to clean the data even further. bad_data$value <- stringi::stri_trans_general(bad_data$value, β€œlatin-ascii”) Now, this sounds awesome, but maybe you are like me, and find a massive amount of beer data (say 2GB), and find that there may be some encoding issues.....we could try and run a function to clean the data after import, but that could take quite a bit of time. Is there a better way of dealing with this mess? Yes, there is. Enter iconv: www.gnu.org iconv is a GNU command-line utility that helps with force converting data into it’s correct form, while still trying to retain as much data as possible. Let’s use data from here as an example: data.world Now, at first glance the data may seem a bit messy, but let’s focus on trying to convert the data into UTF-8. First, lets use gunzip from r to unzip the file to a directory. #Gunzip Ratebeer gunzip(filename = β€œ~/petergensler/Desktop/Ratebeer.txt.gz”, destname = β€œ~/petergensler/Desktop/Ratebeer.txt”, remove= FALSE) The ~ in this command simply means relative to your Home directory on your machine. Simply type cd inside a terminal, and you will be take to your home directory. Next, we can use bash to determine how many lines are in this file via wc -l, and we can also see what bash thinks the encoding is with file -I: wc -l Ratebeer.txt22212596 Ratebeer.txtfile -I Ratebeer.txtRatebeer.txt: text/plain; charset=utf-8 Ok, so this looks to appear ok, but with 22 million lines, this has to be a hassle to fix. Not quite iconv makes this process a breeze: Approach 1:iconv βˆ’f isoβˆ’8859βˆ’1 βˆ’t UTFβˆ’8 Ratebeer.txt > RateBeer-iconv.txtApproach 2:iconv -c -t UTF-8 Ratebeer.txt > Ratebeer-iconv.txt With approach one, we try to take the file in what we think the file should be, and specify that we want it to be UTF-8, and try to overwrite it. Approach two is a much more brute-force approach, as we simply tell iconv that we want to convert to UTF-8, and create a new file. Woila! We can now read the file in as raw lines if needed, and no hiccups, all thanks to iconv. One thing to note is that while R does have an iconv function, I have found the command line utility to be much more versatile for my needs, and you can simply put a bash chunk in RMarkdown notebook. Use the command line. Now that we have obtained our data, and cleaned the encoding, let’s see if we can try to get the basic statistics into their respective columns. At first glance, this seems simple, as we just need to split the statistics column on a delimiter, and life should be good. But of course one of the beers I have does not have the same amount of elements as the other’s thus wreaking havoc at first sight (as if encoding was already challenging enough). Just to recap, our data looks like this: bad_data <- tibble::tribble( ~name, ~link, ~beer_stats, "pollyanna-eleanor-with-vanilla-beans", "https://www.ratebeer.com/beer/pollyanna-eleanor-with-vanilla-beans/390639/", "RATINGS: 4 MEAN: 3.83/5.0 WEIGHTED AVG: 3.39/5 IBU: 35 EST. CALORIES: 204 ABV: 6.8%", "brickstone-apa", "https://www.ratebeer.com/beer/brickstone-apa/99472/", "RATINGS: 89 WEIGHTED AVG: 3.64/5 EST. CALORIES: 188 ABV: 6.25%", "penrose-taproom-ipa", "https://www.ratebeer.com/beer/penrose-taproom-ipa/361258/", "RATINGS: 8 MEAN: 3.7/5.0 WEIGHTED AVG: 3.45/5 IBU: 85 EST. CALORIES: 213 ABV: 7.1%", "revolution-rev-pils", "https://www.ratebeer.com/beer/revolution-rev-pils/360716/", "RATINGS: 34 MEAN: 3.47/5.0 WEIGHTED AVG: 3.42/5 IBU: 50 EST. CALORIES: 150 Part of the key to understanding the task at hand is twofold- we want to split the data into each column but using the : to keep the key-value pair relationship. final_output <- bad_data %>% # create a new list column, str_split returns a list mutate(split = str_split(string, " ")) %>% # then unnest the column before further data prep unnest() %>% # you can now separate in a fixed 2 length vector separate(split, c("type", "valeur"), ": ") %>% # then get the result in column with NA in cells where you did not have value in string spread(type, valeur) %>% rename_all(str_trim) %>% select(-string, -link)#> # A tibble: 3 x 6#> ABV `EST. CALORIES` IBU MEAN `WEIGHTED AVG` RATINGS#> * <chr> <chr> <chr> <chr> <chr> <chr>#> 1 6.8% 204 35 3.83/5.0 3.39/5 4#> 2 7.1% 213 85 3.7/5.0 3.45/5 8#> 3 6.25% 188 <NA> <NA> 3.64/5 89 Understand that when I first ran this script, the very first line failed right out the gate β€” β€” due to encoding issues, but I never got an error message until actually trying to use the spread function. At first, this can seem a bit convoluted, especially if you are unfamiliar with the list-column.When I first looked at this code, it seemed like the str_split just had a really odd behavior, and was almost an unnecessary burden on the code. Unnesting the list-column almost creates a cartesian-like join which takes each record, and then makes it so that each row has every possible combination of every value, thus making it possible to spread, and spread dynamically. Now our table looks like this: > head(final_output)# A tibble: 4 x 7 name ABV `EST. CALORIES` IBU MEAN RATINGS `WEIGHTED AVG` <chr> <chr> <chr> <chr> <chr> <chr> <chr>1 brickstone-apa 6.25% 188 <NA> <NA> 89 3.64/52 penrose-taproom-ipa 7.1% 213 85 3.7/5.0 8 3.45/53 pollyanna-eleanor-with-vanilla-beans 6.8% 204 35 3.83/5.0 4 3.39/54 revolution-rev-pils 5% 150 50 3.47/5.0 34 3.42/5 From this, it’s interesting to note that the beer with the most amount of ratings does not have an average review, but the Pollyanna seems to have the highest score. As you finish up reading this article, I would encourage you to try and take some beers (or beverages of your choice), and try to collect data on them. What do you notice? Is there a correlation between ABV(how strong the drink can be) and the beer’s average review score? I hope this tutorial has been able to help you gain insights into how to use R to your advantage when trying to solve problems, and that you have learned more about encoding in R, and tools to help when faced with these challenges. I’ve outlined some of my thoughts below as I’ve been reflecting on how this data has challenged me in so many ways, and not just with R, but in my personal workflow in general. Encoding As I have been working with R over the past few days, one of the things that I’ve continued to notice is that when R fails, it can be hard to explicitly tell when it failed and why.As a novice coming into R, I think this makes it incredibly challenging to diagnose what tool could be failing, as R does not fail fast, and fail hard. With the encoding of our strings: Did reading the html fail? Was it just tidyr that had issues with UTF-8, or this a deeper issue? If base r has so many encoding issues, is this a β€œfirm foundation” for any project, work related or not? Going through the hell of encoding issues definitely makes it clear that if you are using Windows, encoding can be a disaster with R. For me personally, I actually looked at a different flavor of R released from TIBCO called TERR: docs.tibco.com because so much of base-r’s encoding issue were just such a hassle to mess with. These issues while small, I think almost sent a message regarding R’s core: it is simply not a stable foundation. Working with functions and not trusting the output can be extremely hindering from a development point of view. The tidyverse definitely has a lot to offer for newcomers with new packages being developed, but I think this raises up a good question: should you be using R in production pipelines, or even for analysis purposes? Everything seems to be so smooth when you don’t hit any of these issues, but once you do, it’s a true pain to debug, especially for a novice to the language. purr map vs dplyr: Riding the line purrr at first sight seems like an ideal package, but can be hard to work with if you don’t have the right use case. In our example, we had URL’s that we want to apply a function over. However, while purrr is designed to apply functions to objects, most times we are simply interested in applying a function such as converting POSIX to datetime via a predicate function: library(lubridate)library(dplyr)x <- data.frame(date=as.POSIXct("2010-12-07 08:00:00", "2010-12-08 08:00:00"), orderid =c(1,2))str(x)x <- mutate_if(x, is.POSIXt, as.Date)str(x) Purrr really shines when you need to iterate over elements with custom functions, but can be hard to come to grips if all you have done is using a mutate_if in your workflow. On the contrary, it can also be just as hard trying to figure out what these newer functions in dplyr can do for you, if you have never seen them in action. R has good merits with being a functional programming language: it allows you to operate on data with ease, and there is plenty of functions at your disposal to do so. If anything, one of the biggest challenges I faced as I wrote this article is just where exactly to start when looking for a solution: R Manual, stack overflow, a particular package, or even the RStudio Community. In the right hands, and with the right skillset, R can be a powerful tool when put to good use, but is not for the faint of heart. What do you think? Do you think R is powerful enough for your everyday tasks, or do you think base-r feels unstable at times?
[ { "code": null, "e": 755, "s": 172, "text": "If there had to be one topic that was so hard to comprehend after using R, it has to be functions. Everything from writing a function, to learning how to debug a function has just never had some clear instructions on how to do so. In addition, there are tools that have come out that are meant to help with this task, but can seem rather hard to understand how to utilize when solving your problem. This blog intends to get you up and running with what functions are in R, how to utilize them for tasks, and easily debug them inside RStudio to troubleshoot what is exactly going on." }, { "code": null, "e": 1500, "s": 755, "text": "Recently I had the opportunity of going to a Cider Festival, to learn and try new ciders.I’m not the biggest fan of cider’s, so naturally I opted to try almost every beer that was available, and wanted to compare what I tasted. If anyone were to ask about my taste buds, it would be that I love shandy’s, and wheat beer. None of the beer’s I tried were even remotely close to my liking, yet somehow tasted much better than I anticipated. It sure would be helpful to have a way to compare the beer’s I’ve tried to see just why I enjoyed an American Pale ale, and even a cask. Using rvest, we can easily scrape the necessary data about each beer from RateBeer to help compare them against each other to determine what similarities they may share." }, { "code": null, "e": 1903, "s": 1500, "text": "Before we get started, a few ground rules need to be established so that you get yourself on the right track for the task at hand. Interacting with the web via programming can very easily feel like uncharted terriority at first, almost like drinking your first beer: Where am I, and how did I end up here?But, fear not, as this blog will provide you the resources to not get lost navigating this abyss." }, { "code": null, "e": 2010, "s": 1903, "text": "In order to gain the most value from what is outlined within this blog, you will need the following tools:" }, { "code": null, "e": 2018, "s": 2010, "text": "RStudio" }, { "code": null, "e": 2037, "s": 2018, "text": "Visual Studio Code" }, { "code": null, "e": 2047, "s": 2037, "text": "GitKraken" }, { "code": null, "e": 2670, "s": 2047, "text": "Why do we need these you might ask? Equipping yourself with the right tools can sometimes be half the battle with r: it’s hard to figure out how to understand the problem at hand if you don’t have the necessary tools to solve the problem. In addition to these tools, I would strongly encourage you to think about using a sandbox environment, using Docker or RStudio Cloud, as R has had some pain points with encodings on different operating systems. If you would like more information on how to create your own custom sandbox environment for R, you can check out this blog for more information, or check out RStudio Cloud." }, { "code": null, "e": 2765, "s": 2670, "text": "https://medium.com/@peterjgensler/creating-sandbox-environments-for-r-with-docker-def54e3491a3" }, { "code": null, "e": 2788, "s": 2765, "text": "https://rstudio.cloud/" }, { "code": null, "e": 2862, "s": 2788, "text": "At a high level, there are two generic ways of obtaining data on the web:" }, { "code": null, "e": 2918, "s": 2862, "text": "API’s β€” API is called Application Programming Interface" }, { "code": null, "e": 2963, "s": 2918, "text": "Web Scraping- more of a brute-force approach" }, { "code": null, "e": 3022, "s": 2963, "text": "Ok, so what exactly is an API, then? Should I be using it?" }, { "code": null, "e": 3107, "s": 3022, "text": "β€œAn API is a messenger that takes requests, and then returns a response back to you”" }, { "code": null, "e": 3220, "s": 3107, "text": "API’s are setup so you can easily interact with services. Let’s say I want to pull data on Fires in Minneapolis." }, { "code": null, "e": 3231, "s": 3220, "text": "data.world" }, { "code": null, "e": 3296, "s": 3231, "text": "If I wanted, I could easily pull this data via data.world’s API:" }, { "code": null, "e": 3315, "s": 3296, "text": "apidocs.data.world" }, { "code": null, "e": 3672, "s": 3315, "text": "Web scraping, on the other hand is a much more brute-force way of obtaining data on the web. Not all sites have API’s to use, which means that it may be necessary to scrape to find. How would we go about checking if we can scrape a webpage? Simple, check the robots.txt file. Check out this video for more information on what a robots.txt file is used for:" }, { "code": null, "e": 3780, "s": 3672, "text": "For our case, we are using the site RateBeer, so let’s look at their file to see if there are restrictions:" }, { "code": null, "e": 3816, "s": 3780, "text": "https://www.ratebeer.com/robots.txt" }, { "code": null, "e": 3879, "s": 3816, "text": "User-agent: Mediapartners-GoogleDisallow:User-agent: *Allow: /" }, { "code": null, "e": 4006, "s": 3879, "text": "Looking at RateBeer’s robots.txt file, we can see that they allow scraping, as they disallow nothing, so we are OK to proceed." }, { "code": null, "e": 4185, "s": 4006, "text": "Grab a sandwich, get some coffee, and go watch this webinar from RStudio listed below. RStudio has two great webinars that cover API’s, and web-scraping in depth, we want part 2:" }, { "code": null, "e": 4201, "s": 4185, "text": "www.rstudio.com" }, { "code": null, "e": 4247, "s": 4201, "text": "The slides for the webinar can be found here:" }, { "code": null, "e": 4331, "s": 4247, "text": "https://github.com/rstudio/webinars/blob/master/32-Web-Scraping/02-Web-Scraping.pdf" }, { "code": null, "e": 4746, "s": 4331, "text": "After I watched the webinar listed above, I was so lost on all these topics, and rightfully so. Learning about the web technologies used to engineer websites is not a small task, and can be very hard when first getting started. If you want further resources to look to, I would strongly encourage you to view these slides from useR 2016 which are very similar, and do a good job of the getting the lay of the land:" }, { "code": null, "e": 4840, "s": 4746, "text": "https://github.com/ropensci/user2016-tutorial/blob/master/03-scraping-data-without-an-api.pdf" }, { "code": null, "e": 5118, "s": 4840, "text": "Most packages developed for web scraping with R are meant for scraping either HTML or CSS parts of a webpage, not Javascript content, which is rendered in the browser. Javascript is much more complex to scrape, and can be done with RSelenium, but is not for the faint of heart:" }, { "code": null, "e": 5129, "s": 5118, "text": "github.com" }, { "code": null, "e": 5397, "s": 5129, "text": "To get our data to work with, we first need to set up some functions to acquire our variables for each beer. Now, I have only picked three beers to keep this simple, but I hope this example illustrates how powerful a function can be when put to use. Lets take a look:" }, { "code": null, "e": 5551, "s": 5397, "text": "In order to compare each beer, we first need to find a way to get attributes about each beer. Ratebeer provides us with basic statistics about each beer:" }, { "code": null, "e": 5916, "s": 5551, "text": "As you can see above, we are interested in taking the descriptive statistics about each beer, but how would we go about finding what exactly links to that element? As there is no JavaScript on these webpages about each Beer, we can simply utilize tools to find the respective CSS or Xpath to the element we are interested in. The easiest way of going about this is" }, { "code": null, "e": 6195, "s": 5916, "text": "Now, in order to pull the data from the website, we first need to download the webpage, and then attempt to select the element we are interested in via a CSS tag or an xpath to the element we are interested in.Unquestionably, this can be an excruciating process for two reasons:" }, { "code": null, "e": 6372, "s": 6195, "text": "CSS tags should(but do not) work with rvest due to selectr having some issues(which drives finding the CSS tags): https://github.com/sjp/selectr/issues/7#issuecomment-344230855" }, { "code": null, "e": 6505, "s": 6372, "text": "Or, you have no idea if the path selected was the correct path for the element you want, which is more common than I’d like to admit" }, { "code": null, "e": 6667, "s": 6505, "text": "Now, at first, this seems like an almost impossible task, but fear not. We can still use an xpath to select what we are interested in extracting for further use." }, { "code": null, "e": 6809, "s": 6667, "text": "Two tools are very useful for finding the correct xpath for the element that you wish to pull: Selectorgadget and the chrome developer tools." }, { "code": null, "e": 7100, "s": 6809, "text": "Selectorgadget is a point-and-click CSS selector, specifically for Chrome. Simply install the chrome extension, and then click on the elements you are interested it. This will select all elements that are related to that object.Next, select anything in yellow you do not want. There you go!" }, { "code": null, "e": 7154, "s": 7100, "text": "More information on SelectorGadget can be found here:" }, { "code": null, "e": 7173, "s": 7154, "text": "selectorgadget.com" }, { "code": null, "e": 7259, "s": 7173, "text": "You can also find a well detailed walkthrough here if you need an additional example:" }, { "code": null, "e": 7278, "s": 7259, "text": "cran.r-project.org" }, { "code": null, "e": 7425, "s": 7278, "text": "If you have issues getting the correct xpath from SelectorGadget, you can also try using the Chrome developer tools, which are very user friendly." }, { "code": null, "e": 7503, "s": 7425, "text": "Simply click on View-Developer Tools, which will load up the developer tools." }, { "code": null, "e": 7660, "s": 7503, "text": "Next, click on the little mouse button to interact with the webpage. This will enable your cursor to show you what code is driving each element on the page." }, { "code": null, "e": 7798, "s": 7660, "text": "In the below screenshot, we can see that what we select with our mouse, and the respective code which is driving that particular element." }, { "code": null, "e": 8273, "s": 7798, "text": "Click on the blue area above, as indicated above. In this case, we are interested in the stats container, as it contains the metrics that we want to compare. This will lock you on that element so your cursor does not try to select HTML or CSS for other elements. Now right click on the area in the html code highlighted(red box), and then select copy->Copy XPath. This will allow you to get down to the most specific path for where that particular element lives on the page." }, { "code": null, "e": 8400, "s": 8273, "text": "Perfect! Now that we have the xpath for the element we can begin to start writing our function to extract data from the xpath." }, { "code": null, "e": 8728, "s": 8400, "text": "Let’s recap up to this point what we have accomplished. Up to this point, we first identified what exactly we wanted to accomplish: scrape basic statistics about each beer. We then found the necessary xpath, which identifies the element on the webpage we are interested in. Using rvest, we can write a script which allows us to" }, { "code": null, "e": 8935, "s": 8728, "text": "Outlined in the slides from RStudio(links at the beginning of the talk), there are three β€œcore activities” that we need to accomplish for a given webpage in our function. Thinking about it, they make sense:" }, { "code": null, "e": 8955, "s": 8935, "text": "Pull down a webpage" }, { "code": null, "e": 8981, "s": 8955, "text": "Identify elements we want" }, { "code": null, "e": 9012, "s": 8981, "text": "Extract & pull the element out" }, { "code": null, "e": 9051, "s": 9012, "text": "Tidy up the element to make it useable" }, { "code": null, "e": 9246, "s": 9051, "text": "There are three functions from the rvest package which allow us to perform these steps with ease. However, as we want to perform these steps on multiple URL’s we can set up our function like so:" }, { "code": null, "e": 10107, "s": 9246, "text": "library(magrittr) #for pipeslibrary(dplyr) #for pull functionlibrary(rvest) #get html nodeslibrary(xml2) #pull html datalibrary(selectr) #for xpath elementlibrary(tibble)library(purrr) #for map functionslibrary(datapasta) #for recreating tibble's with ease#Sample Datasample_data <- tibble::tibble( name = c(\"pollyanna-eleanor-with-vanilla-beans\",\"brickstone-apa\",\"penrose-taproom-ipa\",\"revolution-rev-pils\"), link = c(\"https://www.ratebeer.com/beer/pollyanna-eleanor-with-vanilla-beans/390639/\", \"https://www.ratebeer.com/beer/brickstone-apa/99472/\", \"https://www.ratebeer.com/beer/penrose-taproom-ipa/361258/\", \"https://www.ratebeer.com/beer/revolution-rev-pils/360716/\" ))#the function:get_beer_stats1 <- function(x){ read_html(x) %>% html_nodes(xpath = '//*[@id=\"container\"]/div[2]/div[2]/div[2]') %>% html_text()}" }, { "code": null, "e": 10238, "s": 10107, "text": "We could also write our function to be more explicit on when values change, making it easier to step through and debug in RStudio:" }, { "code": null, "e": 10419, "s": 10238, "text": "get_beer_stats2 <- function(x){ url <- read_html(x) html_doc <- html_nodes(url, xpath = '//*[@id=\"container\"]/div[2]/div[2]/div[2]') stats <- html_text(html_doc) return(stats)}" }, { "code": null, "e": 10735, "s": 10419, "text": "Hold up, I thought we were supposed to make sure every action is precisely logged so them computer understands it? Don’t we need some sort of for-loop, that acts as a counter to increase after each URL? Why didn’t we use the dplyr::pull command to literally pull the vector out of the dataframe to iterate on first?" }, { "code": null, "e": 10931, "s": 10735, "text": "One of the issues of working with purrr is understand how to think about the problem you are facing in the right mindset. Thinking about the problem, we can approach it from the following angles:" }, { "code": null, "e": 11053, "s": 10931, "text": "I have a dataframe of URL’s, and I want to iterate over each row(or URL), and perform a given set of actions for each URL" }, { "code": null, "e": 11143, "s": 11053, "text": "I have a dataframe with a column of URL’s and for each URL, I want to operate on each URL" }, { "code": null, "e": 11248, "s": 11143, "text": "Treating my column of URL’s in my dataframe as a vector, I want to operate on each element in the vector" }, { "code": null, "e": 11591, "s": 11248, "text": "You see, purr’s main workhorse function map, is designed to iterate over objects which contain a bunch of elements, which then allow you as the user to focus on writing a function that does some action. In R, most times these objects are either lists, list-columns, or simply a vector. In doing this, it allows you to have a workflow as such:" }, { "code": null, "e": 11647, "s": 11591, "text": "Determine what you would like to do for a given element" }, { "code": null, "e": 11683, "s": 11647, "text": "Turn that β€œrecipie” into a function" }, { "code": null, "e": 11790, "s": 11683, "text": "Apply the recipe with purr over the object (and if necessary, create a new column to store the results in)" }, { "code": null, "e": 11873, "s": 11790, "text": "Ok, now let’s apply the function we just created to our data, and see if it works:" }, { "code": null, "e": 11974, "s": 11873, "text": "sample_data_rev <- sample_data %>% mutate(., beer_stats = map_chr(.x = link, .f = get_beer_stats1))" }, { "code": null, "e": 12240, "s": 11974, "text": "Before we move on, lets break down what is exactly happening. First, we pipe in the dataframe, and say we want to add a new column with mutate. Next, we create a new column defined as a character column using map_chr (or vector), and then apply our custom function." }, { "code": null, "e": 12410, "s": 12240, "text": "Now that our core function is defined, we can use RStudio to walk through our function if we wanted to see how values are changing. Simply enable debug mode by going to:" }, { "code": null, "e": 12444, "s": 12410, "text": "Debug->On Error-> Error Inspector" }, { "code": null, "e": 12493, "s": 12444, "text": "Next, simply wrap your function with debug like:" }, { "code": null, "e": 12639, "s": 12493, "text": "debug(get_beer_stats1 <- function(x){ read_html(x) %>% html_nodes(xpath = '//*[@id=\"container\"]/div[2]/div[2]/div[2]') %>% html_text()})" }, { "code": null, "e": 12766, "s": 12639, "text": "When you run your code that calls your function, you will enter into debug mode so you can view how values change in the code:" }, { "code": null, "e": 12867, "s": 12766, "text": "sample_data_rev <- sample_data %>% mutate(., beer_stats = map_chr(.x = link, .f = get_beer_stats1))" }, { "code": null, "e": 13021, "s": 12867, "text": "Expanding on our example, lets say that we have URL’s that may cause some hiccups. How would we make an function which could hand these errors with ease?" }, { "code": null, "e": 13174, "s": 13021, "text": "purr equips us with error handling functions to wrap our function in to gracefully handle errors. We can add error handling using the possibly function:" }, { "code": null, "e": 13302, "s": 13174, "text": "sample_data_rev <- sample_data %>% mutate(., beer_stats = map_chr(.x = link, possibly(get_beer_stats1, otherwise= \"NULL\")))" }, { "code": null, "e": 13528, "s": 13302, "text": "Possibly is very similar to a try-catch, which allows us to wrap our created function with a different function for error handling. This can be a bit confusing at first glance, but makes sense once you have it setup properly." }, { "code": null, "e": 13782, "s": 13528, "text": "Before we move further, it may be worth noting that the following is what I will call β€œthe Abyss”, or Mordor. Beware that this is not for the faint of heart, so if you feel that you are ready, then proceed. Otherwise, go make a sandwich, and take a nap." }, { "code": null, "e": 13983, "s": 13782, "text": "For me, encoding in R has really reminded me of Mordor from Lord of the Rings. It just seems like some never ending pit that is almost near-death. Not to worry though, you are in good hands. Let’s go." }, { "code": null, "e": 14150, "s": 13983, "text": "So we have our data, and it should be all set for cleanup, right? Nope. Why is this the case? Earlier we mentioned that our workflow consisted of the following steps:" }, { "code": null, "e": 14170, "s": 14150, "text": "Pull down a webpage" }, { "code": null, "e": 14196, "s": 14170, "text": "Identify elements we want" }, { "code": null, "e": 14227, "s": 14196, "text": "Extract & pull the element out" }, { "code": null, "e": 14266, "s": 14227, "text": "Tidy up the element to make it useable" }, { "code": null, "e": 14681, "s": 14266, "text": "Part of the issue with this workflow is that it assumes once we pull out the data from the webpage, it should be β€˜ready to go, right off the boat’, which unfortunately, is not the case with data from the web. You see, data from the web has to be encoded, and finding or even detecting encoding issues can be a real hassle, as you may not find out until much further downstream in your analysis process, like I did." }, { "code": null, "e": 14909, "s": 14681, "text": "Before we step in any further, I would encourage you to first read the following articles. This will help lay the foundation for understanding what exactly is wrong with our text data, and strategies to help detect the culprit:" }, { "code": null, "e": 14920, "s": 14909, "text": "www.w3.org" }, { "code": null, "e": 14935, "s": 14920, "text": "r4ds.had.co.nz" }, { "code": null, "e": 15500, "s": 14935, "text": "To re-iterate, our computer (or machine, really), stores data in terms of bytes. These bytes are then encoded into different locales, such as UTF-8, or ANSI. Depending on how you have your platform(or machine’s) native encoding set up, R can cause you much grief with this. As a rule of thumb, it is always best to try to interface with UTF-8 whenever possible, as it causes the least pain points, regardless of what your platform’s native encoding may be. Finding out where the source of encoding issues arise can be a challenge, so the following tools will help:" }, { "code": null, "e": 15560, "s": 15500, "text": "textclean package β€” used to detect issues with encoded text" }, { "code": null, "e": 15628, "s": 15560, "text": "rvest β€” good for attempting to guess the encoding if you are unsure" }, { "code": null, "e": 15676, "s": 15628, "text": "datapasta β€” good for easily recreating a tibble" }, { "code": null, "e": 15769, "s": 15676, "text": "stringi- brute force way to view if the unicode matches what we are looking at, and clean it" }, { "code": null, "e": 15819, "s": 15769, "text": "base::charToRaw β€” to view raw bytes of the string" }, { "code": null, "e": 15873, "s": 15819, "text": "tools::showNonASCII and iconv to show non-ASCII chars" }, { "code": null, "e": 15939, "s": 15873, "text": "Unicode inspector - https://apps.timwhitlock.info/unicode/inspect" }, { "code": null, "e": 15985, "s": 15939, "text": "Unicode Table - http://www.utf8-chartable.de/" }, { "code": null, "e": 16023, "s": 15985, "text": "Our general workflow will be as such:" }, { "code": null, "e": 16063, "s": 16023, "text": "Detect or identify issues with the text" }, { "code": null, "e": 16087, "s": 16063, "text": "attempt to fix encoding" }, { "code": null, "e": 16248, "s": 16087, "text": "Before we move on, I would strongly encourage you to make sure you can view whitespace in RStudio via Tools-Global Options-Code, and show whitespace characters." }, { "code": null, "e": 16350, "s": 16248, "text": "Also, go into Visual Studio Code, and do the same by going to View- Toggle Render Whitespace as well." }, { "code": null, "e": 16430, "s": 16350, "text": "Lets take a small bit of code to use for an example. Suppose you get this data:" }, { "code": null, "e": 16787, "s": 16430, "text": "bad_data <- tibble::tribble( ~id, ~value, 390639, β€œRATINGS: 4 MEAN: 3.83/5.0 WEIGHTED AVG: 3.39/5 IBU: 35 EST. CALORIES: 204 ABV: 6.8%”, 99472, β€œRATINGS: 89 WEIGHTED AVG: 3.64/5 EST. CALORIES: 188 ABV: 6.25%”, 361258, β€œRATINGS: 8 MEAN: 3.7/5.0 WEIGHTED AVG: 3.45/5 IBU: 85 EST. CALORIES: 213 ABV: 7.1%”)> Encoding(bad_data$value)[1] \"UTF-8\" \"UTF-8\" \"UTF-8\"" }, { "code": null, "e": 17155, "s": 16787, "text": "How would we detect if there is an issue with it? We can see from above that the data is encoded as UTF-8, so we should be fine then......right? Wasn’t that what the webpage told us it was encoded in? Yes, but looking deeper into the data, there appears to be some characters that diden’t get converted over correctly. So how exactly do we β€˜correct’ a bad UTF-8 file?" }, { "code": null, "e": 17273, "s": 17155, "text": "Well, for starters, we could try re-create the dataframe using datapasta as below, and hope that we can see something" }, { "code": null, "e": 17308, "s": 17273, "text": "datapasta::tribble_paste(bad_data)" }, { "code": null, "e": 17392, "s": 17308, "text": "Lucky for us, when we do this, we can see that there is something that seems funny:" }, { "code": null, "e": 17565, "s": 17392, "text": "Ok, so there’s some odd red spaces inside our data...what does that even mean RStudio?If we paste the output into a Visual Studio Code, we can see something a bit pecuilar:" }, { "code": null, "e": 17860, "s": 17565, "text": "After looking at the above screenshot, something seems to be a bit off. Why is there no space where the blue arrows are? Seems a bit odd. Say we wanted to look at not just 3 beers, but hundreds, maybe thousands of beers, could this work? Sure, but there has to be a better method, and there is:" }, { "code": null, "e": 18334, "s": 17860, "text": "#Truncated Outputtextclean::check_text(bad_data$value)=========NON ASCII=========The following observations were non ascii:1, 2, 3The following text is non ascii:1: RATINGS: 4 MEAN: 3.83/5.0 WEIGHTED AVG: 3.39/5 IBU: 35 EST. CALORIES: 204 ABV: 6.8%2: RATINGS: 89 WEIGHTED AVG: 3.64/5 EST. CALORIES: 188 ABV: 6.25%3: RATINGS: 8 MEAN: 3.7/5.0 WEIGHTED AVG: 3.45/5 IBU: 85 EST. CALORIES: 213 ABV: 7.1%*Suggestion: Consider running `replace_non_ascii`" }, { "code": null, "e": 18786, "s": 18334, "text": "The textclean package is a derivative of the qdap package, which is designed to work with text data, but requires rJava to work properly. textclean is a port from the qdap ecosystem, and much lighter, thus allowing us to use it to detect issues with our text. As we can see above, there are plenty of errors, but this allows us to verify that non-ascii characters exist within our text, and hence causes us headaches if we don’t take care of them now." }, { "code": null, "e": 19040, "s": 18786, "text": "Now, if you are like me, attempting to get a grip on what exactly is going on in the string can be a bit of a challenge: how do we know where in the string these issues occur? Fortunately for us, base-r provides some excellent tools to help detect this:" }, { "code": null, "e": 19361, "s": 19040, "text": "> iconv(bad_data$value[[2]], to = \"ASCII\", sub = \"byte\")[1] \"RATINGS: 89<c2><a0><c2><a0> WEIGHTED AVG: 3.64/5<c2><a0><c2><a0> EST. CALORIES: 188<c2><a0><c2><a0> ABV: 6.25%\"> tools::showNonASCII(x$value[[2]])1: RATINGS: 89<c2><a0><c2><a0> WEIGHTED AVG: 3.64/5<c2><a0><c2><a0> EST. CALORIES: 188<c2><a0><c2><a0> ABV: 6.25%" }, { "code": null, "e": 19494, "s": 19361, "text": "The tools package and iconv in R both allow us to see that sure enough, there appears to be some odd characters indicated by the <>." }, { "code": null, "e": 19740, "s": 19494, "text": "If you want to get a better feel for what exactly these characters are, we can plug the raw output from datapasta’s tribble_paste into Tim Whitlock’s Unicode Inspector, and we can see that sure enough, we have a character called β€œNo Break Space”" }, { "code": null, "e": 19870, "s": 19740, "text": "and the respective UTF-16 code. To verify, we can plug in that code with the prefix \\u, and the code from above, and sure enough:" }, { "code": null, "e": 19912, "s": 19870, "text": "str_detect(bad_data$value[[2]], β€œ\\u00A0”)" }, { "code": null, "e": 20057, "s": 19912, "text": "It works! Now we need to figure out how to repair the string.To repair the string, we could go about fixing it via rvest, textclean, or stringi:" }, { "code": null, "e": 20736, "s": 20057, "text": "bad_data <- tibble::tribble( ~id, ~value, 390639, β€œRATINGS: 4 MEAN: 3.83/5.0 WEIGHTED AVG: 3.39/5 IBU: 35 EST. CALORIES: 204 ABV: 6.8%”, 99472, β€œRATINGS: 89 WEIGHTED AVG: 3.64/5 EST. CALORIES: 188 ABV: 6.25%”, 361258, β€œRATINGS: 8 MEAN: 3.7/5.0 WEIGHTED AVG: 3.45/5 IBU: 85 EST. CALORIES: 213 ABV: 7.1%”)#' for reference#' https://stackoverflow.com/questions/29265172/print-unicode-character-string-in-r#' stringi also uses mostly UTF-8, which is very comforting to know#'https://jangorecki.gitlab.io/data.table/library/stringi/html/stringi-encoding.htmlstr_detect(x$value, \"\\u00A0\")ex1 <- textclean::replace_non_ascii(bad_data$value)ex2 <- rvest::repair_encoding(bad_data$value)" }, { "code": null, "e": 21171, "s": 20736, "text": "textclean will eliminate the values it detects, while rvest will try to preserve the value. While rvest can (and does offer this capability), it doesn’t do the best job of cleaning the text data reliably. Instead, stringi offers us the function str_trans_general, which will allow us to keep our three spaces between each characters intact. This will allow us to use those spaces later on as delimiters to clean the data even further." }, { "code": null, "e": 21248, "s": 21171, "text": "bad_data$value <- stringi::stri_trans_general(bad_data$value, β€œlatin-ascii”)" }, { "code": null, "e": 21585, "s": 21248, "text": "Now, this sounds awesome, but maybe you are like me, and find a massive amount of beer data (say 2GB), and find that there may be some encoding issues.....we could try and run a function to clean the data after import, but that could take quite a bit of time. Is there a better way of dealing with this mess? Yes, there is. Enter iconv:" }, { "code": null, "e": 21597, "s": 21585, "text": "www.gnu.org" }, { "code": null, "e": 21750, "s": 21597, "text": "iconv is a GNU command-line utility that helps with force converting data into it’s correct form, while still trying to retain as much data as possible." }, { "code": null, "e": 21790, "s": 21750, "text": "Let’s use data from here as an example:" }, { "code": null, "e": 21801, "s": 21790, "text": "data.world" }, { "code": null, "e": 21975, "s": 21801, "text": "Now, at first glance the data may seem a bit messy, but let’s focus on trying to convert the data into UTF-8. First, lets use gunzip from r to unzip the file to a directory." }, { "code": null, "e": 22117, "s": 21975, "text": "#Gunzip Ratebeer gunzip(filename = β€œ~/petergensler/Desktop/Ratebeer.txt.gz”, destname = β€œ~/petergensler/Desktop/Ratebeer.txt”, remove= FALSE)" }, { "code": null, "e": 22280, "s": 22117, "text": "The ~ in this command simply means relative to your Home directory on your machine. Simply type cd inside a terminal, and you will be take to your home directory." }, { "code": null, "e": 22425, "s": 22280, "text": "Next, we can use bash to determine how many lines are in this file via wc -l, and we can also see what bash thinks the encoding is with file -I:" }, { "code": null, "e": 22524, "s": 22425, "text": "wc -l Ratebeer.txt22212596 Ratebeer.txtfile -I Ratebeer.txtRatebeer.txt: text/plain; charset=utf-8" }, { "code": null, "e": 22660, "s": 22524, "text": "Ok, so this looks to appear ok, but with 22 million lines, this has to be a hassle to fix. Not quite iconv makes this process a breeze:" }, { "code": null, "e": 22796, "s": 22660, "text": "Approach 1:iconv βˆ’f isoβˆ’8859βˆ’1 βˆ’t UTFβˆ’8 Ratebeer.txt > RateBeer-iconv.txtApproach 2:iconv -c -t UTF-8 Ratebeer.txt > Ratebeer-iconv.txt" }, { "code": null, "e": 23169, "s": 22796, "text": "With approach one, we try to take the file in what we think the file should be, and specify that we want it to be UTF-8, and try to overwrite it. Approach two is a much more brute-force approach, as we simply tell iconv that we want to convert to UTF-8, and create a new file. Woila! We can now read the file in as raw lines if needed, and no hiccups, all thanks to iconv." }, { "code": null, "e": 23391, "s": 23169, "text": "One thing to note is that while R does have an iconv function, I have found the command line utility to be much more versatile for my needs, and you can simply put a bash chunk in RMarkdown notebook. Use the command line." }, { "code": null, "e": 23839, "s": 23391, "text": "Now that we have obtained our data, and cleaned the encoding, let’s see if we can try to get the basic statistics into their respective columns. At first glance, this seems simple, as we just need to split the statistics column on a delimiter, and life should be good. But of course one of the beers I have does not have the same amount of elements as the other’s thus wreaking havoc at first sight (as if encoding was already challenging enough)." }, { "code": null, "e": 23880, "s": 23839, "text": "Just to recap, our data looks like this:" }, { "code": null, "e": 24992, "s": 23880, "text": "bad_data <- tibble::tribble( ~name, ~link, ~beer_stats, \"pollyanna-eleanor-with-vanilla-beans\", \"https://www.ratebeer.com/beer/pollyanna-eleanor-with-vanilla-beans/390639/\", \"RATINGS: 4 MEAN: 3.83/5.0 WEIGHTED AVG: 3.39/5 IBU: 35 EST. CALORIES: 204 ABV: 6.8%\", \"brickstone-apa\", \"https://www.ratebeer.com/beer/brickstone-apa/99472/\", \"RATINGS: 89 WEIGHTED AVG: 3.64/5 EST. CALORIES: 188 ABV: 6.25%\", \"penrose-taproom-ipa\", \"https://www.ratebeer.com/beer/penrose-taproom-ipa/361258/\", \"RATINGS: 8 MEAN: 3.7/5.0 WEIGHTED AVG: 3.45/5 IBU: 85 EST. CALORIES: 213 ABV: 7.1%\", \"revolution-rev-pils\", \"https://www.ratebeer.com/beer/revolution-rev-pils/360716/\", \"RATINGS: 34 MEAN: 3.47/5.0 WEIGHTED AVG: 3.42/5 IBU: 50 EST. CALORIES: 150" }, { "code": null, "e": 25154, "s": 24992, "text": "Part of the key to understanding the task at hand is twofold- we want to split the data into each column but using the : to keep the key-value pair relationship." }, { "code": null, "e": 25955, "s": 25154, "text": "final_output <- bad_data %>% # create a new list column, str_split returns a list mutate(split = str_split(string, \" \")) %>% # then unnest the column before further data prep unnest() %>% # you can now separate in a fixed 2 length vector separate(split, c(\"type\", \"valeur\"), \": \") %>% # then get the result in column with NA in cells where you did not have value in string spread(type, valeur) %>% rename_all(str_trim) %>% select(-string, -link)#> # A tibble: 3 x 6#> ABV `EST. CALORIES` IBU MEAN `WEIGHTED AVG` RATINGS#> * <chr> <chr> <chr> <chr> <chr> <chr>#> 1 6.8% 204 35 3.83/5.0 3.39/5 4#> 2 7.1% 213 85 3.7/5.0 3.45/5 8#> 3 6.25% 188 <NA> <NA> 3.64/5 89" }, { "code": null, "e": 26158, "s": 25955, "text": "Understand that when I first ran this script, the very first line failed right out the gate β€” β€” due to encoding issues, but I never got an error message until actually trying to use the spread function." }, { "code": null, "e": 26628, "s": 26158, "text": "At first, this can seem a bit convoluted, especially if you are unfamiliar with the list-column.When I first looked at this code, it seemed like the str_split just had a really odd behavior, and was almost an unnecessary burden on the code. Unnesting the list-column almost creates a cartesian-like join which takes each record, and then makes it so that each row has every possible combination of every value, thus making it possible to spread, and spread dynamically." }, { "code": null, "e": 26659, "s": 26628, "text": "Now our table looks like this:" }, { "code": null, "e": 27285, "s": 26659, "text": "> head(final_output)# A tibble: 4 x 7 name ABV `EST. CALORIES` IBU MEAN RATINGS `WEIGHTED AVG` <chr> <chr> <chr> <chr> <chr> <chr> <chr>1 brickstone-apa 6.25% 188 <NA> <NA> 89 3.64/52 penrose-taproom-ipa 7.1% 213 85 3.7/5.0 8 3.45/53 pollyanna-eleanor-with-vanilla-beans 6.8% 204 35 3.83/5.0 4 3.39/54 revolution-rev-pils 5% 150 50 3.47/5.0 34 3.42/5" }, { "code": null, "e": 27451, "s": 27285, "text": "From this, it’s interesting to note that the beer with the most amount of ratings does not have an average review, but the Pollyanna seems to have the highest score." }, { "code": null, "e": 28133, "s": 27451, "text": "As you finish up reading this article, I would encourage you to try and take some beers (or beverages of your choice), and try to collect data on them. What do you notice? Is there a correlation between ABV(how strong the drink can be) and the beer’s average review score? I hope this tutorial has been able to help you gain insights into how to use R to your advantage when trying to solve problems, and that you have learned more about encoding in R, and tools to help when faced with these challenges. I’ve outlined some of my thoughts below as I’ve been reflecting on how this data has challenged me in so many ways, and not just with R, but in my personal workflow in general." }, { "code": null, "e": 28142, "s": 28133, "text": "Encoding" }, { "code": null, "e": 28509, "s": 28142, "text": "As I have been working with R over the past few days, one of the things that I’ve continued to notice is that when R fails, it can be hard to explicitly tell when it failed and why.As a novice coming into R, I think this makes it incredibly challenging to diagnose what tool could be failing, as R does not fail fast, and fail hard. With the encoding of our strings:" }, { "code": null, "e": 28536, "s": 28509, "text": "Did reading the html fail?" }, { "code": null, "e": 28606, "s": 28536, "text": "Was it just tidyr that had issues with UTF-8, or this a deeper issue?" }, { "code": null, "e": 28711, "s": 28606, "text": "If base r has so many encoding issues, is this a β€œfirm foundation” for any project, work related or not?" }, { "code": null, "e": 28942, "s": 28711, "text": "Going through the hell of encoding issues definitely makes it clear that if you are using Windows, encoding can be a disaster with R. For me personally, I actually looked at a different flavor of R released from TIBCO called TERR:" }, { "code": null, "e": 28957, "s": 28942, "text": "docs.tibco.com" }, { "code": null, "e": 29637, "s": 28957, "text": "because so much of base-r’s encoding issue were just such a hassle to mess with. These issues while small, I think almost sent a message regarding R’s core: it is simply not a stable foundation. Working with functions and not trusting the output can be extremely hindering from a development point of view. The tidyverse definitely has a lot to offer for newcomers with new packages being developed, but I think this raises up a good question: should you be using R in production pipelines, or even for analysis purposes? Everything seems to be so smooth when you don’t hit any of these issues, but once you do, it’s a true pain to debug, especially for a novice to the language." }, { "code": null, "e": 29672, "s": 29637, "text": "purr map vs dplyr: Riding the line" }, { "code": null, "e": 29857, "s": 29672, "text": "purrr at first sight seems like an ideal package, but can be hard to work with if you don’t have the right use case. In our example, we had URL’s that we want to apply a function over." }, { "code": null, "e": 30043, "s": 29857, "text": "However, while purrr is designed to apply functions to objects, most times we are simply interested in applying a function such as converting POSIX to datetime via a predicate function:" }, { "code": null, "e": 30235, "s": 30043, "text": "library(lubridate)library(dplyr)x <- data.frame(date=as.POSIXct(\"2010-12-07 08:00:00\", \"2010-12-08 08:00:00\"), orderid =c(1,2))str(x)x <- mutate_if(x, is.POSIXt, as.Date)str(x)" }, { "code": null, "e": 30567, "s": 30235, "text": "Purrr really shines when you need to iterate over elements with custom functions, but can be hard to come to grips if all you have done is using a mutate_if in your workflow. On the contrary, it can also be just as hard trying to figure out what these newer functions in dplyr can do for you, if you have never seen them in action." } ]
ReactJS - Quick Guide
ReactJS is a simple, feature rich, component based JavaScript UI library. It can be used to develop small applications as well as big, complex applications. ReactJS provides minimal and solid feature set to kick-start a web application. React community compliments React library by providing large set of ready-made components to develop web application in a record time. React community also provides advanced concept like state management, routing, etc., on top of the React library. The initial version, 0.3.0 of React is released on May, 2013 and the latest version, 17.0.1 is released on October, 2020. The major version introduces breaking changes and the minor version introduces new feature without breaking the existing functionality. Bug fixes are released as and when necessary. React follows the Sematic Versioning (semver) principle. The salient features of React library are as follows βˆ’ Solid base architecture Extensible architecture Component based library JSX based design architecture Declarative UI library Few benefits of using React library are as follows βˆ’ Easy to learn Easy to adept in modern as well as legacy application Faster way to code a functionality Availability of large number of ready-made component Large and active community Few popular websites powered by React library are listed below βˆ’ Facebook, popular social media application Instagram, popular photo sharing application Netflix, popular media streaming application Code Academy, popular online training application Reddit, popular content sharing application As you see, most popular application in every field is being developed by React Library. This chapter explains the installation of React library and its related tools in your machine. Before moving to the installation, let us verify the prerequisite first. React provides CLI tools for the developer to fast forward the creation, development and deployment of the React based web application. React CLI tools depends on the Node.js and must be installed in your system. Hopefully, you have installed Node.js on your machine. We can check it using the below command βˆ’ node --version You could see the version of Nodejs you might have installed. It is shown as below for me, v14.2.0 If Nodejs is not installed, you can download and install by visiting https://nodejs.org/en/download/. To develop lightweight features such as form validation, model dialog, etc., React library can be directly included into the web application through content delivery network (CDN). It is similar to using jQuery library in a web application. For moderate to big application, it is advised to write the application as multiple files and then use bundler such as webpack, parcel, rollup, etc., to compile and bundle the application before deploying the code. React toolchain helps to create, build, run and deploy the React application. React toolchain basically provides a starter project template with all necessary code to bootstrap the application. Some of the popular toolchain to develop React applications are βˆ’ Create React App βˆ’ SPA oriented toolchain Next.js βˆ’ server-side rendering oriented toolchain Gatsby βˆ’ Static content oriented toolchain Tools required to develop a React application are βˆ’ The serve, a static server to serve our application during development Babel compiler Create React App CLI Let us learn the basics of the above mentioned tools and how to install those in this chapter. The serve is a lightweight web server. It serves static site and single page application. It loads fast and consume minimum memory. It can be used to serve a React application. Let us install the tool using npm package manager in our system. npm install serve -g Let us create a simple static site and serve the application using serve app. Open a command prompt and go to your workspace. cd /go/to/your/workspace Create a new folder, static_site and change directory to newly created folder. mkdir static_site cd static_site Next, create a simple webpage inside the folder using your favorite html editor. <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Static website</title> </head> <body> <div><h1>Hello!</h1></div> </body> </html> Next, run the serve command. serve . We can also serve single file, index.html instead of the whole folder. serve ./index.html Next, open the browser and enter http://localhost:5000 in the address bar and press enter. serve application will serve our webpage as shown below. The serve will serve the application using default port, 5000. If it is not available, it will pick up a random port and specify it. β”‚ Serving! β”‚ β”‚ β”‚ β”‚ - Local: http://localhost:57311 β”‚ β”‚ - On Your Network: http://192.168.56.1:57311 β”‚ β”‚ β”‚ β”‚ This port was picked because 5000 is in use. β”‚ β”‚ β”‚ β”‚ Copied local address to clipboard! Babel is a JavaScript compiler which compiles many variant (es2015, es6, etc.,) of JavaScript into standard JavaScript code supported by all browsers. React uses JSX, an extension of JavaScript to design the user interface code. Babel is used to compile the JSX code into JavaScript code. To install Babel and it’s React companion, run the below command βˆ’ npm install babel-cli@6 babel-preset-react-app@3 -g ... ... + babel-cli@6.26.0 + babel-preset-react-app@3.1.2 updated 2 packages in 8.685s Babel helps us to write our application in next generation of advanced JavaScript syntax. Create React App is a modern CLI tool to create single page React application. It is the standard tool supported by React community. It handles babel compiler as well. Let us install Create React App in our local system. > npm install -g create-react-app + create-react-app@4.0.1 added 6 packages from 4 contributors, removed 37 packages and updated 12 packages in 4.693s React Create App toolchain uses the react-scripts package to build and run the application. Once we started working on the application, we can update the react-script to the latest version at any time using npm package manager. npm install react-scripts@latest React toolchain provides lot of features out of the box. Some of the advantages of using React toolchain are βˆ’ Predefined and standard structure of the application. Ready-made project template for different type of application. Development web server is included. Easy way to include third party React components. Default setup to test the application. React library is built on a solid foundation. It is simple, flexible and extensible. As we learned earlier, React is a library to create user interface in a web application. React’s primary purpose is to enable the developer to create user interface using pure JavaScript. Normally, every user interface library introduces a new template language (which we need to learn) to design the user interface and provides an option to write logic, either inside the template or separately. Instead of introducing new template language, React introduces three simple concepts as given below βˆ’ JavaScript representation of HTML DOM. React provides an API, React.createElement to create React Element. A JavaScript extension to design user interface. JSX is an XML based, extensible language supporting HTML syntax with little modification. JSX can be compiled to React Elements and used to create user interface. React component is the primary building block of the React application. It uses React elements and JSX to design its user interface. React component is basically a JavaScript class (extends the React.component class) or pure JavaScript function. React component has properties, state management, life cycle and event handler. React component can be able to do simple as well as advanced logic. Let us learn more about components in the React Component chapter. Let us understand the workflow of a React application in this chapter by creating and analyzing a simple React application. Open a command prompt and go to your workspace. cd /go/to/your/workspace Next, create a folder, static_site and change directory to newly created folder. mkdir static_site cd static_site Next, create a file, hello.html and write a simple React application. <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>React Application</title> </head> <body> <div id="react-app"></div> <script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script> <script language="JavaScript"> element = React.createElement('h1', {}, 'Hello React!') ReactDOM.render(element, document.getElementById('react-app')); </script> </body> </html> Next, serve the application using serve web server. serve ./hello.html Next, open your favorite browser. Enter http://localhost:5000 in the address bar and then press enter. Let us analyse the code and do little modification to better understand the React application. Here, we are using two API provided by the React library. Used to create React elements. It expects three parameters βˆ’ Element tag Element attributes as object Element content - It can contain nested React element as well Used to render the element into the container. It expects two parameters βˆ’ React Element OR JSX Root element of the webpage As React.createElement allows nested React element, let us add nested element as shown below βˆ’ Example <script language="JavaScript"> element = React.createElement('div', {}, React.createElement('h1', {}, 'Hello React!')); ReactDOM.render(element, document.getElementById('react-app')); </script> Output It will generate the below content βˆ’ <div><h1> Hello React!</h1></div> Next, let us remove the React element entirely and introduce JSX syntax as shown below βˆ’ <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>React Application</title> </head> <body> <div id="react-app"></div> <script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script> <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> <script type="text/babel"> ReactDOM.render( <div><h1>Hello React!</h1></div>, document.getElementById('react-app') ); </script> </body> </html> Here, we have included babel to convert JSX into JavaScript and added type=β€œtext/babel” in the script tag. <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> <script type="text/babel"> ... ... </script> Next, run the application and open the browser. The output of the application is as follows βˆ’ Next, let us create a new React component, Greeting and then try to use it in the webpage. <script type="text/babel"> function Greeting() { return <div><h1>Hello JSX!</h1></div> } ReactDOM.render(<Greeting />, document.getElementById('react-app') ); </script> The result is same and as shown below βˆ’ By analyzing the application, we can visualize the workflow of the React application as shown in the below diagram. React app calls ReactDOM.render method by passing the user interface created using React component (coded in either JSX or React element format) and the container to render the user interface. ReactDOM.render processes the JSX or React element and emits Virtual DOM. Virtual DOM will be merged and rendered into the container. React library is just UI library and it does not enforce any particular pattern to write a complex application. Developers are free to choose the design pattern of their choice. React community advocates certain design pattern. One of the patterns is Flux pattern. React library also provides lot of concepts like Higher Order component, Context, Render props, Refs etc., to write better code. React Hooks is evolving concept to do state management in big projects. Let us try to understand the high level architecture of a React application. React app starts with a single root component. React app starts with a single root component. Root component is build using one or more component. Root component is build using one or more component. Each component can be nested with other component to any level. Each component can be nested with other component to any level. Composition is one of the core concepts of React library. So, each component is build by composing smaller components instead of inheriting one component from another component. Composition is one of the core concepts of React library. So, each component is build by composing smaller components instead of inheriting one component from another component. Most of the components are user interface components. Most of the components are user interface components. React app can include third party component for specific purpose such as routing, animation, state management, etc. React app can include third party component for specific purpose such as routing, animation, state management, etc. As we learned earlier, React library can be used in both simple and complex application. Simple application normally includes the React library in its script section. In complex application, developers have to split the code into multiple files and organize the code into a standard structure. Here, React toolchain provides pre-defined structure to bootstrap the application. Also, developers are free to use their own project structure to organize the code. Let us see how to create simple as well as complex React application βˆ’ Simple application using CDN Simple application using CDN Complex application using React Create App cli Complex application using React Create App cli Complex application using customized method Complex application using customized method Rollup is one of the small and fast JavaScript bundlers. Let us learn how to use rollup bundler in this chapter. Open a terminal and go to your workspace. cd /go/to/your/workspace Next, create a folder, expense-manager-rollup and move to newly created folder. Also, open the folder in your favorite editor or IDE. mkdir expense-manager-rollup cd expense-manager-rollup Next, create and initialize the project. npm init -y Next, install React libraries (react and react-dom). npm install react@^17.0.0 react-dom@^17.0.0 --save Next, install babel and its preset libraries as development dependency. npm install @babel/preset-env @babel/preset-react @babel/core @babel/plugin-proposal-class-properties -D Next, install rollup and its plugin libraries as development dependency. npm i -D rollup postcss@8.1 @rollup/plugin-babel @rollup/plugin-commonjs @rollup/plugin-node-resolve @rollup/plugin-replace rollup-plugin-livereload rollup-plugin-postcss rollup-plugin-serve postcss@8.1 postcss-modules@4 rollup-plugin-postcss Next, install corejs and regenerator runtime for async programming. npm i regenerator-runtime core-js Next, create a babel configuration file, .babelrc under the root folder to configure the babel compiler. { "presets": [ [ "@babel/preset-env", { "useBuiltIns": "usage", "corejs": 3, "targets": "> 0.25%, not dead" } ], "@babel/preset-react" ], "plugins": [ "@babel/plugin-proposal-class-properties" ] } Next, create a rollup.config.js file in the root folder to configure the rollup bundler. import babel from '@rollup/plugin-babel'; import resolve from '@rollup/plugin-node-resolve'; import commonjs from '@rollup/plugin-commonjs'; import replace from '@rollup/plugin-replace'; import serve from 'rollup-plugin-serve'; import livereload from 'rollup-plugin-livereload'; import postcss from 'rollup-plugin-postcss' export default { input: 'src/index.js', output: { file: 'public/index.js', format: 'iife', }, plugins: [ commonjs({ include: [ 'node_modules/**', ], exclude: [ 'node_modules/process-es6/**', ], }), resolve(), babel({ exclude: 'node_modules/**' }), replace({ 'process.env.NODE_ENV': JSON.stringify('production'), }), postcss({ autoModules: true }), livereload('public'), serve({ contentBase: 'public', port: 3000, open: true, }), // index.html should be in root of project ] } Next, update the package.json and include our entry point (public/index.js and public/styles.css) and command to build and run the application. ... "main": "public/index.js", "style": "public/styles.css", "files": [ "public" ], "scripts": { "start": "rollup -c -w", "build": "rollup" }, ... Next, create a src folder in the root directory of the application, which will hold all the source code of the application. Next, create a folder, components under src to include our React components. The idea is to create two files, <component>.js to write the component logic and <component.css> to include the component specific styles. The final structure of the application will be as follows βˆ’ |-- package-lock.json |-- package.json |-- rollup.config.js |-- .babelrc `-- public |-- index.html `-- src |-- index.js `-- components | |-- mycom.js | |-- mycom.css Let us create a new component, HelloWorld to confirm our setup is working fine. Create a file, HelloWorld.js under components folder and write a simple component to emit Hello World message. import React from "react"; class HelloWorld extends React.Component { render() { return ( <div> <h1>Hello World!</h1> </div> ); } } export default HelloWorld; Next, create our main file, index.js under src folder and call our newly created component. import React from 'react'; import ReactDOM from 'react-dom'; import HelloWorld from './components/HelloWorld'; ReactDOM.render( <React.StrictMode> <HelloWorld /> </React.StrictMode>, document.getElementById('root') ); Next, create a public folder in the root directory. Next, create a html file, index.html (under public folder*), which will be our entry point of the application. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Expense Manager :: Rollup version</title> </head> <body> <div id="root"></div> <script type="text/JavaScript" src="./index.js"></script> </body> </html> Next, build and run the application. npm start The npm build command will execute the rollup and bundle our application into a single file, dist/index.js file and start serving the application. The dev command will recompile the code whenever the source code is changed and also reload the changes in the browser. > expense-manager-rollup@1.0.0 build /path/to/your/workspace/expense-manager-rollup > rollup -c rollup v2.36.1 bundles src/index.js β†’ dist\index.js... LiveReload enabled http://localhost:10001 -> /path/to/your/workspace/expense-manager-rollup/dist created dist\index.js in 4.7s waiting for changes... Next, open the browser and enter http://localhost:3000 in the address bar and press enter. serve application will serve our webpage as shown below. Parcel is fast bundler with zero configuration. It expects just the entry point of the application and it will resolve the dependency itself and bundle the application. Let us learn how to use parcel bundler in this chapter. First, install the parcel bundler. npm install -g parcel-bundler Open a terminal and go to your workspace. cd /go/to/your/workspace Next, create a folder, expense-manager-parcel and move to newly created folder. Also, open the folder in your favorite editor or IDE. mkdir expense-manager-parcel cd expense-manager-parcel Next, create and initialize the project. npm init -y Next, install React libraries (react and react-dom). npm install react@^17.0.0 react-dom@^17.0.0 --save Next, install babel and its preset libraries as development dependency. npm install @babel/preset-env @babel/preset-react @babel/core @babel/plugin-proposal-class-properties -D Next, create a babel configuration file, .babelrc under the root folder to configure the babel compiler. { "presets": [ "@babel/preset-env", "@babel/preset-react" ], "plugins": [ "@babel/plugin-proposal-class-properties" ] } Next, update the package.json and include our entry point (src/index.js) and commands to build and run the application. ... "main": "src/index.js", "scripts": { "start": "parcel public/index.html", "build": "parcel build public/index.html --out-dir dist" }, ... Next, create a src folder in the root directory of the application, which will hold all the source code of the application. Next, create a folder, components under src to include our React components. The idea is to create two files, <component>.js to write the component logic and <component.css> to include the component specific styles. The final structure of the application will be as follows βˆ’ |-- package-lock.json |-- package.json |-- .babelrc `-- public |-- index.html `-- src |-- index.js `-- components | |-- mycom.js | |-- mycom.css Let us create a new component, HelloWorld to confirm our setup is working fine. Create a file, HelloWorld.js under components folder and write a simple component to emit Hello World message. import React from "react"; class HelloWorld extends React.Component { render() { return ( <div> <h1>Hello World!</h1> </div> ); } } export default HelloWorld; Next, create our main file, index.js under src folder and call our newly created component. import React from 'react'; import ReactDOM from 'react-dom'; import HelloWorld from './components/HelloWorld'; ReactDOM.render( <React.StrictMode> <HelloWorld /> </React.StrictMode>, document.getElementById('root') ); Next, create a public folder in the root directory. Next, create a html file, index.html (in the public folder), which will be our entry point of the application. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Expense Manager :: Parcel version</title> </head> <body> <div id="root"></div> <script type="text/JavaScript" src="../src/index.js"></script> </body> </html> Next, build and run the application. npm start The npm build command will execute the parcel command. It will bundle and serve the application on the fly. It recompiles whenever the source code is changed and also reload the changes in the browser. > expense-manager-parcel@1.0.0 dev /go/to/your/workspace/expense-manager-parcel > parcel index.html Server running at http://localhost:1234 √ Built in 10.41s. Next, open the browser and enter http://localhost:1234 in the address bar and press enter. To create the production bundle of the application to deploy it in production server, use build command. It will generate a index.js file with all the bundled source code under dist folder. npm run build > expense-manager-parcel@1.0.0 build /go/to/your/workspace/expense-manager-parcel > parcel build index.html --out-dir dist √ Built in 6.42s. dist\src.80621d09.js.map 270.23 KB 79ms dist\src.80621d09.js 131.49 KB 4.67s dist\index.html 221 B 1.63s As we learned earlier, React JSX is an extension to JavaScript. It enables developer to create virtual DOM using XML syntax. It compiles down to pure JavaScript (React.createElement function calls). Since it compiles to JavaScript, it can be used inside any valid JavaScript code. For example, below codes are perfectly valid. Assign to a variable. var greeting = <h1>Hello React!</h1> Assign to a variable based on a condition. var canGreet = true; if(canGreet) { greeting = <h1>Hello React!</h1> } Can be used as return value of a function. function Greeting() { return <h1>Hello React!</h1> } greeting = Greeting() Can be used as argument of a function. function Greet(message) { ReactDOM.render(message, document.getElementById('react-app') } Greet(<h1>Hello React!</h1>) JSX supports expression in pure JavaScript syntax. Expression has to be enclosed inside the curly braces, { }. Expression can contain all variables available in the context, where the JSX is defined. Let us create simple JSX with expression. <script type="text/babel"> var cTime = new Date().toTimeString(); ReactDOM.render( <div><p>The current time is {cTime}</p></div>, document.getElementById('react-app') ); </script> Here, cTime used in the JSX using expression. The output of the above code is as follows, The Current time is 21:19:56 GMT+0530(India Standard Time) One of the positive side effects of using expression in JSX is that it prevents Injection attacks as it converts any string into html safe string. JSX supports user defined JavaScript function. Function usage is similar to expression. Let us create a simple function and use it inside JSX. <script type="text/babel"> var cTime = new Date().toTimeString(); ReactDOM.render( <div><p>The current time is {cTime}</p></div>, document.getElementById('react-app') ); </script> Here, getCurrentTime() is used get the current time and the output is similar as specified below βˆ’ The Current time is 21:19:56 GMT+0530(India Standard Time) JSX supports HTML like attributes. All HTML tags and its attributes are supported. Attributes has to be specified using camelCase convention (and it follows JavaScript DOM API) instead of normal HTML attribute name. For example, class attribute in HTML has to be defined as className. The following are few other examples βˆ’ htmlFor instead of for tabIndex instead of tabindex onClick instead of onclick <style> .red { color: red } </style> <script type="text/babel"> function getCurrentTime() { return new Date().toTimeString(); } ReactDOM.render( <div> <p>The current time is <span className="red">{getCurrentTime()}</span></p> </div>, document.getElementById('react-app') ); </script> The output is as follows βˆ’ The Current time is 22:36:55 GMT+0530(India Standard Time) JSX supports expression to be specified inside the attributes. In attributes, double quote should not be used along with expression. Either expression or string using double quote has to be used. The above example can be changed to use expression in attributes. <style> .red { color: red } </style> <script type="text/babel"> function getCurrentTime() { return new Date().toTimeString(); } var class_name = "red"; ReactDOM.render( <div> <p>The current time is <span className={class_name}>{getCurrentTime()}</span></p> </div>, document.getElementById('react-app') ); </script> React component is the building block of a React application. Let us learn how to create a new React component and the features of React components in this chapter. A React component represents a small chunk of user interface in a webpage. The primary job of a React component is to render its user interface and update it whenever its internal state is changed. In addition to rendering the UI, it manages the events belongs to its user interface. To summarize, React component provides below functionalities. Initial rendering of the user interface. Management and handling of events. Updating the user interface whenever the internal state is changed. React component accomplish these feature using three concepts βˆ’ Properties βˆ’ Enables the component to receive input. Properties βˆ’ Enables the component to receive input. Events βˆ’ Enable the component to manage DOM events and end-user interaction. Events βˆ’ Enable the component to manage DOM events and end-user interaction. State βˆ’ Enable the component to stay stateful. Stateful component updates its UI with respect to its state. State βˆ’ Enable the component to stay stateful. Stateful component updates its UI with respect to its state. Let us learn all the concept one-by-one in the upcoming chapters. React library has two component types. The types are categorized based on the way it is being created. Function component βˆ’ Uses plain JavaScript function. ES6 class component βˆ’ Uses ES6 class. The core difference between function and class component are βˆ’ Function components are very minimal in nature. Its only requirement is to return a React element. Function components are very minimal in nature. Its only requirement is to return a React element. function Hello() { return '<div>Hello</div>' } The same functionality can be done using ES6 class component with little extra coding. class ExpenseEntryItem extends React.Component { render() { return ( <div>Hello</div> ); } } Class components supports state management out of the box whereas function components does not support state management. But, React provides a hook, useState() for the function components to maintain its state. Class components supports state management out of the box whereas function components does not support state management. But, React provides a hook, useState() for the function components to maintain its state. Class component have a life cycle and access to each life cycle events through dedicated callback apis. Function component does not have life cycle. Again, React provides a hook, useEffect() for the function component to access different stages of the component. Class component have a life cycle and access to each life cycle events through dedicated callback apis. Function component does not have life cycle. Again, React provides a hook, useEffect() for the function component to access different stages of the component. Let us create a new React component (in our expense-manager app), ExpenseEntryItem to showcase an expense entry item. Expense entry item consists of name, amount, date and category. The object representation of the expense entry item is βˆ’ { 'name': 'Mango juice', 'amount': 30.00, 'spend_date': '2020-10-10' 'category': 'Food', } Open expense-manager application in your favorite editor. Next, create a file, ExpenseEntryItem.css under src/components folder to style our component. Next, create a file, ExpenseEntryItem.js under src/components folder by extending React.Component. import React from 'react'; import './ExpenseEntryItem.css'; class ExpenseEntryItem extends React.Component { } Next, create a method render inside the ExpenseEntryItem class. class ExpenseEntryItem extends React.Component { render() { } } Next, create the user interface using JSX and return it from render method. class ExpenseEntryItem extends React.Component { render() { return ( <div> <div><b>Item:</b> <em>Mango Juice</em></div> <div><b>Amount:</b> <em>30.00</em></div> <div><b>Spend Date:</b> <em>2020-10-10</em></div> <div><b>Category:</b> <em>Food</em></div> </div> ); } } Next, specify the component as default export class. import React from 'react'; import './ExpenseEntryItem.css'; class ExpenseEntryItem extends React.Component { render() { return ( <div> <div><b>Item:</b> <em>Mango Juice</em></div> <div><b>Amount:</b> <em>30.00</em></div> <div><b>Spend Date:</b> <em>2020-10-10</em></div> <div><b>Category:</b> <em>Food</em></div> </div> ); } } export default ExpenseEntryItem; Now, we successfully created our first React component. Let us use our newly created component in index.js. import React from 'react'; import ReactDOM from 'react-dom'; import ExpenseEntryItem from './components/ExpenseEntryItem' ReactDOM.render( <React.StrictMode> <ExpenseEntryItem /> </React.StrictMode>, document.getElementById('root') ); The same functionality can be done in a webpage using CDN as shown below βˆ’ <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>React application :: ExpenseEntryItem component</title> </head> <body> <div id="react-app"></div> <script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script> <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> <script type="text/babel"> class ExpenseEntryItem extends React.Component { render() { return ( <div> <div><b>Item:</b> <em>Mango Juice</em></div> <div><b>Amount:</b> <em>30.00</em></div> <div><b>Spend Date:</b> <em>2020-10-10</em></div> <div><b>Category:</b> <em>Food</em></div> </div> ); } } ReactDOM.render( <ExpenseEntryItem />, document.getElementById('react-app') ); </script> </body> </html> Next, serve the application using npm command. npm start Next, open the browser and enter http://localhost:3000 in the address bar and press enter. Item: Mango Juice Amount: 30.00 Spend Date: 2020-10-10 Category: Food React component can also be created using plain JavaScript function but with limited features. Function based React component does not support state management and other advanced features. It can be used to quickly create a simple component. The above ExpenseEntryItem can be rewritten in function as specified below βˆ’ function ExpenseEntryItem() { return ( <div> <div><b>Item:</b> <em>Mango Juice</em></div> <div><b>Amount:</b> <em>30.00</em></div> <div><b>Spend Date:</b> <em>2020-10-10</em></div> <div><b>Category:</b> <em>Food</em></div> </div> ); } Here, we just included the render functionality and it is enough to create a simple React component. In general, React allows component to be styled using CSS class through className attribute. Since, the React JSX supports JavaScript expression, a lot of common CSS methodology can be used. Some of the top options are as follows βˆ’ CSS stylesheet βˆ’ Normal CSS styles along with className CSS stylesheet βˆ’ Normal CSS styles along with className Inline styling βˆ’ CSS styles as JavaScript objects along with camelCase properties. Inline styling βˆ’ CSS styles as JavaScript objects along with camelCase properties. CSS Modules βˆ’ Locally scoped CSS styles. CSS Modules βˆ’ Locally scoped CSS styles. Styled component βˆ’ Component level styles. Styled component βˆ’ Component level styles. Sass stylesheet βˆ’ Supports Sass based CSS styles by converting the styles to normal css at build time. Sass stylesheet βˆ’ Supports Sass based CSS styles by converting the styles to normal css at build time. Post processing stylesheet βˆ’ Supports Post processing styles by converting the styles to normal css at build time. Post processing stylesheet βˆ’ Supports Post processing styles by converting the styles to normal css at build time. Let use learn how to apply the three important methodology to style our component in this chapter. CSS Stylesheet CSS Stylesheet Inline Styling Inline Styling CSS Modules CSS Modules CSS stylesheet is usual, common and time-tested methodology. Simply create a CSS stylesheet for a component and enter all your styles for that particular component. Then, in the component, use className to refer the styles. Let us style our ExpenseEntryItem component. Open expense-manager application in your favorite editor. Next, open ExpenseEntryItem.css file and add few styles. div.itemStyle { color: brown; font-size: 14px; } Next, open ExpenseEntryItem.js and add className to the main container. import React from 'react'; import './ExpenseEntryItem.css'; class ExpenseEntryItem extends React.Component { render() { return ( <div className="itemStyle"> <div><b>Item:</b> <em>Mango Juice</em></div> <div><b>Amount:</b> <em>30.00</em></div> <div><b>Spend Date:</b> <em>2020-10-10</em></div> <div><b>Category:</b> <em>Food</em></div> </div> ); } } export default ExpenseEntryItem; Next, serve the application using npm command. npm start Next, open the browser and enter http://localhost:3000 in the address bar and press enter. CSS stylesheet is easy to understand and use. But, when the project size increases, CSS styles will also increase and ultimately create lot of conflict in the class name. Moreover, loading the CSS file directly is only supported in Webpack bundler and it may not supported in other tools. Inline Styling is one of the safest ways to style the React component. It declares all the styles as JavaScript objects using DOM based css properties and set it to the component through style attributes. Let us add inline styling in our component. Open expense-manager application in your favorite editor and modify ExpenseEntryItem.js file in the src folder. Declare a variable of type object and set the styles. itemStyle = { color: 'brown', fontSize: '14px' } Here, fontSize represent the css property, font-size. All css properties can be used by representing it in camelCase format. Next, set itemStyle style in the component using curly braces {} βˆ’ render() { return ( <div style={ this.itemStyle }> <div><b>Item:</b> <em>Mango Juice</em></div> <div><b>Amount:</b> <em>30.00</em></div> <div><b>Spend Date:</b> <em>2020-10-10</em></div> <div><b>Category:</b> <em>Food</em></div> </div> ); } Also, style can be directly set inside the component βˆ’ render() { return ( <div style={ { color: 'brown', fontSize: '14px' } }> <div><b>Item:</b> <em>Mango Juice</em></div> <div><b>Amount:</b> <em>30.00</em></div> <div><b>Spend Date:</b> <em>2020-10-10</em></div> <div><b>Category:</b> <em>Food</em></div> </div> ); } Now, we have successfully used the inline styling in our application. Next, serve the application using npm command. npm start Next, open the browser and enter http://localhost:3000 in the address bar and press enter. Css Modules provides safest as well as easiest way to define the style. It uses normal css stylesheet with normal syntax. While importing the styles, CSS modules converts all the styles into locally scoped styles so that the name conflicts will not happen. Let us change our component to use CSS modules Open expense-manager application in your favorite editor. Next, create a new stylesheet, ExpenseEntryItem.module.css file under src/components folder and write regular css styles. div.itemStyle { color: 'brown'; font-size: 14px; } Here, file naming convention is very important. React toolchain will pre-process the css files ending with .module.css through CSS Module. Otherwise, it will be considered as a normal stylesheet. Next, open ExpenseEntryItem.js file in the src/component folder and import the styles. import styles from './ExpenseEntryItem.module.css' Next, use the styles as JavaScript expression in the component. <div className={styles.itemStyle}> Now, we have successfully used the CSS modules in our application. The final and complete code is βˆ’ import React from 'react'; import './ExpenseEntryItem.css'; import styles from './ExpenseEntryItem.module.css' class ExpenseEntryItem extends React.Component { render() { return ( <div className={styles.itemStyle} > <div><b>Item:</b> <em>Mango Juice</em></div> <div><b>Amount:</b> <em>30.00</em></div> <div><b>Spend Date:</b> <em>2020-10-10</em></div> <div><b>Category:</b> <em>Food</em></div> </div> ); } } export default ExpenseEntryItem; Next, serve the application using npm command. npm start Next, open the browser and enter http://localhost:3000 in the address bar and press enter. React enables developers to create dynamic and advanced component using properties. Every component can have attributes similar to HTML attributes and each attribute’s value can be accessed inside the component using properties (props). For example, Hello component with a name attribute can be accessed inside the component through this.props.name variable. <Hello name="React" /> // value of name will be "Hello* const name = this.props.name React properties supports attribute’s value of different types. They are as follows, String Number Datetime Array List Objects Let us learn one by one in this chapter. Create a component using Properties Create a component using Properties Nested Components Nested Components Use Component Use Component Component Collection Component Collection Event management is one of the important features in a web application. It enables the user to interact with the application. React support all events available in a web application. React event handling is very similar to DOM events with little changes. Let us learn how to handle events in a React application in this chapter. Let us see the step-by-step process of handling an event in a React component. Define an event handler method to handle the given event. Define an event handler method to handle the given event. log() { cosole.log("Event is fired"); } React provides an alternative syntax using lambda function to define event handler. The lambda syntax is βˆ’ log = () =;> { cosole.log("Event is fired"); } If you want to know the target of the event, then add an argument e in the handler method. React will send the event target details to the handler method. log(e) { cosole.log("Event is fired"); console.log(e.target); } The alternative lambda syntax is βˆ’ log = (e) => { cosole.log("Event is fired"); console.log(e.target); } If you want to send extra details during an event, then add the extra details as initial argument and then add argument (e) for event target. log(extra, e) { cosole.log("Event is fired"); console.log(e.target); console.log(extra); console.log(this); } The alternative lambda syntax is as follows βˆ’ log = (extra, e) => { cosole.log("Event is fired"); console.log(e.target); console.log(extra); console.log(this); } Bind the event handler method in the constructor of the component. This will ensure the availability of this in the event handler method. constructor(props) { super(props); this.logContent = this.logContent.bind(this); } If the event handler is defined in alternate lambda syntax, then the binding is not needed. this keyword will be automatically bound to the event handler method. Set the event handler method for the specific event as specified below βˆ’ <div onClick={this.log}> ... </div> To set extra arguments, bind the event handler method and then pass the extra information as second argument. <div onClick={this.log.bind(this, extra)}> ... </div> The alternate lambda syntax is as follows βˆ’ <div onClick={this.log(extra, e)}> ... </div> Here, Create a event-aware component Create a event-aware component Introduce events in Expense manager app Introduce events in Expense manager app State management is one of the important and unavoidable features of any dynamic application. React provides a simple and flexible API to support state management in a React component. Let us understand how to maintain state in React application in this chapter. State represents the value of a dynamic properties of a React component at a given instance. React provides a dynamic data store for each component. The internal data represents the state of a React component and can be accessed using this.state member variable of the component. Whenever the state of the component is changed, the component will re-render itself by calling the render() method along with the new state. A simple example to better understand the state management is to analyse a real-time clock component. The clock component primary job is to show the date and time of a location at the given instance. As the current time will change every second, the clock component should maintain the current date and time in it’s state. As the state of the clock component changes every second, the clock’s render() method will be called every second and the render() method show the current time using it’s current state. The simple representation of the state is as follows βˆ’ { date: '2020-10-10 10:10:10' } Let us create a new Clock component later in this chapter. Here, State management API State management API Stateless component Stateless component State management using React Hooks State management using React Hooks Component Life cycle Component Life cycle Component life cycle using React Hooks Component life cycle using React Hooks Layout in component Layout in component Pagination Pagination Material UI Material UI Http client programming enables the application to connect and fetch data from http server through JavaScript. It reduces the data transfer between client and server as it fetches only the required data instead of the whole design and subsequently improves the network speed. It improves the user experience and becomes an indispensable feature of every modern web application. Nowadays, lot of server side application exposes its functionality through REST API (functionality over HTTP protocol) and allows any client application to consume the functionality. React does not provide it’s own http programming api but it supports browser’s built-in fetch() api as well as third party client library like axios to do client side programming. Let us learn how to do http programming in React application in this chapter. Developer should have a basic knowledge in Http programming to understand this chapter. The prerequisite to do Http programming is the basic knowledge of Http protocol and REST API technique. Http programming involves two part, server and client. React provides support to create client side application. Express a popular web framework provides support to create server side application. Let us first create a Expense Rest Api server using express framework and then access it from our ExpenseManager application using browser’s built-in fetch api. Open a command prompt and create a new folder, express-rest-api. cd /go/to/workspace mkdir apiserver cd apiserver Initialize a new node application using the below command βˆ’ npm init The npm init will prompt and ask us to enter basic project details. Let us enter apiserver for project name and server.js for entry point. Leave other configuration with default option. This utility will walk you through creating a package.json file. It only covers the most common items, and tries to guess sensible defaults. See `npm help json` for definitive documentation on these fields and exactly what they do. Use `npm install <pkg>` afterwards to install a package and save it as a dependency in the package.json file. Press ^C at any time to quit. package name: (apiserver) version: (1.0.0) description: Rest api for Expense Application entry point: (index.js) server.js test command: git repository: keywords: author: license: (ISC) About to write to \path\to\workspace\expense-rest-api\package.json: { "name": "expense-rest-api", "version": "1.0.0", "description": "Rest api for Expense Application", "main": "server.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC" } Is this OK? (yes) yes Next, install express, nedb & cors modules using below command βˆ’ npm install express nedb cors express is used to create server side application. express is used to create server side application. nedb is a datastore used to store the expense data. nedb is a datastore used to store the expense data. cors is a middleware for express framework to configure the client access details. cors is a middleware for express framework to configure the client access details. Next, let us create a file, data.csv and populate it with initial expense data for testing purposes. The structure of the file is that it contains one expense entry per line. Pizza,80,2020-10-10,Food Grape Juice,30,2020-10-12,Food Cinema,210,2020-10-16,Entertainment Java Programming book,242,2020-10-15,Academic Mango Juice,35,2020-10-16,Food Dress,2000,2020-10-25,Cloth Tour,2555,2020-10-29,Entertainment Meals,300,2020-10-30,Food Mobile,3500,2020-11-02,Gadgets Exam Fees,1245,2020-11-04,Academic Next, create a file expensedb.js and include code to load the initial expense data into the data store. The code checks the data store for initial data and load only if the data is not available in the store. var store = require("nedb") var fs = require('fs'); var expenses = new store({ filename: "expense.db", autoload: true }) expenses.find({}, function (err, docs) { if (docs.length == 0) { loadExpenses(); } }) function loadExpenses() { readCsv("data.csv", function (data) { console.log(data); data.forEach(function (rec, idx) { item = {} item.name = rec[0]; item.amount = parseFloat(rec[1]); item.spend_date = new Date(rec[2]); item.category = rec[3]; expenses.insert(item, function (err, doc) { console.log('Inserted', doc.item_name, 'with ID', doc._id); }) }) }) } function readCsv(file, callback) { fs.readFile(file, 'utf-8', function (err, data) { if (err) throw err; var lines = data.split('\r\n'); var result = lines.map(function (line) { return line.split(','); }); callback(result); }); } module.exports = expenses Next, create a file, server.js and include the actual code to list, add, update and delete the expense entries. var express = require("express") var cors = require('cors') var expenseStore = require("./expensedb.js") var app = express() app.use(cors()); var bodyParser = require("body-parser"); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); var HTTP_PORT = 8000 app.listen(HTTP_PORT, () => { console.log("Server running on port %PORT%".replace("%PORT%", HTTP_PORT)) }); app.get("/", (req, res, next) => { res.json({ "message": "Ok" }) }); app.get("/api/expenses", (req, res, next) => { expenseStore.find({}, function (err, docs) { res.json(docs); }); }); app.get("/api/expense/:id", (req, res, next) => { var id = req.params.id; expenseStore.find({ _id: id }, function (err, docs) { res.json(docs); }) }); app.post("/api/expense/", (req, res, next) => { var errors = [] if (!req.body.item) { errors.push("No item specified"); } var data = { name: req.body.name, amount: req.body.amount, category: req.body.category, spend_date: req.body.spend_date, } expenseStore.insert(data, function (err, docs) { return res.json(docs); }); }) app.put("/api/expense/:id", (req, res, next) => { var id = req.params.id; var errors = [] if (!req.body.item) { errors.push("No item specified"); } var data = { _id: id, name: req.body.name, amount: req.body.amount, category: req.body.category, spend_date: req.body.spend_date, } expenseStore.update( { _id: id }, data, function (err, docs) { return res.json(data); }); }) app.delete("/api/expense/:id", (req, res, next) => { var id = req.params.id; expenseStore.remove({ _id: id }, function (err, numDeleted) { res.json({ "message": "deleted" }) }); }) app.use(function (req, res) { res.status(404); }); Now, it is time to run the application. npm run start Next, open a browser and enter http://localhost:8000/ in the address bar. { "message": "Ok" } It confirms that our application is working fine. Finally, change the url to http://localhost:8000/api/expense and press enter. The browser will show the initial expense entries in JSON format. [ ... { "name": "Pizza", "amount": 80, "spend_date": "2020-10-10T00:00:00.000Z", "category": "Food", "_id": "5H8rK8lLGJPVZ3gD" }, ... ] Let us use our newly created expense server in our Expense manager application through fetch() api in the upcoming section. Let us create a new application to showcase client side programming in React. First, create a new react application, react-http-app using Create React App or Rollup bundler by following instruction in Creating a React application chapter. Next, open the application in your favorite editor. Next, create src folder under the root directory of the application. Next, create components folder under src folder. Next, create a file, ExpenseEntryItemList.css under src/components folder and include generic table styles. html { font-family: sans-serif; } table { border-collapse: collapse; border: 2px solid rgb(200,200,200); letter-spacing: 1px; font-size: 0.8rem; } td, th { border: 1px solid rgb(190,190,190); padding: 10px 20px; } th { background-color: rgb(235,235,235); } td, th { text-align: left; } tr:nth-child(even) td { background-color: rgb(250,250,250); } tr:nth-child(odd) td { background-color: rgb(245,245,245); } caption { padding: 10px; } tr.highlight td { background-color: #a6a8bd; } Next, create a file, ExpenseEntryItemList.js under src/components folder and start editing. Next, import React library. import React from 'react'; Next, create a class, ExpenseEntryItemList and call constructor with props. class ExpenseEntryItemList extends React.Component { constructor(props) { super(props); } } Next, initialize the state with empty list in the constructor. this.state = { isLoaded: false, items: [] } Next, create a method, setItems to format the items received from remote server and then set it into the state of the component. setItems(remoteItems) { var items = []; remoteItems.forEach((item) => { let newItem = { id: item._id, name: item.name, amount: item.amount, spendDate: item.spend_date, category: item.category } items.push(newItem) }); this.setState({ isLoaded: true, items: items }); } Next, add a method, fetchRemoteItems to fetch the items from the server. fetchRemoteItems() { fetch("http://localhost:8000/api/expenses") .then(res => res.json()) .then( (result) => { this.setItems(result); }, (error) => { this.setState({ isLoaded: false, error }); } ) } Here, fetch api is used to fetch the item from the remote server. fetch api is used to fetch the item from the remote server. setItems is used to format and store the items in the state. setItems is used to format and store the items in the state. Next, add a method, deleteRemoteItem to delete the item from the remote server. deleteRemoteItem(id) { fetch('http://localhost:8000/api/expense/' + id, { method: 'DELETE' }) .then(res => res.json()) .then( () => { this.fetchRemoteItems() } ) } Here, fetch api is used to delete and fetch the item from the remote server. fetch api is used to delete and fetch the item from the remote server. setItems is again used to format and store the items in the state. setItems is again used to format and store the items in the state. Next, call the componentDidMount life cycle api to load the items into the component during its mounting phase. componentDidMount() { this.fetchRemoteItems(); } Next, write an event handler to remove the item from the list. handleDelete = (id, e) => { e.preventDefault(); console.log(id); this.deleteRemoteItem(id); } Next, write the render method. render() { let lists = []; if (this.state.isLoaded) { lists = this.state.items.map((item) => <tr key={item.id} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}> <td>{item.name}</td> <td>{item.amount}</td> <td>{new Date(item.spendDate).toDateString()}</td> <td>{item.category}</td> <td><a href="#" onClick={(e) => this.handleDelete(item.id, e)}>Remove</a></td> </tr> ); } return ( <div> <table onMouseOver={this.handleMouseOver}> <thead> <tr> <th>Item</th> <th>Amount</th> <th>Date</th> <th>Category</th> <th>Remove</th> </tr> </thead> <tbody> {lists} </tbody> </table> </div> ); } Finally, export the component. export default ExpenseEntryItemList; Next, create a file, index.js under the src folder and use ExpenseEntryItemList component. import React from 'react'; import ReactDOM from 'react-dom'; import ExpenseEntryItemList from './components/ExpenseEntryItemList'; ReactDOM.render( <React.StrictMode> <ExpenseEntryItemList /> </React.StrictMode>, document.getElementById('root') ); Finally, create a public folder under the root folder and create index.html file. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>React App</title> </head> <body> <div id="root"></div> <script type="text/JavaScript" src="./index.js"></script> </body> </html> Next, open a new terminal window and start our server application. cd /go/to/server/application npm start Next, serve the client application using npm command. npm start Next, open the browser and enter http://localhost:3000 in the address bar and press enter. Try to remove the item by clicking the remove link. The nature of form programming needs the state to be maintained. Because, the input field information will get changed as the user interacts with the form. But as we learned earlier, React library does not store or maintain any state information by itself and component has to use state management api to manage state. Considering this, React provides two types of components to support form programming. Controlled component βˆ’ In controlled component, React provides a special attribute, value for all input elements and controls the input elements. The value attribute can be used to get and set the value of the input element. It has to be in sync with state of the component. Controlled component βˆ’ In controlled component, React provides a special attribute, value for all input elements and controls the input elements. The value attribute can be used to get and set the value of the input element. It has to be in sync with state of the component. Uncontrolled component βˆ’ In uncontrolled component, React provides minimal support for form programming. It has to use Ref concept (another react concept to get a DOM element in the React component during runtime) to do the form programming. Uncontrolled component βˆ’ In uncontrolled component, React provides minimal support for form programming. It has to use Ref concept (another react concept to get a DOM element in the React component during runtime) to do the form programming. Let us learn the form programming using controlled as well as uncontrolled component in this chapter. Controlled component Controlled component Uncontrolled Component Uncontrolled Component Formik Formik In web application, Routing is a process of binding a web URL to a specific resource in the web application. In React, it is binding an URL to a component. React does not support routing natively as it is basically an user interface library. React community provides many third party component to handle routing in the React application. Let us learn React Router, a top choice routing library for React application. Let us learn how to install React Router component in our Expense Manager application. Open a command prompt and go to the root folder of our application. cd /go/to/expense/manager Install the react router using below command. npm install react-router-dom --save React router provides four components to manage navigation in React application. Router βˆ’ Router is th top level component. It encloses the entire application. Link βˆ’ Similar to anchor tag in html. It sets the target url along with reference text. <Link to="/">Home</Link> Here, to attribute is used to set the target url. Switch & Route βˆ’ Both are used together. Maps the target url to the component. Switch is the parent component and Route is the child component. Switch component can have multiple Route component and each Route component mapping a particular url to a component. <Switch> <Route exact path="/"> <Home /> </Route> <Route path="/home"> <Home /> </Route> <Route path="/list"> <ExpenseEntryItemList /> </Route> </Switch> Here, path attribute is used to match the url. Basically, Switch works similar to traditional switch statement in a programming language. It matches the target url with each child route (path attribute) one by one in sequence and invoke the first matched route. Along with router component, React router provides option to get set and get dynamic information from the url. For example, in an article website, the url may have article type attached to it and the article type needs to be dynamically extracted and has to be used to fetch the specific type of articles. <Link to="/article/c">C Programming</Link> <Link to="/article/java">Java Programming</Link> ... ... <Switch> <Route path="article/:tag" children={<ArticleList />} /> </Switch> Then, in the child component (class component), import { withRouter } from "react-router" class ArticleList extends React.Component { ... ... static getDerivedStateFromProps(props, state) { let newState = { tag: props.match.params.tag } return newState; } ... ... } export default WithRouter(ArticleList) Here, WithRouter enables ArticleList component to access the tag information through props. The same can be done differently in functional components βˆ’ function ArticleList() { let { tag } = useParams(); return ( <div> <h3>ID: {id}</h3> </div> ); } Here, useParams is a custom React Hooks provided by React Router component. React router supports nested routing as well. React router provides another React Hooks, useRouteMatch() to extract parent route information in nested routes. function ArticleList() { // get the parent url and the matched path let { path, url } = useRouteMatch(); return ( <div> <h2>Articles</h2> <ul> <li> <Link to={`${url}/pointer`}>C with pointer</Link> </li> <li> <Link to={`${url}/basics`}>C basics</Link> </li> </ul> <Switch> <Route exact path={path}> <h3>Please select an article.</h3> </Route> <Route path={`${path}/:article`}> <Article /> </Route> </Switch> </div> ); } function Article() { let { article } = useParams(); return ( <div> <h3>The select article is {article}</h3> </div> ); } Here, useRouteMatch returns the matched path and the target url. url can be used to create next level of links and path can be used to map next level of components / screens. Let us learn how to do routing by creating the possible routing in our expense manager application. The minimum screens of the application are given below βˆ’ Home screen βˆ’ Landing or initial screen of the application Home screen βˆ’ Landing or initial screen of the application Expense list screen βˆ’ Shows the expense items in a tabular format Expense list screen βˆ’ Shows the expense items in a tabular format Expense add screen βˆ’ Add interface to add an expense item Expense add screen βˆ’ Add interface to add an expense item First, create a new react application, react-router-app using Create React App or Rollup bundler by following instruction in Creating a React application chapter. Next, open the application in your favorite editor. Next, create src folder under the root directory of the application. Next, create components folder under src folder. Next, create a file, Home.js under src/components folder and start editing. Next, import React library. import React from 'react'; Next, import Link from React router library. import { Link } from 'react-router-dom' Next, create a class, Home and call constructor with props. class Home extends React.Component { constructor(props) { super(props); } } Next, add render() method and show the welcome message and links to add and list expense screen. render() { return ( <div> <p>Welcome to the React tutorial</p> <p><Link to="/list">Click here</Link> to view expense list</p> <p><Link to="/add">Click here</Link> to add new expenses</p> </div> ) } Finally, export the component. export default Home; The complete source code of the Home component is given below βˆ’ import React from 'react'; import { Link } from 'react-router-dom' class Home extends React.Component { constructor(props) { super(props); } render() { return ( <div> <p>Welcome to the React tutorial</p> <p><Link to="/list">Click here</Link> to view expense list</p> <p><Link to="/add">Click here</Link> to add new expenses</p> </div> ) } } export default Home; Next, create ExpenseEntryItemList.js file under src/components folder and create ExpenseEntryItemList component. import React from 'react'; import { Link } from 'react-router-dom' class ExpenseEntryItemList extends React.Component { constructor(props) { super(props); } render() { return ( <div> <h1>Expenses</h1> <p><Link to="/add">Click here</Link> to add new expenses</p> <div> Expense list </div> </div> ) } } export default ExpenseEntryItemList; Next, create ExpenseEntryItemForm.js file under src/components folder and create ExpenseEntryItemForm component. import React from 'react'; import { Link } from 'react-router-dom' class ExpenseEntryItemForm extends React.Component { constructor(props) { super(props); } render() { return ( <div> <h1>Add Expense item</h1> <p><Link to="/list">Click here</Link> to view new expense list</p> <div> Expense form </div> </div> ) } } export default ExpenseEntryItemForm; Next, create a file, App.css under src/components folder and add generic css styles. html { font-family: sans-serif; } a{ text-decoration: none; } p, li, a{ font-size: 14px; } nav ul { width: 100%; list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: rgb(235,235,235); } nav li { float: left; } nav li a { display: block; color: black; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 16px; } nav li a:hover { background-color: rgb(187, 202, 211); } Next, create a file, App.js under src/components folder and start editing. The purpose of the App component is to handle all the screen in one component. It will configure routing and enable navigation to all other components. Next, import React library and other components. import React from 'react'; import Home from './Home' import ExpenseEntryItemList from './ExpenseEntryItemList' import ExpenseEntryItemForm from './ExpenseEntryItemForm' import './App.css' Next, import React router components. import { BrowserRouter as Router, Link, Switch, Route } from 'react-router-dom' Next, write the render() method and configure routing. function App() { return ( <Router> <div> <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/list">List Expenses</Link> </li> <li> <Link to="/add">Add Expense</Link> </li> </ul> </nav> <Switch> <Route path="/list"> <ExpenseEntryItemList /> </Route> <Route path="/add"> <ExpenseEntryItemForm /> </Route> <Route path="/"> <Home /> </Route> </Switch> </div> </Router> ); } Next, create a file, index.js under the src folder and use App component. import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/App'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root') ); Finally, create a public folder under the root folder and create index.html file. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>React router app</title> </head> <body> <div id="root"></div> <script type="text/JavaScript" src="./index.js"></script> </body> </html> Next, serve the application using npm command. npm start Next, open the browser and enter http://localhost:3000 in the address bar and press enter. Try to navigate the links and confirm that the routing is working. React redux is an advanced state management library for React. As we learned earlier, React only supports component level state management. In a big and complex application, large number of components are used. React recommends to move the state to the top level component and pass the state to the nested component using properties. It helps to some extent but it becomes complex when the components increases. React redux chips in and helps to maintain state at the application level. React redux allows any component to access the state at any time. Also, it allows any component to change the state of the application at any time. Let us learn about the how to write a React application using React redux in this chapter. React redux maintains the state of the application in a single place called Redux store. React component can get the latest state from the store as well as change the state at any time. Redux provides a simple process to get and set the current state of the application and involves below concepts. Store βˆ’ The central place to store the state of the application. Actions βˆ’ Action is an plain object with the type of the action to be done and the input (called payload) necessary to do the action. For example, action for adding an item in the store contains ADD_ITEM as type and an object with item’s details as payload. The action can be represented as βˆ’ { type: 'ADD_ITEM', payload: { name: '..', ... } } Reducers βˆ’ Reducers are pure functions used to create a new state based on the existing state and the current action. It returns the newly created state. For example, in add item scenario, it creates a new item list and merges the item from the state and new item and returns the newly created list. Action creators βˆ’ Action creator creates an action with proper action type and data necessary for the action and returns the action. For example, addItem action creator returns below object βˆ’ { type: 'ADD_ITEM', payload: { name: '..', ... } } Component βˆ’ Component can connect to the store to get the current state and dispatch action to the store so that the store executes the action and updates it’s current state. The workflow of a typical redux store can be represented as shown below. React component subscribes to the store and get the latest state during initialization of the application. To change the state, React component creates necessary action and dispatches the action. Reducer creates a new state based on the action and returns it. Store updates itself with the new state. Once the state changes, store sends the updated state to all its subscribed component. Redux provides a single api, connect which will connect a components to the store and allows the component to get and set the state of the store. The signature of the connect API is βˆ’ function connect(mapStateToProps?, mapDispatchToProps?, mergeProps?, options?) All parameters are optional and it returns a HOC (higher order component). A higher order component is a function which wraps a component and returns a new component. let hoc = connect(mapStateToProps, mapDispatchToProps) let connectedComponent = hoc(component) Let us see the first two parameters which will be enough for most cases. mapStateToProps βˆ’ Accepts a function with below signature. mapStateToProps βˆ’ Accepts a function with below signature. (state, ownProps?) => Object Here, state refers current state of the store and Object refers the new props of the component. It gets called whenever the state of the store is updated. (state) => { prop1: this.state.anyvalue } mapDispatchToProps βˆ’ Accepts a function with below signature. mapDispatchToProps βˆ’ Accepts a function with below signature. Object | (dispatch, ownProps?) => Object Here, dispatch refers the dispatch object used to dispatch action in the redux store and Object refers one or more dispatch functions as props of the component. (dispatch) => { addDispatcher: (dispatch) => dispatch({ type: 'ADD_ITEM', payload: { } }), removeispatcher: (dispatch) => dispatch({ type: 'REMOVE_ITEM', payload: { } }), } React Redux provides a Provider component and its sole purpose to make the Redux store available to its all nested components connected to store using connect API. The sample code is given below βˆ’ import React from 'react' import ReactDOM from 'react-dom' import { Provider } from 'react-redux' import { App } from './App' import createStore from './createReduxStore' const store = createStore() ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') ) Now, all the component inside the App component can get access to the Redux store by using connect API. Let us recreate our expense manager application and uses the React redux concept to maintain the state of the application. First, create a new react application, react-message-app using Create React App or Rollup bundler by following instruction in Creating a React application chapter. Next, install Redux and React redux library. npm install redux react-redux --save Next, install uuid library to generate unique identifier for new expenses. npm install uuid --save Next, open the application in your favorite editor. Next, create src folder under the root directory of the application. Next, create actions folder under src folder. Next, create a file, types.js under src/actions folder and start editing. Next, add two action type, one for add expense and one for remove expense. export const ADD_EXPENSE = 'ADD_EXPENSE'; export const DELETE_EXPENSE = 'DELETE_EXPENSE'; Next, create a file, index.js under src/actions folder to add action and start editing. Next, import uuid to create unique identifier. import { v4 as uuidv4 } from 'uuid'; Next, import action types. import { ADD_EXPENSE, DELETE_EXPENSE } from './types'; Next, add a new function to return action type for adding an expense and export it. export const addExpense = ({ name, amount, spendDate, category }) => ({ type: ADD_EXPENSE, payload: { id: uuidv4(), name, amount, spendDate, category } }); Here, the function expects expense object and return action type of ADD_EXPENSE along with a payload of expense information. Next, add a new function to return action type for deleting an expense and export it. export const deleteExpense = id => ({ type: DELETE_EXPENSE, payload: { id } }); Here, the function expects id of the expense item to be deleted and return action type of β€˜DELETE_EXPENSE’ along with a payload of expense id. The complete source code of the action is given below βˆ’ import { v4 as uuidv4 } from 'uuid'; import { ADD_EXPENSE, DELETE_EXPENSE } from './types'; export const addExpense = ({ name, amount, spendDate, category }) => ({ type: ADD_EXPENSE, payload: { id: uuidv4(), name, amount, spendDate, category } }); export const deleteExpense = id => ({ type: DELETE_EXPENSE, payload: { id } }); Next, create a new folder, reducers under src folder. Next, create a file, index.js under src/reducers to write reducer function and start editing. Next, import the action types. import { ADD_EXPENSE, DELETE_EXPENSE } from '../actions/types'; Next, add a function, expensesReducer to do the actual feature of adding and updating expenses in the redux store. export default function expensesReducer(state = [], action) { switch (action.type) { case ADD_EXPENSE: return [...state, action.payload]; case DELETE_EXPENSE: return state.filter(expense => expense.id !== action.payload.id); default: return state; } } The complete source code of the reducer is given below βˆ’ import { ADD_EXPENSE, DELETE_EXPENSE } from '../actions/types'; export default function expensesReducer(state = [], action) { switch (action.type) { case ADD_EXPENSE: return [...state, action.payload]; case DELETE_EXPENSE: return state.filter(expense => expense.id !== action.payload.id); default: return state; } } Here, the reducer checks the action type and execute the relevant code. Next, create components folder under src folder. Next, create a file, ExpenseEntryItemList.css under src/components folder and add generic style for the html tables. html { font-family: sans-serif; } table { border-collapse: collapse; border: 2px solid rgb(200,200,200); letter-spacing: 1px; font-size: 0.8rem; } td, th { border: 1px solid rgb(190,190,190); padding: 10px 20px; } th { background-color: rgb(235,235,235); } td, th { text-align: left; } tr:nth-child(even) td { background-color: rgb(250,250,250); } tr:nth-child(odd) td { background-color: rgb(245,245,245); } caption { padding: 10px; } tr.highlight td { background-color: #a6a8bd; } Next, create a file, ExpenseEntryItemList.js under src/components folder and start editing. Next, import React and React redux library. import React from 'react'; import { connect } from 'react-redux'; Next, import ExpenseEntryItemList.css file. import './ExpenseEntryItemList.css'; Next, import action creators. import { deleteExpense } from '../actions'; import { addExpense } from '../actions'; Next, create a class, ExpenseEntryItemList and call constructor with props. class ExpenseEntryItemList extends React.Component { constructor(props) { super(props); } } Next, create mapStateToProps function. const mapStateToProps = state => { return { expenses: state }; }; Here, we copied the input state to expenses props of the component. Next, create mapDispatchToProps function. const mapDispatchToProps = dispatch => { return { onAddExpense: expense => { dispatch(addExpense(expense)); }, onDelete: id => { dispatch(deleteExpense(id)); } }; }; Here, we created two function, one to dispatch add expense (addExpense) function and another to dispatch delete expense (deleteExpense) function and mapped those function to props of the component. Next, export the component using connect api. export default connect( mapStateToProps, mapDispatchToProps )(ExpenseEntryItemList); Now, the component gets three new properties given below βˆ’ expenses βˆ’ list of expense expenses βˆ’ list of expense onAddExpense βˆ’ function to dispatch addExpense function onAddExpense βˆ’ function to dispatch addExpense function onDelete βˆ’ function to dispatch deleteExpense function onDelete βˆ’ function to dispatch deleteExpense function Next, add few expense into the redux store in the constructor using onAddExpense property. if (this.props.expenses.length == 0) { const items = [ { id: 1, name: "Pizza", amount: 80, spendDate: "2020-10-10", category: "Food" }, { id: 2, name: "Grape Juice", amount: 30, spendDate: "2020-10-12", category: "Food" }, { id: 3, name: "Cinema", amount: 210, spendDate: "2020-10-16", category: "Entertainment" }, { id: 4, name: "Java Programming book", amount: 242, spendDate: "2020-10-15", category: "Academic" }, { id: 5, name: "Mango Juice", amount: 35, spendDate: "2020-10-16", category: "Food" }, { id: 6, name: "Dress", amount: 2000, spendDate: "2020-10-25", category: "Cloth" }, { id: 7, name: "Tour", amount: 2555, spendDate: "2020-10-29", category: "Entertainment" }, { id: 8, name: "Meals", amount: 300, spendDate: "2020-10-30", category: "Food" }, { id: 9, name: "Mobile", amount: 3500, spendDate: "2020-11-02", category: "Gadgets" }, { id: 10, name: "Exam Fees", amount: 1245, spendDate: "2020-11-04", category: "Academic" } ] items.forEach((item) => { this.props.onAddExpense( { name: item.name, amount: item.amount, spendDate: item.spendDate, category: item.category } ); }) } Next, add an event handler to delete the expense item using expense id. handleDelete = (id,e) => { e.preventDefault(); this.props.onDelete(id); } Here, the event handler calls the onDelete dispatcher, which call deleteExpense along with the expense id. Next, add a method to calculate the total amount of all expenses. getTotal() { let total = 0; for (var i = 0; i < this.props.expenses.length; i++) { total += this.props.expenses[i].amount } return total; } Next, add render() method and list the expense item in the tabular format. render() { const lists = this.props.expenses.map( (item) => <tr key={item.id}> <td>{item.name}</td> <td>{item.amount}</td> <td>{new Date(item.spendDate).toDateString()}</td> <td>{item.category}</td> <td><a href="#" onClick={(e) => this.handleDelete(item.id, e)}>Remove</a></td> </tr> ); return ( <div> <table> <thead> <tr> <th>Item</th> <th>Amount</th> <th>Date</th> <th>Category</th> <th>Remove</th> </tr> </thead> <tbody> {lists} <tr> <td colSpan="1" style={{ textAlign: "right" }}>Total Amount</td> <td colSpan="4" style={{ textAlign: "left" }}> {this.getTotal()} </td> </tr> </tbody> </table> </div> ); } Here, we set the event handler handleDelete to remove the expense from the store. The complete source code of the ExpenseEntryItemList component is given below βˆ’ import React from 'react'; import { connect } from 'react-redux'; import './ExpenseEntryItemList.css'; import { deleteExpense } from '../actions'; import { addExpense } from '../actions'; class ExpenseEntryItemList extends React.Component { constructor(props) { super(props); if (this.props.expenses.length == 0){ const items = [ { id: 1, name: "Pizza", amount: 80, spendDate: "2020-10-10", category: "Food" }, { id: 2, name: "Grape Juice", amount: 30, spendDate: "2020-10-12", category: "Food" }, { id: 3, name: "Cinema", amount: 210, spendDate: "2020-10-16", category: "Entertainment" }, { id: 4, name: "Java Programming book", amount: 242, spendDate: "2020-10-15", category: "Academic" }, { id: 5, name: "Mango Juice", amount: 35, spendDate: "2020-10-16", category: "Food" }, { id: 6, name: "Dress", amount: 2000, spendDate: "2020-10-25", category: "Cloth" }, { id: 7, name: "Tour", amount: 2555, spendDate: "2020-10-29", category: "Entertainment" }, { id: 8, name: "Meals", amount: 300, spendDate: "2020-10-30", category: "Food" }, { id: 9, name: "Mobile", amount: 3500, spendDate: "2020-11-02", category: "Gadgets" }, { id: 10, name: "Exam Fees", amount: 1245, spendDate: "2020-11-04", category: "Academic" } ] items.forEach((item) => { this.props.onAddExpense( { name: item.name, amount: item.amount, spendDate: item.spendDate, category: item.category } ); }) } } handleDelete = (id,e) => { e.preventDefault(); this.props.onDelete(id); } getTotal() { let total = 0; for (var i = 0; i < this.props.expenses.length; i++) { total += this.props.expenses[i].amount } return total; } render() { const lists = this.props.expenses.map((item) => <tr key={item.id}> <td>{item.name}</td> <td>{item.amount}</td> <td>{new Date(item.spendDate).toDateString()}</td> <td>{item.category}</td> <td><a href="#" onClick={(e) => this.handleDelete(item.id, e)}>Remove</a></td> </tr> ); return ( <div> <table> <thead> <tr> <th>Item</th> <th>Amount</th> <th>Date</th> <th>Category</th> <th>Remove</th> </tr> </thead> <tbody> {lists} <tr> <td colSpan="1" style={{ textAlign: "right" }}>Total Amount</td> <td colSpan="4" style={{ textAlign: "left" }}> {this.getTotal()} </td> </tr> </tbody> </table> </div> ); } } const mapStateToProps = state => { return { expenses: state }; }; const mapDispatchToProps = dispatch => { return { onAddExpense: expense => { dispatch(addExpense(expense)); }, onDelete: id => { dispatch(deleteExpense(id)); } }; }; export default connect( mapStateToProps, mapDispatchToProps )(ExpenseEntryItemList); Next, create a file, App.js under the src/components folder and use ExpenseEntryItemList component. import React, { Component } from 'react'; import ExpenseEntryItemList from './ExpenseEntryItemList'; class App extends Component { render() { return ( <div> <ExpenseEntryItemList /> </div> ); } } export default App; Next, create a file, index.js under src folder. import React from 'react'; import ReactDOM from 'react-dom'; import { createStore } from 'redux'; import { Provider } from 'react-redux'; import rootReducer from './reducers'; import App from './components/App'; const store = createStore(rootReducer); ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') ); Here, Create a store using createStore by attaching the our reducer. Create a store using createStore by attaching the our reducer. Used Provider component from React redux library and set the store as props, which enables all the nested component to connect to store using connect api. Used Provider component from React redux library and set the store as props, which enables all the nested component to connect to store using connect api. Finally, create a public folder under the root folder and create index.html file. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>React Containment App</title> </head> <body> <div id="root"></div> <script type="text/JavaScript" src="./index.js"></script> </body> </html> Next, serve the application using npm command. npm start Next, open the browser and enter http://localhost:3000 in the address bar and press enter. Clicking the remove link will remove the item from redux store. Animation is an exciting feature of modern web application. It gives a refreshing feel to the application. React community provides many excellent react based animation library like React Motion, React Reveal, react-animations, etc., React itself provides an animation library, React Transition Group as an add-on option earlier. It is an independent library enhancing the earlier version of the library. Let us learn React Transition Group animation library in this chapter. React Transition Group library is a simple implementation of animation. It does not do any animation out of the box. Instead, it exposes the core animation related information. Every animation is basically transition of an element from one state to another. The library exposes minimum possible state of every element and they are given below βˆ’ Entering Entered Exiting Exited The library provides options to set CSS style for each state and animate the element based on the style when the element moves from one state to another. The library provides in props to set the current state of the element. If in props value is true, then it means the element is moving from entering state to exiting state. If in props value is false, then it means the element is moving from exiting to exited. Transition is the basic component provided by the React Transition Group to animate an element. Let us create a simple application and try to fade in / fade out an element using Transition element. First, create a new react application, react-animation-app using Create React App or Rollup bundler by following instruction in Creating a React application chapter. Next, install React Transition Group library. cd /go/to/project npm install react-transition-group --save Next, open the application in your favorite editor. Next, create src folder under the root directory of the application. Next, create components folder under src folder. Next, create a file, HelloWorld.js under src/components folder and start editing. Next, import React and animation library. import React from 'react'; import { Transition } from 'react-transition-group' Next, create the HelloWorld component. class HelloWorld extends React.Component { constructor(props) { super(props); } } Next, define transition related styles as JavaScript objects in the constructor. this.duration = 2000; this.defaultStyle = { transition: `opacity ${this.duration}ms ease-in-out`, opacity: 0, } this.transitionStyles = { entering: { opacity: 1 }, entered: { opacity: 1 }, exiting: { opacity: 0 }, exited: { opacity: 0 }, }; Here, defaultStyles sets the transition animation defaultStyles sets the transition animation transitionStyles set the styles for various states transitionStyles set the styles for various states Next, set the initial state for the element in the constructor. this.state = { inProp: true } Next, simulate the animation by changing the inProp values every 3 seconds. setInterval(() => { this.setState((state, props) => { let newState = { inProp: !state.inProp }; return newState; }) }, 3000); Next, create a render function. render() { return ( ); } Next, add Transition component. Use this.state.inProp for in prop and this.duration for timeout prop. Transition component expects a function, which returns the user interface. It is basically a Render props. render() { return ( <Transition in={this.state.inProp} timeout={this.duration}> {state => ({ ... component's user interface. }) </Transition> ); } Next, write the components user interface inside a container and set the defaultStyle and transitionStyles for the container. render() { return ( <Transition in={this.state.inProp} timeout={this.duration}> {state => ( <div style={{ ...this.defaultStyle, ...this.transitionStyles[state] }}> <h1>Hello World!</h1> </div> )} </Transition> ); } Finally, expose the component. export default HelloWorld The complete source code of the component is as follows βˆ’ import React from "react"; import { Transition } from 'react-transition-group'; class HelloWorld extends React.Component { constructor(props) { super(props); this.duration = 2000; this.defaultStyle = { transition: `opacity ${this.duration}ms ease-in-out`, opacity: 0, } this.transitionStyles = { entering: { opacity: 1 }, entered: { opacity: 1 }, exiting: { opacity: 0 }, exited: { opacity: 0 }, }; this.state = { inProp: true } setInterval(() => { this.setState((state, props) => { let newState = { inProp: !state.inProp }; return newState; }) }, 3000); } render() { return ( <Transition in={this.state.inProp} timeout={this.duration}> {state => ( <div style={{ ...this.defaultStyle, ...this.transitionStyles[state] }}> <h1>Hello World!</h1> </div> )} </Transition> ); } } export default HelloWorld; Next, create a file, index.js under the src folder and use HelloWorld component. import React from 'react'; import ReactDOM from 'react-dom'; import HelloWorld from './components/HelloWorld'; ReactDOM.render( <React.StrictMode <HelloWorld / </React.StrictMode , document.getElementById('root') ); Finally, create a public folder under the root folder and create index.html file. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>React Containment App</title> </head> <body> <div id="root"></div> <script type="text/JavaScript" src="./index.js"></script> </body> </html> Next, serve the application using npm command. npm start Next, open the browser and enter http://localhost:3000 in the address bar and press enter. Clicking the remove link will remove the item from redux store. CSSTransition is built on top of Transition component and it improves Transition component by introducing classNames prop. classNames prop refers the css class name used for various state of the element. For example, classNames=hello prop refers below css classes. .hello-enter { opacity: 0; } .hello-enter-active { opacity: 1; transition: opacity 200ms; } .hello-exit { opacity: 1; } .hello-exit-active { opacity: 0; transition: opacity 200ms; } Let us create a new component HelloWorldCSSTransition using CSSTransition component. First, open our react-animation-app application in your favorite editor. Next, create a new file, HelloWorldCSSTransition.css under src/components folder and enter transition classes. .hello-enter { opacity: 1; transition: opacity 2000ms ease-in-out; } .hello-enter-active { opacity: 1; transition: opacity 2000ms ease-in-out; } .hello-exit { opacity: 0; transition: opacity 2000ms ease-in-out; } .hello-exit-active { opacity: 0; transition: opacity 2000ms ease-in-out; } Next, create a new file, HelloWorldCSSTransition.js under src/components folder and start editing. Next, import React and animation library. import React from 'react'; import { CSSTransition } from 'react-transition-group' Next, import HelloWorldCSSTransition.css. import './HelloWorldCSSTransition.css' Next, create the HelloWorld component. class HelloWorldCSSTransition extends React.Component { constructor(props) { super(props); } } Next, define duration of the transition in the constructor. this.duration = 2000; Next, set the initial state for the element in the constructor. this.state = { inProp: true } Next, simulate the animation by changing the inProp values every 3 seconds. setInterval(() => { this.setState((state, props) => { let newState = { inProp: !state.inProp }; return newState; }) }, 3000); Next, create a render function. render() { return ( ); } Next, add CSSTransition component. Use this.state.inProp for in prop, this.duration for timeout prop and hello for classNames prop. CSSTransition component expects user interface as child prop. render() { return ( <CSSTransition in={this.state.inProp} timeout={this.duration} classNames="hello"> // ... user interface code ... </CSSTransition> ); } Next, write the components user interface. render() { return ( <CSSTransition in={this.state.inProp} timeout={this.duration} classNames="hello"> <div> <h1>Hello World!</h1> </div> </CSSTransition> ); } Finally, expose the component. export default HelloWorldCSSTransition; The complete source code of the component is given below βˆ’ import React from 'react'; import { CSSTransition } from 'react-transition-group' import './HelloWorldCSSTransition.css' class HelloWorldCSSTransition extends React.Component { constructor(props) { super(props); this.duration = 2000; this.state = { inProp: true } setInterval(() => { this.setState((state, props) => { let newState = { inProp: !state.inProp }; return newState; }) }, 3000); } render() { return ( <CSSTransition in={this.state.inProp} timeout={this.duration} classNames="hello"> <div> <h1>Hello World!</h1> </div> </CSSTransition> ); } } export default HelloWorldCSSTransition; Next, create a file, index.js under the src folder and use HelloWorld component. import React from 'react'; import ReactDOM from 'react-dom'; import HelloWorldCSSTransition from './components/HelloWorldCSSTransition'; ReactDOM.render( <React.StrictMode> <HelloWorldCSSTransition /> </React.StrictMode>, document.getElementById('root') ); Next, serve the application using npm command. npm start Next, open the browser and enter http://localhost:3000 in the address bar and press enter. The message will fade in and out for every 3 seconds. TransitionGroup is a container component, which manages multiple transition component in a list. For example, while each item in a list use CSSTransition, TransitionGroup can be used to group all the item for proper animation. <TransitionGroup> {items.map(({ id, text }) => ( <CSSTransition key={id} timeout={500} classNames="item" > <Button onClick={() => setItems(items => items.filter(item => item.id !== id) ) } > &times; </Button> {text} </CSSTransition> ))} </TransitionGroup> Testing is one of the processes to make sure that the functionality created in any application is working in accordance with the business logic and coding specification. React recommends React testing library to test React components and jest test runner to run the test. The react-testing-library allows the components to be checked in isolation. It can be installed in the application using below command βˆ’ npm install --save @testing-library/react @testing-library/jest-dom Create React app configures React testing library and jest test runner by default. So, testing a React application created using Create React App is just a command away. cd /go/to/react/application npm test The npm test command is similar to npm build command. Both re-compiles as and when the developer changes the code. Once the command is executed in the command prompt, it emits below questions. No tests found related to files changed since last commit. Press `a` to run all tests, or run Jest with `--watchAll`. Watch Usage β€Ί Press a to run all tests. β€Ί Press f to run only failed tests. β€Ί Press q to quit watch mode. β€Ί Press p to filter by a filename regex pattern. β€Ί Press t to filter by a test name regex pattern. β€Ί Press Enter to trigger a test run. Pressing a will try to run all the test script and finally summaries the result as shown below βˆ’ Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 4.312 s, estimated 12 s Ran all test suites. Watch Usage: Press w to show more. Let us write a custom React application using Rollup bundler and test it using React testing library and jest test runner in this chapter. First, create a new react application, react-test-app using Rollup bundler by following instruction in Creating a React application chapter. Next, install the testing library. cd /go/to/react-test-app npm install --save @testing-library/react @testing-library/jest-dom Next, open the application in your favorite editor. Next, create a file, HelloWorld.test.js under src/components folder to write test for HelloWorld component and start editing. Next, import react library. import React from 'react'; Next, import the testing library. import { render, screen } from '@testing-library/react'; import '@testing-library/jest-dom'; Next, import our HelloWorld component. import HelloWorld from './HelloWorld'; Next, write a test to check the existence of Hello World text in the document. test('test scenario 1', () => { render(<HelloWorld />); const element = screen.getByText(/Hello World/i); expect(element).toBeInTheDocument(); }); The complete source code of the test code is given below βˆ’ import React from 'react'; import { render, screen } from '@testing-library/react'; import '@testing-library/jest-dom'; import HelloWorld from './HelloWorld'; test('test scenario 1', () => { render(<HelloWorld />); const element = screen.getByText(/Hello World/i); expect(element).toBeInTheDocument(); }); Next, install jest test runner, if it is not installed already in the system. npm install jest -g Next, run jest command in the root folder of the application. jest Next, run jest command in the root folder of the application. PASS src/components/HelloWorld.test.js √ test scenario 1 (29 ms) Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 5.148 s Ran all test suites. Let us learn the basic command available in Create React App command line application in this chapter. Create React App provides multiple ways to create React application. Using npx script. npx create-react-app <react-app-name> npx create-react-app hello-react-app Using npm package manager. npm init react-app <react-app-name> npm init react-app hello-react-app Using yarn package manager. yarn init react-app <react-app-name> yarn init react-app hello-react-app Create React App creates React application using default template. Template refers the initial code with certain build-in functionality. There are hundreds of template with many advanced features are available in npm package server. Create React App allows the users to select the template through –template command line switch. create-react-app my-app --template typescript Above command will create react app using cra-template-typescript package from npm server. React dependency package can be installed using normal npm or yarn package command as React uses the project structure recommended by npm and yarn. Using npm package manager. npm install --save react-router-dom Using yarn package manager. yarn add react-router-dom React application can be started using npm or yarn command depending on the package manager used in the project. Using npm package manager. npm start Using yarn package manager. yarn start To run the application in secure mode (HTTPS), set an environment variable, HTTPS and set it to true before starting the application. For example, in windows command prompt (cmd.exe), the below command set HTTPS and starts the application is HTTPS mode. set HTTPS=true && npm start Let us learn how to do production build and deployment of React application in this chapter. Once a React application development is done, application needs to be bundled and deployed to a production server. Let us learn the command available to build and deploy the application in this chapter. A single command is enough to create a production build of the application. npm run build > expense-manager@0.1.0 build path\to\expense-manager > react-scripts build Creating an optimized production build... Compiled with warnings. File sizes after gzip: 41.69 KB build\static\js\2.a164da11.chunk.js 2.24 KB build\static\js\main.de70a883.chunk.js 1.4 KB build\static\js\3.d8a9fc85.chunk.js 1.17 KB build\static\js\runtime-main.560bee6e.js 493 B build\static\css\main.e75e7bbe.chunk.css The project was built assuming it is hosted at /. You can control this with the homepage field in your package.json. The build folder is ready to be deployed. You may serve it with a static server: npm install -g serve serve -s build Find out more about deployment here: https://cra.link/deployment Once the application is build, the application is available under build/static folder. By default, profiling option is disable and can be enabled through –profile command line option. –profile will include profiling information in the code. The profiling information can be used along with React DevTools to analyse the application. npm run build -- --profile Once the application is build, it can be deployed to any web server. Let us learn how to deploy a React application in this chapter. Local deployment can be done using serve package. Let us first install serve package using below command βˆ’ npm install -g server To start the application using serve, use the below command βˆ’ cd /go/to/app/root/folder serve -s build By default, serve serve the application using port 5000. The application can be viewed @ http://localhost:5000. Production deployment can be easily done by copying the files under build/static folder to the production application’s root directory. It will work in all web server including Apache, IIS, Nginx, etc. By default, the production build is created assuming that the application will be hosted in the root folder of a web application. If the application needs to be hosted in a subfolder, then use below configuration in the package.json and then build the application. { ... "homepage": "http://domainname.com/path/to/subfolder", ... } Let us create a sample expense manager application by applying the concepts that we have learned in this tutorial. Some of the concepts are listed below βˆ’ React basics (component, jsx, props and state) React basics (component, jsx, props and state) Router using react-router Router using react-router Http client programming (Web API) Http client programming (Web API) Form programming using Formik Form programming using Formik Advanced state management using Redux Advanced state management using Redux Async / await programming Async / await programming Some of the features of our sample expense manager application are βˆ’ Listing all the expenses from the server Listing all the expenses from the server Add an expense item Add an expense item Delete an expense item Delete an expense item Here, Expense manager API Expense manager API Install necessary modules Install necessary modules State management State management List expenses List expenses Add expense Add expense 20 Lectures 1.5 hours Anadi Sharma 60 Lectures 4.5 hours Skillbakerystudios 165 Lectures 13 hours Paul Carlo Tordecilla 63 Lectures 9.5 hours TELCOMA Global 17 Lectures 2 hours Mohd Raqif Warsi Print Add Notes Bookmark this page
[ { "code": null, "e": 2519, "s": 2033, "text": "ReactJS is a simple, feature rich, component based JavaScript UI library. It can be used to develop small applications as well as big, complex applications. ReactJS provides minimal and solid feature set to kick-start a web application. React community compliments React library by providing large set of ready-made components to develop web application in a record time. React community also provides advanced concept like state management, routing, etc., on top of the React library." }, { "code": null, "e": 2880, "s": 2519, "text": "The initial version, 0.3.0 of React is released on May, 2013 and the latest version, 17.0.1 is released on October, 2020. The major version introduces breaking changes and the minor version introduces new feature without breaking the existing functionality. Bug fixes are released as and when necessary. React follows the Sematic Versioning (semver) principle." }, { "code": null, "e": 2935, "s": 2880, "text": "The salient features of React library are as follows βˆ’" }, { "code": null, "e": 2959, "s": 2935, "text": "Solid base architecture" }, { "code": null, "e": 2983, "s": 2959, "text": "Extensible architecture" }, { "code": null, "e": 3007, "s": 2983, "text": "Component based library" }, { "code": null, "e": 3037, "s": 3007, "text": "JSX based design architecture" }, { "code": null, "e": 3060, "s": 3037, "text": "Declarative UI library" }, { "code": null, "e": 3113, "s": 3060, "text": "Few benefits of using React library are as follows βˆ’" }, { "code": null, "e": 3127, "s": 3113, "text": "Easy to learn" }, { "code": null, "e": 3181, "s": 3127, "text": "Easy to adept in modern as well as legacy application" }, { "code": null, "e": 3216, "s": 3181, "text": "Faster way to code a functionality" }, { "code": null, "e": 3269, "s": 3216, "text": "Availability of large number of ready-made component" }, { "code": null, "e": 3296, "s": 3269, "text": "Large and active community" }, { "code": null, "e": 3361, "s": 3296, "text": "Few popular websites powered by React library are listed below βˆ’" }, { "code": null, "e": 3404, "s": 3361, "text": "Facebook, popular social media application" }, { "code": null, "e": 3449, "s": 3404, "text": "Instagram, popular photo sharing application" }, { "code": null, "e": 3494, "s": 3449, "text": "Netflix, popular media streaming application" }, { "code": null, "e": 3544, "s": 3494, "text": "Code Academy, popular online training application" }, { "code": null, "e": 3588, "s": 3544, "text": "Reddit, popular content sharing application" }, { "code": null, "e": 3677, "s": 3588, "text": "As you see, most popular application in every field is being developed by React Library." }, { "code": null, "e": 3845, "s": 3677, "text": "This chapter explains the installation of React library and its related tools in your machine. Before moving to the installation, let us verify the prerequisite first." }, { "code": null, "e": 4155, "s": 3845, "text": "React provides CLI tools for the developer to fast forward the creation, development and deployment of the React based web application. React CLI tools depends on the Node.js and must be installed in your system. Hopefully, you have installed Node.js on your machine. We can check it using the below command βˆ’" }, { "code": null, "e": 4171, "s": 4155, "text": "node --version\n" }, { "code": null, "e": 4262, "s": 4171, "text": "You could see the version of Nodejs you might have installed. It is shown as below for me," }, { "code": null, "e": 4271, "s": 4262, "text": "v14.2.0\n" }, { "code": null, "e": 4373, "s": 4271, "text": "If Nodejs is not installed, you can download and install by visiting https://nodejs.org/en/download/." }, { "code": null, "e": 4829, "s": 4373, "text": "To develop lightweight features such as form validation, model dialog, etc., React library can be directly included into the web application through content delivery network (CDN). It is similar to using jQuery library in a web application. For moderate to big application, it is advised to write the application as multiple files and then use bundler such as webpack, parcel, rollup, etc., to compile and bundle the application before deploying the code." }, { "code": null, "e": 5023, "s": 4829, "text": "React toolchain helps to create, build, run and deploy the React application. React toolchain basically provides a starter project template with all necessary code to bootstrap the application." }, { "code": null, "e": 5089, "s": 5023, "text": "Some of the popular toolchain to develop React applications are βˆ’" }, { "code": null, "e": 5131, "s": 5089, "text": "Create React App βˆ’ SPA oriented toolchain" }, { "code": null, "e": 5182, "s": 5131, "text": "Next.js βˆ’ server-side rendering oriented toolchain" }, { "code": null, "e": 5225, "s": 5182, "text": "Gatsby βˆ’ Static content oriented toolchain" }, { "code": null, "e": 5277, "s": 5225, "text": "Tools required to develop a React application are βˆ’" }, { "code": null, "e": 5348, "s": 5277, "text": "The serve, a static server to serve our application during development" }, { "code": null, "e": 5363, "s": 5348, "text": "Babel compiler" }, { "code": null, "e": 5384, "s": 5363, "text": "Create React App CLI" }, { "code": null, "e": 5479, "s": 5384, "text": "Let us learn the basics of the above mentioned tools and how to install those in this chapter." }, { "code": null, "e": 5721, "s": 5479, "text": "The serve is a lightweight web server. It serves static site and single page application. It loads fast and consume minimum memory. It can be used to serve a React application. Let us install the tool using npm package manager in our system." }, { "code": null, "e": 5743, "s": 5721, "text": "npm install serve -g\n" }, { "code": null, "e": 5821, "s": 5743, "text": "Let us create a simple static site and serve the application using serve app." }, { "code": null, "e": 5869, "s": 5821, "text": "Open a command prompt and go to your workspace." }, { "code": null, "e": 5895, "s": 5869, "text": "cd /go/to/your/workspace\n" }, { "code": null, "e": 5974, "s": 5895, "text": "Create a new folder, static_site and change directory to newly created folder." }, { "code": null, "e": 6009, "s": 5974, "text": "mkdir static_site \ncd static_site\n" }, { "code": null, "e": 6090, "s": 6009, "text": "Next, create a simple webpage inside the folder using your favorite html editor." }, { "code": null, "e": 6273, "s": 6090, "text": "<!DOCTYPE html> \n<html> \n <head> \n <meta charset=\"UTF-8\" /> \n <title>Static website</title> \n </head> \n <body> \n <div><h1>Hello!</h1></div> \n </body> \n</html>\n" }, { "code": null, "e": 6302, "s": 6273, "text": "Next, run the serve command." }, { "code": null, "e": 6311, "s": 6302, "text": "serve .\n" }, { "code": null, "e": 6382, "s": 6311, "text": "We can also serve single file, index.html instead of the whole folder." }, { "code": null, "e": 6402, "s": 6382, "text": "serve ./index.html\n" }, { "code": null, "e": 6550, "s": 6402, "text": "Next, open the browser and enter http://localhost:5000 in the address bar and press enter. serve application will serve our webpage as shown below." }, { "code": null, "e": 6683, "s": 6550, "text": "The serve will serve the application using default port, 5000. If it is not available, it will pick up a random port and specify it." }, { "code": null, "e": 7093, "s": 6683, "text": "β”‚ Serving! β”‚ \n β”‚ β”‚ \n β”‚ - Local: http://localhost:57311 β”‚ \n β”‚ - On Your Network: http://192.168.56.1:57311 β”‚ \n β”‚ β”‚ \n β”‚ This port was picked because 5000 is in use. β”‚ \n β”‚ β”‚ \n β”‚ Copied local address to clipboard!" }, { "code": null, "e": 7382, "s": 7093, "text": "Babel is a JavaScript compiler which compiles many variant (es2015, es6, etc.,) of JavaScript into standard JavaScript code supported by all browsers. React uses JSX, an extension of JavaScript to design the user interface code. Babel is used to compile the JSX code into JavaScript code." }, { "code": null, "e": 7449, "s": 7382, "text": "To install Babel and it’s React companion, run the below command βˆ’" }, { "code": null, "e": 7592, "s": 7449, "text": "npm install babel-cli@6 babel-preset-react-app@3 -g\n... \n... \n+ babel-cli@6.26.0 \n+ babel-preset-react-app@3.1.2 \nupdated 2 packages in 8.685s" }, { "code": null, "e": 7682, "s": 7592, "text": "Babel helps us to write our application in next generation of advanced JavaScript syntax." }, { "code": null, "e": 7903, "s": 7682, "text": "Create React App is a modern CLI tool to create single page React application. It is the standard tool supported by React community. It handles babel compiler as well. Let us install Create React App in our local system." }, { "code": null, "e": 8055, "s": 7903, "text": "> npm install -g create-react-app\n+ create-react-app@4.0.1 \nadded 6 packages from 4 contributors, removed 37 packages and updated 12 packages in 4.693s" }, { "code": null, "e": 8283, "s": 8055, "text": "React Create App toolchain uses the react-scripts package to build and run the application. Once we started working on the application, we can update the react-script to the latest version at any time using npm package manager." }, { "code": null, "e": 8317, "s": 8283, "text": "npm install react-scripts@latest\n" }, { "code": null, "e": 8428, "s": 8317, "text": "React toolchain provides lot of features out of the box. Some of the advantages of using React toolchain are βˆ’" }, { "code": null, "e": 8482, "s": 8428, "text": "Predefined and standard structure of the application." }, { "code": null, "e": 8545, "s": 8482, "text": "Ready-made project template for different type of application." }, { "code": null, "e": 8581, "s": 8545, "text": "Development web server is included." }, { "code": null, "e": 8631, "s": 8581, "text": "Easy way to include third party React components." }, { "code": null, "e": 8670, "s": 8631, "text": "Default setup to test the application." }, { "code": null, "e": 9152, "s": 8670, "text": "React library is built on a solid foundation. It is simple, flexible and extensible. As we learned earlier, React is a library to create user interface in a web application. React’s primary purpose is to enable the developer to create user interface using pure JavaScript. Normally, every user interface library introduces a new template language (which we need to learn) to design the user interface and provides an option to write logic, either inside the template or separately." }, { "code": null, "e": 9254, "s": 9152, "text": "Instead of introducing new template language, React introduces three simple concepts as given below βˆ’" }, { "code": null, "e": 9361, "s": 9254, "text": "JavaScript representation of HTML DOM. React provides an API, React.createElement to create React Element." }, { "code": null, "e": 9573, "s": 9361, "text": "A JavaScript extension to design user interface. JSX is an XML based, extensible language supporting HTML syntax with little modification. JSX can be compiled to React Elements and used to create user interface." }, { "code": null, "e": 9967, "s": 9573, "text": "React component is the primary building block of the React application. It uses React elements and JSX to design its user interface. React component is basically a JavaScript class (extends the React.component class) or pure JavaScript function. React component has properties, state management, life cycle and event handler. React component can be able to do simple as well as advanced logic." }, { "code": null, "e": 10034, "s": 9967, "text": "Let us learn more about components in the React Component chapter." }, { "code": null, "e": 10158, "s": 10034, "text": "Let us understand the workflow of a React application in this chapter by creating and analyzing a simple React application." }, { "code": null, "e": 10206, "s": 10158, "text": "Open a command prompt and go to your workspace." }, { "code": null, "e": 10232, "s": 10206, "text": "cd /go/to/your/workspace\n" }, { "code": null, "e": 10313, "s": 10232, "text": "Next, create a folder, static_site and change directory to newly created folder." }, { "code": null, "e": 10348, "s": 10313, "text": "mkdir static_site \ncd static_site\n" }, { "code": null, "e": 10418, "s": 10348, "text": "Next, create a file, hello.html and write a simple React application." }, { "code": null, "e": 10996, "s": 10418, "text": "<!DOCTYPE html> \n<html> \n <head> \n <meta charset=\"UTF-8\" /> \n <title>React Application</title> \n </head> \n <body> \n <div id=\"react-app\"></div> \n <script src=\"https://unpkg.com/react@17/umd/react.development.js\" crossorigin></script> \n <script src=\"https://unpkg.com/react-dom@17/umd/react-dom.development.js\" crossorigin></script> \n <script language=\"JavaScript\"> \n element = React.createElement('h1', {}, 'Hello React!') \n ReactDOM.render(element, document.getElementById('react-app')); \n </script> \n </body> \n</html>" }, { "code": null, "e": 11048, "s": 10996, "text": "Next, serve the application using serve web server." }, { "code": null, "e": 11068, "s": 11048, "text": "serve ./hello.html\n" }, { "code": null, "e": 11171, "s": 11068, "text": "Next, open your favorite browser. Enter http://localhost:5000 in the address bar and then press enter." }, { "code": null, "e": 11266, "s": 11171, "text": "Let us analyse the code and do little modification to better understand the React application." }, { "code": null, "e": 11324, "s": 11266, "text": "Here, we are using two API provided by the React library." }, { "code": null, "e": 11385, "s": 11324, "text": "Used to create React elements. It expects three parameters βˆ’" }, { "code": null, "e": 11397, "s": 11385, "text": "Element tag" }, { "code": null, "e": 11426, "s": 11397, "text": "Element attributes as object" }, { "code": null, "e": 11488, "s": 11426, "text": "Element content - It can contain nested React element as well" }, { "code": null, "e": 11563, "s": 11488, "text": "Used to render the element into the container. It expects two parameters βˆ’" }, { "code": null, "e": 11584, "s": 11563, "text": "React Element OR JSX" }, { "code": null, "e": 11612, "s": 11584, "text": "Root element of the webpage" }, { "code": null, "e": 11707, "s": 11612, "text": "As React.createElement allows nested React element, let us add nested element as shown below βˆ’" }, { "code": null, "e": 11715, "s": 11707, "text": "Example" }, { "code": null, "e": 11916, "s": 11715, "text": "<script language=\"JavaScript\">\n element = React.createElement('div', {}, React.createElement('h1', {}, 'Hello React!'));\n ReactDOM.render(element, document.getElementById('react-app')); \n</script>" }, { "code": null, "e": 11923, "s": 11916, "text": "Output" }, { "code": null, "e": 11960, "s": 11923, "text": "It will generate the below content βˆ’" }, { "code": null, "e": 11996, "s": 11960, "text": "<div><h1> Hello React!</h1></div> \n" }, { "code": null, "e": 12085, "s": 11996, "text": "Next, let us remove the React element entirely and introduce JSX syntax as shown below βˆ’" }, { "code": null, "e": 12734, "s": 12085, "text": "<!DOCTYPE html> \n<html> \n <head> \n <meta charset=\"UTF-8\" /> \n <title>React Application</title> \n </head> \n <body> \n <div id=\"react-app\"></div> \n <script src=\"https://unpkg.com/react@17/umd/react.development.js\" crossorigin></script> \n <script src=\"https://unpkg.com/react-dom@17/umd/react-dom.development.js\" crossorigin></script> \n <script src=\"https://unpkg.com/@babel/standalone/babel.min.js\"></script> \n <script type=\"text/babel\"> \n ReactDOM.render(\n <div><h1>Hello React!</h1></div>, \n document.getElementById('react-app') \n ); \n </script> \n </body> \n</html>" }, { "code": null, "e": 12841, "s": 12734, "text": "Here, we have included babel to convert JSX into JavaScript and added type=β€œtext/babel” in the script tag." }, { "code": null, "e": 12970, "s": 12841, "text": "<script src=\"https://unpkg.com/@babel/standalone/babel.min.js\"></script> \n<script type=\"text/babel\"> \n ... \n ... \n</script>\n" }, { "code": null, "e": 13064, "s": 12970, "text": "Next, run the application and open the browser. The output of the application is as follows βˆ’" }, { "code": null, "e": 13155, "s": 13064, "text": "Next, let us create a new React component, Greeting and then try to use it in the webpage." }, { "code": null, "e": 13344, "s": 13155, "text": "<script type=\"text/babel\"> \n function Greeting() {\n return <div><h1>Hello JSX!</h1></div> \n } \n ReactDOM.render(<Greeting />, document.getElementById('react-app') ); \n</script>\n" }, { "code": null, "e": 13384, "s": 13344, "text": "The result is same and as shown below βˆ’" }, { "code": null, "e": 13500, "s": 13384, "text": "By analyzing the application, we can visualize the workflow of the React application as shown in the below diagram." }, { "code": null, "e": 13693, "s": 13500, "text": "React app calls ReactDOM.render method by passing the user interface created using React component (coded in either JSX or React element format) and the container to render the user interface." }, { "code": null, "e": 13767, "s": 13693, "text": "ReactDOM.render processes the JSX or React element and emits Virtual DOM." }, { "code": null, "e": 13827, "s": 13767, "text": "Virtual DOM will be merged and rendered into the container." }, { "code": null, "e": 14370, "s": 13827, "text": "React library is just UI library and it does not enforce any particular pattern to write a complex application. Developers are free to choose the design pattern of their choice. React community advocates certain design pattern. One of the patterns is Flux pattern. React library also provides lot of concepts like Higher Order component, Context, Render props, Refs etc., to write better code. React Hooks is evolving concept to do state management in big projects. Let us try to understand the high level architecture of a React application." }, { "code": null, "e": 14417, "s": 14370, "text": "React app starts with a single root component." }, { "code": null, "e": 14464, "s": 14417, "text": "React app starts with a single root component." }, { "code": null, "e": 14517, "s": 14464, "text": "Root component is build using one or more component." }, { "code": null, "e": 14570, "s": 14517, "text": "Root component is build using one or more component." }, { "code": null, "e": 14634, "s": 14570, "text": "Each component can be nested with other component to any level." }, { "code": null, "e": 14698, "s": 14634, "text": "Each component can be nested with other component to any level." }, { "code": null, "e": 14876, "s": 14698, "text": "Composition is one of the core concepts of React library. So, each component is build by composing smaller components instead of inheriting one component from another component." }, { "code": null, "e": 15054, "s": 14876, "text": "Composition is one of the core concepts of React library. So, each component is build by composing smaller components instead of inheriting one component from another component." }, { "code": null, "e": 15108, "s": 15054, "text": "Most of the components are user interface components." }, { "code": null, "e": 15162, "s": 15108, "text": "Most of the components are user interface components." }, { "code": null, "e": 15278, "s": 15162, "text": "React app can include third party component for specific purpose such as routing, animation, state management, etc." }, { "code": null, "e": 15394, "s": 15278, "text": "React app can include third party component for specific purpose such as routing, animation, state management, etc." }, { "code": null, "e": 15854, "s": 15394, "text": "As we learned earlier, React library can be used in both simple and complex application. Simple application normally includes the React library in its script section. In complex application, developers have to split the code into multiple files and organize the code into a standard structure. Here, React toolchain provides pre-defined structure to bootstrap the application. Also, developers are free to use their own project structure to organize the code." }, { "code": null, "e": 15925, "s": 15854, "text": "Let us see how to create simple as well as complex React application βˆ’" }, { "code": null, "e": 15954, "s": 15925, "text": "Simple application using CDN" }, { "code": null, "e": 15983, "s": 15954, "text": "Simple application using CDN" }, { "code": null, "e": 16030, "s": 15983, "text": "Complex application using React Create App cli" }, { "code": null, "e": 16077, "s": 16030, "text": "Complex application using React Create App cli" }, { "code": null, "e": 16121, "s": 16077, "text": "Complex application using customized method" }, { "code": null, "e": 16165, "s": 16121, "text": "Complex application using customized method" }, { "code": null, "e": 16278, "s": 16165, "text": "Rollup is one of the small and fast JavaScript bundlers. Let us learn how to use rollup bundler in this chapter." }, { "code": null, "e": 16320, "s": 16278, "text": "Open a terminal and go to your workspace." }, { "code": null, "e": 16346, "s": 16320, "text": "cd /go/to/your/workspace\n" }, { "code": null, "e": 16480, "s": 16346, "text": "Next, create a folder, expense-manager-rollup and move to newly created folder. Also, open the folder in your favorite editor or IDE." }, { "code": null, "e": 16537, "s": 16480, "text": "mkdir expense-manager-rollup \ncd expense-manager-rollup\n" }, { "code": null, "e": 16578, "s": 16537, "text": "Next, create and initialize the project." }, { "code": null, "e": 16591, "s": 16578, "text": "npm init -y\n" }, { "code": null, "e": 16644, "s": 16591, "text": "Next, install React libraries (react and react-dom)." }, { "code": null, "e": 16696, "s": 16644, "text": "npm install react@^17.0.0 react-dom@^17.0.0 --save\n" }, { "code": null, "e": 16768, "s": 16696, "text": "Next, install babel and its preset libraries as development dependency." }, { "code": null, "e": 16875, "s": 16768, "text": "npm install @babel/preset-env @babel/preset-react \n@babel/core @babel/plugin-proposal-class-properties -D\n" }, { "code": null, "e": 16948, "s": 16875, "text": "Next, install rollup and its plugin libraries as development dependency." }, { "code": null, "e": 17196, "s": 16948, "text": "npm i -D rollup postcss@8.1 @rollup/plugin-babel \n@rollup/plugin-commonjs @rollup/plugin-node-resolve \n@rollup/plugin-replace rollup-plugin-livereload \nrollup-plugin-postcss rollup-plugin-serve postcss@8.1 \npostcss-modules@4 rollup-plugin-postcss\n" }, { "code": null, "e": 17264, "s": 17196, "text": "Next, install corejs and regenerator runtime for async programming." }, { "code": null, "e": 17299, "s": 17264, "text": "npm i regenerator-runtime core-js\n" }, { "code": null, "e": 17404, "s": 17299, "text": "Next, create a babel configuration file, .babelrc under the root folder to configure the babel compiler." }, { "code": null, "e": 17700, "s": 17404, "text": "{\n \"presets\": [\n [\n \"@babel/preset-env\",\n {\n \"useBuiltIns\": \"usage\",\n \"corejs\": 3,\n \"targets\": \"> 0.25%, not dead\"\n }\n ],\n \"@babel/preset-react\"\n ],\n \"plugins\": [\n \"@babel/plugin-proposal-class-properties\"\n ]\n}" }, { "code": null, "e": 17789, "s": 17700, "text": "Next, create a rollup.config.js file in the root folder to configure the rollup bundler." }, { "code": null, "e": 18802, "s": 17789, "text": "import babel from '@rollup/plugin-babel';\nimport resolve from '@rollup/plugin-node-resolve';\nimport commonjs from '@rollup/plugin-commonjs';\nimport replace from '@rollup/plugin-replace';\nimport serve from 'rollup-plugin-serve';\nimport livereload from 'rollup-plugin-livereload';\nimport postcss from 'rollup-plugin-postcss'\n\nexport default {\n input: 'src/index.js',\n output: {\n file: 'public/index.js',\n format: 'iife',\n },\n plugins: [\n commonjs({\n include: [\n 'node_modules/**',\n ],\n exclude: [\n 'node_modules/process-es6/**',\n ],\n }),\n resolve(),\n babel({\n exclude: 'node_modules/**'\n }),\n replace({\n 'process.env.NODE_ENV': JSON.stringify('production'),\n }),\n postcss({\n autoModules: true\n }),\n livereload('public'),\n serve({\n contentBase: 'public',\n port: 3000,\n open: true,\n }), // index.html should be in root of project\n ]\n}" }, { "code": null, "e": 18946, "s": 18802, "text": "Next, update the package.json and include our entry point (public/index.js and public/styles.css) and command to build and run the application." }, { "code": null, "e": 19102, "s": 18946, "text": "...\n\"main\": \"public/index.js\",\n\"style\": \"public/styles.css\",\n\"files\": [\n \"public\"\n],\n\"scripts\": {\n \"start\": \"rollup -c -w\",\n \"build\": \"rollup\"\n},\n..." }, { "code": null, "e": 19226, "s": 19102, "text": "Next, create a src folder in the root directory of the application, which will hold all the source code of the application." }, { "code": null, "e": 19442, "s": 19226, "text": "Next, create a folder, components under src to include our React components. The idea is to create two files, <component>.js to write the component logic and <component.css> to include the component specific styles." }, { "code": null, "e": 19502, "s": 19442, "text": "The final structure of the application will be as follows βˆ’" }, { "code": null, "e": 19685, "s": 19502, "text": "|-- package-lock.json\n|-- package.json\n|-- rollup.config.js\n|-- .babelrc\n`-- public\n |-- index.html\n`-- src\n |-- index.js\n `-- components\n | |-- mycom.js\n | |-- mycom.css" }, { "code": null, "e": 19876, "s": 19685, "text": "Let us create a new component, HelloWorld to confirm our setup is working fine. Create a file, HelloWorld.js under components folder and write a simple component to emit Hello World message." }, { "code": null, "e": 20084, "s": 19876, "text": "import React from \"react\";\n\nclass HelloWorld extends React.Component {\n render() {\n return (\n <div>\n <h1>Hello World!</h1>\n </div>\n );\n }\n}\nexport default HelloWorld;" }, { "code": null, "e": 20176, "s": 20084, "text": "Next, create our main file, index.js under src folder and call our newly created component." }, { "code": null, "e": 20410, "s": 20176, "text": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport HelloWorld from './components/HelloWorld';\n\nReactDOM.render(\n <React.StrictMode>\n <HelloWorld />\n </React.StrictMode>,\n document.getElementById('root')\n);" }, { "code": null, "e": 20462, "s": 20410, "text": "Next, create a public folder in the root directory." }, { "code": null, "e": 20573, "s": 20462, "text": "Next, create a html file, index.html (under public folder*), which will be our entry point of the application." }, { "code": null, "e": 20832, "s": 20573, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>Expense Manager :: Rollup version</title>\n </head>\n <body>\n <div id=\"root\"></div>\n <script type=\"text/JavaScript\" src=\"./index.js\"></script>\n </body>\n</html>" }, { "code": null, "e": 20869, "s": 20832, "text": "Next, build and run the application." }, { "code": null, "e": 20880, "s": 20869, "text": "npm start\n" }, { "code": null, "e": 21147, "s": 20880, "text": "The npm build command will execute the rollup and bundle our application into a single file, dist/index.js file and start serving the application. The dev command will recompile the code whenever the source code is changed and also reload the changes in the browser." }, { "code": null, "e": 21456, "s": 21147, "text": "> expense-manager-rollup@1.0.0 build /path/to/your/workspace/expense-manager-rollup \n> rollup -c \nrollup v2.36.1 \nbundles src/index.js β†’ dist\\index.js... \nLiveReload enabled \nhttp://localhost:10001 -> /path/to/your/workspace/expense-manager-rollup/dist \ncreated dist\\index.js in 4.7s \n\nwaiting for changes..." }, { "code": null, "e": 21604, "s": 21456, "text": "Next, open the browser and enter http://localhost:3000 in the address bar and press enter. serve application will serve our webpage as shown below." }, { "code": null, "e": 21829, "s": 21604, "text": "Parcel is fast bundler with zero configuration. It expects just the entry point of the application and it will resolve the dependency itself and bundle the application. Let us learn how to use parcel bundler in this chapter." }, { "code": null, "e": 21864, "s": 21829, "text": "First, install the parcel bundler." }, { "code": null, "e": 21895, "s": 21864, "text": "npm install -g parcel-bundler\n" }, { "code": null, "e": 21937, "s": 21895, "text": "Open a terminal and go to your workspace." }, { "code": null, "e": 21963, "s": 21937, "text": "cd /go/to/your/workspace\n" }, { "code": null, "e": 22097, "s": 21963, "text": "Next, create a folder, expense-manager-parcel and move to newly created folder. Also, open the folder in your favorite editor or IDE." }, { "code": null, "e": 22154, "s": 22097, "text": "mkdir expense-manager-parcel \ncd expense-manager-parcel\n" }, { "code": null, "e": 22195, "s": 22154, "text": "Next, create and initialize the project." }, { "code": null, "e": 22208, "s": 22195, "text": "npm init -y\n" }, { "code": null, "e": 22261, "s": 22208, "text": "Next, install React libraries (react and react-dom)." }, { "code": null, "e": 22313, "s": 22261, "text": "npm install react@^17.0.0 react-dom@^17.0.0 --save\n" }, { "code": null, "e": 22385, "s": 22313, "text": "Next, install babel and its preset libraries as development dependency." }, { "code": null, "e": 22491, "s": 22385, "text": "npm install @babel/preset-env @babel/preset-react @babel/core @babel/plugin-proposal-class-properties -D\n" }, { "code": null, "e": 22596, "s": 22491, "text": "Next, create a babel configuration file, .babelrc under the root folder to configure the babel compiler." }, { "code": null, "e": 22747, "s": 22596, "text": "{\n \"presets\": [\n \"@babel/preset-env\",\n \"@babel/preset-react\"\n ],\n \"plugins\": [\n \"@babel/plugin-proposal-class-properties\"\n ]\n}\n" }, { "code": null, "e": 22867, "s": 22747, "text": "Next, update the package.json and include our entry point (src/index.js) and commands to build and run the application." }, { "code": null, "e": 23019, "s": 22867, "text": "... \n\"main\": \"src/index.js\", \n\"scripts\": {\n \"start\": \"parcel public/index.html\",\n \"build\": \"parcel build public/index.html --out-dir dist\" \n},\n...\n" }, { "code": null, "e": 23143, "s": 23019, "text": "Next, create a src folder in the root directory of the application, which will hold all the source code of the application." }, { "code": null, "e": 23359, "s": 23143, "text": "Next, create a folder, components under src to include our React components. The idea is to create two files, <component>.js to write the component logic and <component.css> to include the component specific styles." }, { "code": null, "e": 23419, "s": 23359, "text": "The final structure of the application will be as follows βˆ’" }, { "code": null, "e": 23582, "s": 23419, "text": "|-- package-lock.json\n|-- package.json\n|-- .babelrc\n`-- public\n |-- index.html\n`-- src\n |-- index.js\n `-- components\n | |-- mycom.js\n | |-- mycom.css\n" }, { "code": null, "e": 23773, "s": 23582, "text": "Let us create a new component, HelloWorld to confirm our setup is working fine. Create a file, HelloWorld.js under components folder and write a simple component to emit Hello World message." }, { "code": null, "e": 23981, "s": 23773, "text": "import React from \"react\";\n\nclass HelloWorld extends React.Component {\n render() {\n return (\n <div>\n <h1>Hello World!</h1>\n </div>\n );\n }\n}\nexport default HelloWorld;" }, { "code": null, "e": 24073, "s": 23981, "text": "Next, create our main file, index.js under src folder and call our newly created component." }, { "code": null, "e": 24307, "s": 24073, "text": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport HelloWorld from './components/HelloWorld';\n\nReactDOM.render(\n <React.StrictMode>\n <HelloWorld />\n </React.StrictMode>,\n document.getElementById('root')\n);" }, { "code": null, "e": 24359, "s": 24307, "text": "Next, create a public folder in the root directory." }, { "code": null, "e": 24470, "s": 24359, "text": "Next, create a html file, index.html (in the public folder), which will be our entry point of the application." }, { "code": null, "e": 24734, "s": 24470, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>Expense Manager :: Parcel version</title>\n </head>\n <body>\n <div id=\"root\"></div>\n <script type=\"text/JavaScript\" src=\"../src/index.js\"></script>\n </body>\n</html>" }, { "code": null, "e": 24771, "s": 24734, "text": "Next, build and run the application." }, { "code": null, "e": 24782, "s": 24771, "text": "npm start\n" }, { "code": null, "e": 24984, "s": 24782, "text": "The npm build command will execute the parcel command. It will bundle and serve the application on the fly. It recompiles whenever the source code is changed and also reload the changes in the browser." }, { "code": null, "e": 25146, "s": 24984, "text": "> expense-manager-parcel@1.0.0 dev /go/to/your/workspace/expense-manager-parcel \n> parcel index.html Server running at http://localhost:1234 \n√ Built in 10.41s.\n" }, { "code": null, "e": 25237, "s": 25146, "text": "Next, open the browser and enter http://localhost:1234 in the address bar and press enter." }, { "code": null, "e": 25427, "s": 25237, "text": "To create the production bundle of the application to deploy it in production server, use build command. It will generate a index.js file with all the bundled source code under dist folder." }, { "code": null, "e": 25727, "s": 25427, "text": "npm run build\n> expense-manager-parcel@1.0.0 build /go/to/your/workspace/expense-manager-parcel\n> parcel build index.html --out-dir dist\n\n√ Built in 6.42s.\n\ndist\\src.80621d09.js.map 270.23 KB 79ms\ndist\\src.80621d09.js 131.49 KB 4.67s\ndist\\index.html 221 B 1.63s\n" }, { "code": null, "e": 26054, "s": 25727, "text": "As we learned earlier, React JSX is an extension to JavaScript. It enables developer to create virtual DOM using XML syntax. It compiles down to pure JavaScript (React.createElement function calls). Since it compiles to JavaScript, it can be used inside any valid JavaScript code. For example, below codes are perfectly valid." }, { "code": null, "e": 26076, "s": 26054, "text": "Assign to a variable." }, { "code": null, "e": 26114, "s": 26076, "text": "var greeting = <h1>Hello React!</h1>\n" }, { "code": null, "e": 26157, "s": 26114, "text": "Assign to a variable based on a condition." }, { "code": null, "e": 26235, "s": 26157, "text": "var canGreet = true; \nif(canGreet) { \n greeting = <h1>Hello React!</h1> \n}\n" }, { "code": null, "e": 26278, "s": 26235, "text": "Can be used as return value of a function." }, { "code": null, "e": 26364, "s": 26278, "text": "function Greeting() { \n return <h1>Hello React!</h1> \n \n} \ngreeting = Greeting()\n" }, { "code": null, "e": 26403, "s": 26364, "text": "Can be used as argument of a function." }, { "code": null, "e": 26529, "s": 26403, "text": "function Greet(message) { \n ReactDOM.render(message, document.getElementById('react-app') \n} \nGreet(<h1>Hello React!</h1>)\n" }, { "code": null, "e": 26771, "s": 26529, "text": "JSX supports expression in pure JavaScript syntax. Expression has to be enclosed inside the curly braces, { }. Expression can contain all variables available in the context, where the JSX is defined. Let us create simple JSX with expression." }, { "code": null, "e": 26970, "s": 26771, "text": "<script type=\"text/babel\">\n var cTime = new Date().toTimeString();\n ReactDOM.render(\n <div><p>The current time is {cTime}</p></div>, \n document.getElementById('react-app') );\n</script>" }, { "code": null, "e": 27060, "s": 26970, "text": "Here, cTime used in the JSX using expression. The output of the above code is as follows," }, { "code": null, "e": 27120, "s": 27060, "text": "The Current time is 21:19:56 GMT+0530(India Standard Time)\n" }, { "code": null, "e": 27267, "s": 27120, "text": "One of the positive side effects of using expression in JSX is that it prevents Injection attacks as it converts any string into html safe string." }, { "code": null, "e": 27410, "s": 27267, "text": "JSX supports user defined JavaScript function. Function usage is similar to expression. Let us create a simple function and use it inside JSX." }, { "code": null, "e": 27613, "s": 27410, "text": "<script type=\"text/babel\">\n var cTime = new Date().toTimeString();\n ReactDOM.render(\n <div><p>The current time is {cTime}</p></div>, \n document.getElementById('react-app') \n );\n</script>" }, { "code": null, "e": 27712, "s": 27613, "text": "Here, getCurrentTime() is used get the current time and the output is similar as specified below βˆ’" }, { "code": null, "e": 27772, "s": 27712, "text": "The Current time is 21:19:56 GMT+0530(India Standard Time)\n" }, { "code": null, "e": 28096, "s": 27772, "text": "JSX supports HTML like attributes. All HTML tags and its attributes are supported. Attributes has to be specified using camelCase convention (and it follows JavaScript DOM API) instead of normal HTML attribute name. For example, class attribute in HTML has to be defined as className. The following are few other examples βˆ’" }, { "code": null, "e": 28119, "s": 28096, "text": "htmlFor instead of for" }, { "code": null, "e": 28148, "s": 28119, "text": "tabIndex instead of tabindex" }, { "code": null, "e": 28175, "s": 28148, "text": "onClick instead of onclick" }, { "code": null, "e": 28508, "s": 28175, "text": "<style>\n .red { color: red }\n</style>\n<script type=\"text/babel\">\n function getCurrentTime() {\n return new Date().toTimeString();\n }\n ReactDOM.render(\n <div>\n <p>The current time is <span className=\"red\">{getCurrentTime()}</span></p>\n </div>,\n document.getElementById('react-app') \n );\n</script>" }, { "code": null, "e": 28535, "s": 28508, "text": "The output is as follows βˆ’" }, { "code": null, "e": 28595, "s": 28535, "text": "The Current time is 22:36:55 GMT+0530(India Standard Time)\n" }, { "code": null, "e": 28857, "s": 28595, "text": "JSX supports expression to be specified inside the attributes. In attributes, double quote should not be used along with expression. Either expression or string using double quote has to be used. The above example can be changed to use expression in attributes." }, { "code": null, "e": 29226, "s": 28857, "text": "<style>\n .red { color: red }\n</style>\n\n<script type=\"text/babel\">\n function getCurrentTime() {\n return new Date().toTimeString();\n }\n var class_name = \"red\";\n ReactDOM.render(\n <div>\n <p>The current time is <span className={class_name}>{getCurrentTime()}</span></p>\n </div>, \n document.getElementById('react-app') \n );\n</script>" }, { "code": null, "e": 29391, "s": 29226, "text": "React component is the building block of a React application. Let us learn how to create a new React component and the features of React components in this chapter." }, { "code": null, "e": 29737, "s": 29391, "text": "A React component represents a small chunk of user interface in a webpage. The primary job of a React component is to render its user interface and update it whenever its internal state is changed. In addition to rendering the UI, it manages the events belongs to its user interface. To summarize, React component provides below functionalities." }, { "code": null, "e": 29778, "s": 29737, "text": "Initial rendering of the user interface." }, { "code": null, "e": 29813, "s": 29778, "text": "Management and handling of events." }, { "code": null, "e": 29881, "s": 29813, "text": "Updating the user interface whenever the internal state is changed." }, { "code": null, "e": 29945, "s": 29881, "text": "React component accomplish these feature using three concepts βˆ’" }, { "code": null, "e": 29998, "s": 29945, "text": "Properties βˆ’ Enables the component to receive input." }, { "code": null, "e": 30051, "s": 29998, "text": "Properties βˆ’ Enables the component to receive input." }, { "code": null, "e": 30128, "s": 30051, "text": "Events βˆ’ Enable the component to manage DOM events and end-user interaction." }, { "code": null, "e": 30205, "s": 30128, "text": "Events βˆ’ Enable the component to manage DOM events and end-user interaction." }, { "code": null, "e": 30313, "s": 30205, "text": "State βˆ’ Enable the component to stay stateful. Stateful component updates its UI with respect to its state." }, { "code": null, "e": 30421, "s": 30313, "text": "State βˆ’ Enable the component to stay stateful. Stateful component updates its UI with respect to its state." }, { "code": null, "e": 30487, "s": 30421, "text": "Let us learn all the concept one-by-one in the upcoming chapters." }, { "code": null, "e": 30590, "s": 30487, "text": "React library has two component types. The types are categorized based on the way it is being created." }, { "code": null, "e": 30643, "s": 30590, "text": "Function component βˆ’ Uses plain JavaScript function." }, { "code": null, "e": 30681, "s": 30643, "text": "ES6 class component βˆ’ Uses ES6 class." }, { "code": null, "e": 30744, "s": 30681, "text": "The core difference between function and class component are βˆ’" }, { "code": null, "e": 30843, "s": 30744, "text": "Function components are very minimal in nature. Its only requirement is to return a React element." }, { "code": null, "e": 30942, "s": 30843, "text": "Function components are very minimal in nature. Its only requirement is to return a React element." }, { "code": null, "e": 30994, "s": 30942, "text": "function Hello() { \n return '<div>Hello</div>' \n}" }, { "code": null, "e": 31081, "s": 30994, "text": "The same functionality can be done using ES6 class component with little extra coding." }, { "code": null, "e": 31214, "s": 31081, "text": "class ExpenseEntryItem extends React.Component { \n render() { \n return ( \n <div>Hello</div> \n ); \n }\n}" }, { "code": null, "e": 31425, "s": 31214, "text": "Class components supports state management out of the box whereas function components does not support state management. But, React provides a hook, useState() for the function components to maintain its state." }, { "code": null, "e": 31636, "s": 31425, "text": "Class components supports state management out of the box whereas function components does not support state management. But, React provides a hook, useState() for the function components to maintain its state." }, { "code": null, "e": 31899, "s": 31636, "text": "Class component have a life cycle and access to each life cycle events through dedicated callback apis. Function component does not have life cycle. Again, React provides a hook, useEffect() for the function component to access different stages of the component." }, { "code": null, "e": 32162, "s": 31899, "text": "Class component have a life cycle and access to each life cycle events through dedicated callback apis. Function component does not have life cycle. Again, React provides a hook, useEffect() for the function component to access different stages of the component." }, { "code": null, "e": 32401, "s": 32162, "text": "Let us create a new React component (in our expense-manager app), ExpenseEntryItem to showcase an expense entry item. Expense entry item consists of name, amount, date and category. The object representation of the expense entry item is βˆ’" }, { "code": null, "e": 32509, "s": 32401, "text": "{ \n 'name': 'Mango juice', \n 'amount': 30.00, \n 'spend_date': '2020-10-10' \n 'category': 'Food', \n}" }, { "code": null, "e": 32567, "s": 32509, "text": "Open expense-manager application in your favorite editor." }, { "code": null, "e": 32661, "s": 32567, "text": "Next, create a file, ExpenseEntryItem.css under src/components folder to style our component." }, { "code": null, "e": 32760, "s": 32661, "text": "Next, create a file, ExpenseEntryItem.js under src/components folder by extending React.Component." }, { "code": null, "e": 32874, "s": 32760, "text": "import React from 'react'; \nimport './ExpenseEntryItem.css'; \nclass ExpenseEntryItem extends React.Component { \n}" }, { "code": null, "e": 32938, "s": 32874, "text": "Next, create a method render inside the ExpenseEntryItem class." }, { "code": null, "e": 33011, "s": 32938, "text": "class ExpenseEntryItem extends React.Component { \n render() { \n } \n}" }, { "code": null, "e": 33087, "s": 33011, "text": "Next, create the user interface using JSX and return it from render method." }, { "code": null, "e": 33438, "s": 33087, "text": "class ExpenseEntryItem extends React.Component {\n render() {\n return (\n <div>\n <div><b>Item:</b> <em>Mango Juice</em></div>\n <div><b>Amount:</b> <em>30.00</em></div>\n <div><b>Spend Date:</b> <em>2020-10-10</em></div>\n <div><b>Category:</b> <em>Food</em></div>\n </div>\n );\n }\n}" }, { "code": null, "e": 33491, "s": 33438, "text": "Next, specify the component as default export class." }, { "code": null, "e": 33936, "s": 33491, "text": "import React from 'react';\nimport './ExpenseEntryItem.css';\n\nclass ExpenseEntryItem extends React.Component {\n render() {\n return (\n <div>\n <div><b>Item:</b> <em>Mango Juice</em></div>\n <div><b>Amount:</b> <em>30.00</em></div>\n <div><b>Spend Date:</b> <em>2020-10-10</em></div>\n <div><b>Category:</b> <em>Food</em></div>\n </div>\n );\n }\n}\nexport default ExpenseEntryItem;" }, { "code": null, "e": 34044, "s": 33936, "text": "Now, we successfully created our first React component. Let us use our newly created component in index.js." }, { "code": null, "e": 34295, "s": 34044, "text": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport ExpenseEntryItem from './components/ExpenseEntryItem'\n\nReactDOM.render(\n <React.StrictMode>\n <ExpenseEntryItem />\n </React.StrictMode>,\n document.getElementById('root')\n);" }, { "code": null, "e": 34370, "s": 34295, "text": "The same functionality can be done in a webpage using CDN as shown below βˆ’" }, { "code": null, "e": 35479, "s": 34370, "text": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"UTF-8\" />\n <title>React application :: ExpenseEntryItem component</title>\n </head>\n <body>\n <div id=\"react-app\"></div>\n \n <script src=\"https://unpkg.com/react@17/umd/react.development.js\" crossorigin></script>\n <script src=\"https://unpkg.com/react-dom@17/umd/react-dom.development.js\" crossorigin></script>\n <script src=\"https://unpkg.com/@babel/standalone/babel.min.js\"></script>\n <script type=\"text/babel\">\n class ExpenseEntryItem extends React.Component {\n render() {\n return (\n <div>\n <div><b>Item:</b> <em>Mango Juice</em></div>\n <div><b>Amount:</b> <em>30.00</em></div>\n <div><b>Spend Date:</b> <em>2020-10-10</em></div>\n <div><b>Category:</b> <em>Food</em></div>\n </div>\n );\n }\n }\n ReactDOM.render(\n <ExpenseEntryItem />,\n document.getElementById('react-app') );\n </script>\n </body>\n</html>" }, { "code": null, "e": 35526, "s": 35479, "text": "Next, serve the application using npm command." }, { "code": null, "e": 35537, "s": 35526, "text": "npm start\n" }, { "code": null, "e": 35628, "s": 35537, "text": "Next, open the browser and enter http://localhost:3000 in the address bar and press enter." }, { "code": null, "e": 35699, "s": 35628, "text": "Item: Mango Juice\nAmount: 30.00\nSpend Date: 2020-10-10\nCategory: Food\n" }, { "code": null, "e": 35941, "s": 35699, "text": "React component can also be created using plain JavaScript function but with limited features. Function based React component does not support state management and other advanced features. It can be used to quickly create a simple component." }, { "code": null, "e": 36018, "s": 35941, "text": "The above ExpenseEntryItem can be rewritten in function as specified below βˆ’" }, { "code": null, "e": 36307, "s": 36018, "text": "function ExpenseEntryItem() {\n return (\n <div>\n <div><b>Item:</b> <em>Mango Juice</em></div>\n <div><b>Amount:</b> <em>30.00</em></div>\n <div><b>Spend Date:</b> <em>2020-10-10</em></div>\n <div><b>Category:</b> <em>Food</em></div>\n </div>\n );\n}" }, { "code": null, "e": 36408, "s": 36307, "text": "Here, we just included the render functionality and it is enough to create a simple React component." }, { "code": null, "e": 36640, "s": 36408, "text": "In general, React allows component to be styled using CSS class through className attribute. Since, the React JSX supports JavaScript expression, a lot of common CSS methodology can be used. Some of the top options are as follows βˆ’" }, { "code": null, "e": 36696, "s": 36640, "text": "CSS stylesheet βˆ’ Normal CSS styles along with className" }, { "code": null, "e": 36752, "s": 36696, "text": "CSS stylesheet βˆ’ Normal CSS styles along with className" }, { "code": null, "e": 36835, "s": 36752, "text": "Inline styling βˆ’ CSS styles as JavaScript objects along with camelCase properties." }, { "code": null, "e": 36918, "s": 36835, "text": "Inline styling βˆ’ CSS styles as JavaScript objects along with camelCase properties." }, { "code": null, "e": 36959, "s": 36918, "text": "CSS Modules βˆ’ Locally scoped CSS styles." }, { "code": null, "e": 37000, "s": 36959, "text": "CSS Modules βˆ’ Locally scoped CSS styles." }, { "code": null, "e": 37043, "s": 37000, "text": "Styled component βˆ’ Component level styles." }, { "code": null, "e": 37086, "s": 37043, "text": "Styled component βˆ’ Component level styles." }, { "code": null, "e": 37189, "s": 37086, "text": "Sass stylesheet βˆ’ Supports Sass based CSS styles by converting the styles to normal css at build time." }, { "code": null, "e": 37292, "s": 37189, "text": "Sass stylesheet βˆ’ Supports Sass based CSS styles by converting the styles to normal css at build time." }, { "code": null, "e": 37407, "s": 37292, "text": "Post processing stylesheet βˆ’ Supports Post processing styles by converting the styles to normal css at build time." }, { "code": null, "e": 37522, "s": 37407, "text": "Post processing stylesheet βˆ’ Supports Post processing styles by converting the styles to normal css at build time." }, { "code": null, "e": 37621, "s": 37522, "text": "Let use learn how to apply the three important methodology to style our component in this chapter." }, { "code": null, "e": 37636, "s": 37621, "text": "CSS Stylesheet" }, { "code": null, "e": 37651, "s": 37636, "text": "CSS Stylesheet" }, { "code": null, "e": 37666, "s": 37651, "text": "Inline Styling" }, { "code": null, "e": 37681, "s": 37666, "text": "Inline Styling" }, { "code": null, "e": 37693, "s": 37681, "text": "CSS Modules" }, { "code": null, "e": 37705, "s": 37693, "text": "CSS Modules" }, { "code": null, "e": 37929, "s": 37705, "text": "CSS stylesheet is usual, common and time-tested methodology. Simply create a CSS stylesheet for a component and enter all your styles for that particular component. Then, in the component, use className to refer the styles." }, { "code": null, "e": 37974, "s": 37929, "text": "Let us style our ExpenseEntryItem component." }, { "code": null, "e": 38032, "s": 37974, "text": "Open expense-manager application in your favorite editor." }, { "code": null, "e": 38089, "s": 38032, "text": "Next, open ExpenseEntryItem.css file and add few styles." }, { "code": null, "e": 38148, "s": 38089, "text": "div.itemStyle { \n color: brown; \n font-size: 14px; \n}\n" }, { "code": null, "e": 38220, "s": 38148, "text": "Next, open ExpenseEntryItem.js and add className to the main container." }, { "code": null, "e": 38687, "s": 38220, "text": "import React from 'react';\nimport './ExpenseEntryItem.css';\n\nclass ExpenseEntryItem extends React.Component {\n render() {\n return (\n <div className=\"itemStyle\">\n <div><b>Item:</b> <em>Mango Juice</em></div>\n <div><b>Amount:</b> <em>30.00</em></div>\n <div><b>Spend Date:</b> <em>2020-10-10</em></div>\n <div><b>Category:</b> <em>Food</em></div>\n </div>\n );\n }\n}\nexport default ExpenseEntryItem;" }, { "code": null, "e": 38734, "s": 38687, "text": "Next, serve the application using npm command." }, { "code": null, "e": 38745, "s": 38734, "text": "npm start\n" }, { "code": null, "e": 38836, "s": 38745, "text": "Next, open the browser and enter http://localhost:3000 in the address bar and press enter." }, { "code": null, "e": 39125, "s": 38836, "text": "CSS stylesheet is easy to understand and use. But, when the project size increases, CSS styles will also increase and ultimately create lot of conflict in the class name. Moreover, loading the CSS file directly is only supported in Webpack bundler and it may not supported in other tools." }, { "code": null, "e": 39330, "s": 39125, "text": "Inline Styling is one of the safest ways to style the React component. It declares all the styles as JavaScript objects using DOM based css properties and set it to the component through style attributes." }, { "code": null, "e": 39374, "s": 39330, "text": "Let us add inline styling in our component." }, { "code": null, "e": 39540, "s": 39374, "text": "Open expense-manager application in your favorite editor and modify ExpenseEntryItem.js file in the src folder. Declare a variable of type object and set the styles." }, { "code": null, "e": 39598, "s": 39540, "text": "itemStyle = {\n color: 'brown', \n fontSize: '14px' \n}\n" }, { "code": null, "e": 39723, "s": 39598, "text": "Here, fontSize represent the css property, font-size. All css properties can be used by representing it in camelCase format." }, { "code": null, "e": 39790, "s": 39723, "text": "Next, set itemStyle style in the component using curly braces {} βˆ’" }, { "code": null, "e": 40085, "s": 39790, "text": "render() {\n return (\n <div style={ this.itemStyle }>\n <div><b>Item:</b> <em>Mango Juice</em></div>\n <div><b>Amount:</b> <em>30.00</em></div>\n <div><b>Spend Date:</b> <em>2020-10-10</em></div>\n <div><b>Category:</b> <em>Food</em></div>\n </div>\n );\n}" }, { "code": null, "e": 40140, "s": 40085, "text": "Also, style can be directly set inside the component βˆ’" }, { "code": null, "e": 40514, "s": 40140, "text": "render() {\n return (\n <div style={\n {\n color: 'brown',\n fontSize: '14px'\n } \n }>\n <div><b>Item:</b> <em>Mango Juice</em></div>\n <div><b>Amount:</b> <em>30.00</em></div>\n <div><b>Spend Date:</b> <em>2020-10-10</em></div>\n <div><b>Category:</b> <em>Food</em></div>\n </div>\n );\n}" }, { "code": null, "e": 40584, "s": 40514, "text": "Now, we have successfully used the inline styling in our application." }, { "code": null, "e": 40631, "s": 40584, "text": "Next, serve the application using npm command." }, { "code": null, "e": 40642, "s": 40631, "text": "npm start\n" }, { "code": null, "e": 40733, "s": 40642, "text": "Next, open the browser and enter http://localhost:3000 in the address bar and press enter." }, { "code": null, "e": 41037, "s": 40733, "text": "Css Modules provides safest as well as easiest way to define the style. It uses normal css stylesheet with normal syntax. While importing the styles, CSS modules converts all the styles into locally scoped styles so that the name conflicts will not happen. Let us change our component to use CSS modules" }, { "code": null, "e": 41095, "s": 41037, "text": "Open expense-manager application in your favorite editor." }, { "code": null, "e": 41217, "s": 41095, "text": "Next, create a new stylesheet, ExpenseEntryItem.module.css file under src/components folder and write regular css styles." }, { "code": null, "e": 41277, "s": 41217, "text": "div.itemStyle {\n color: 'brown'; \n font-size: 14px; \n}\n" }, { "code": null, "e": 41473, "s": 41277, "text": "Here, file naming convention is very important. React toolchain will pre-process the css files ending with .module.css through CSS Module. Otherwise, it will be considered as a normal stylesheet." }, { "code": null, "e": 41560, "s": 41473, "text": "Next, open ExpenseEntryItem.js file in the src/component folder and import the styles." }, { "code": null, "e": 41612, "s": 41560, "text": "import styles from './ExpenseEntryItem.module.css'\n" }, { "code": null, "e": 41676, "s": 41612, "text": "Next, use the styles as JavaScript expression in the component." }, { "code": null, "e": 41712, "s": 41676, "text": "<div className={styles.itemStyle}>\n" }, { "code": null, "e": 41779, "s": 41712, "text": "Now, we have successfully used the CSS modules in our application." }, { "code": null, "e": 41812, "s": 41779, "text": "The final and complete code is βˆ’" }, { "code": null, "e": 42338, "s": 41812, "text": "import React from 'react';\nimport './ExpenseEntryItem.css';\nimport styles from './ExpenseEntryItem.module.css'\n\nclass ExpenseEntryItem extends React.Component {\n render() {\n return (\n <div className={styles.itemStyle} >\n <div><b>Item:</b> <em>Mango Juice</em></div>\n <div><b>Amount:</b> <em>30.00</em></div>\n <div><b>Spend Date:</b> <em>2020-10-10</em></div>\n <div><b>Category:</b> <em>Food</em></div>\n </div>\n );\n }\n}\nexport default ExpenseEntryItem;" }, { "code": null, "e": 42385, "s": 42338, "text": "Next, serve the application using npm command." }, { "code": null, "e": 42396, "s": 42385, "text": "npm start\n" }, { "code": null, "e": 42487, "s": 42396, "text": "Next, open the browser and enter http://localhost:3000 in the address bar and press enter." }, { "code": null, "e": 42724, "s": 42487, "text": "React enables developers to create dynamic and advanced component using properties. Every component can have attributes similar to HTML attributes and each attribute’s value can be accessed inside the component using properties (props)." }, { "code": null, "e": 42846, "s": 42724, "text": "For example, Hello component with a name attribute can be accessed inside the component through this.props.name variable." }, { "code": null, "e": 42932, "s": 42846, "text": "<Hello name=\"React\" />\n// value of name will be \"Hello* const name = this.props.name\n" }, { "code": null, "e": 43017, "s": 42932, "text": "React properties supports attribute’s value of different types. They are as follows," }, { "code": null, "e": 43024, "s": 43017, "text": "String" }, { "code": null, "e": 43031, "s": 43024, "text": "Number" }, { "code": null, "e": 43040, "s": 43031, "text": "Datetime" }, { "code": null, "e": 43046, "s": 43040, "text": "Array" }, { "code": null, "e": 43051, "s": 43046, "text": "List" }, { "code": null, "e": 43059, "s": 43051, "text": "Objects" }, { "code": null, "e": 43100, "s": 43059, "text": "Let us learn one by one in this chapter." }, { "code": null, "e": 43136, "s": 43100, "text": "Create a component using Properties" }, { "code": null, "e": 43172, "s": 43136, "text": "Create a component using Properties" }, { "code": null, "e": 43190, "s": 43172, "text": "Nested Components" }, { "code": null, "e": 43208, "s": 43190, "text": "Nested Components" }, { "code": null, "e": 43222, "s": 43208, "text": "Use Component" }, { "code": null, "e": 43236, "s": 43222, "text": "Use Component" }, { "code": null, "e": 43257, "s": 43236, "text": "Component Collection" }, { "code": null, "e": 43278, "s": 43257, "text": "Component Collection" }, { "code": null, "e": 43607, "s": 43278, "text": "Event management is one of the important features in a web application. It enables the user to interact with the application. React support all events available in a web application. React event handling is very similar to DOM events with little changes. Let us learn how to handle events in a React application in this chapter." }, { "code": null, "e": 43686, "s": 43607, "text": "Let us see the step-by-step process of handling an event in a React component." }, { "code": null, "e": 43744, "s": 43686, "text": "Define an event handler method to handle the given event." }, { "code": null, "e": 43802, "s": 43744, "text": "Define an event handler method to handle the given event." }, { "code": null, "e": 43847, "s": 43802, "text": "log() { \n cosole.log(\"Event is fired\"); \n}" }, { "code": null, "e": 43954, "s": 43847, "text": "React provides an alternative syntax using lambda function to define event handler. The lambda syntax is βˆ’" }, { "code": null, "e": 44006, "s": 43954, "text": "log = () =;> { \n cosole.log(\"Event is fired\"); \n}" }, { "code": null, "e": 44161, "s": 44006, "text": "If you want to know the target of the event, then add an argument e in the handler method. React will send the event target details to the handler method." }, { "code": null, "e": 44234, "s": 44161, "text": "log(e) { \n cosole.log(\"Event is fired\"); \n console.log(e.target); \n}" }, { "code": null, "e": 44269, "s": 44234, "text": "The alternative lambda syntax is βˆ’" }, { "code": null, "e": 44348, "s": 44269, "text": "log = (e) => { \n cosole.log(\"Event is fired\"); \n console.log(e.target); \n}" }, { "code": null, "e": 44490, "s": 44348, "text": "If you want to send extra details during an event, then add the extra details as initial argument and then add argument (e) for event target." }, { "code": null, "e": 44617, "s": 44490, "text": "log(extra, e) { \n cosole.log(\"Event is fired\"); \n console.log(e.target); \n console.log(extra); \n console.log(this); \n}" }, { "code": null, "e": 44663, "s": 44617, "text": "The alternative lambda syntax is as follows βˆ’" }, { "code": null, "e": 44796, "s": 44663, "text": "log = (extra, e) => { \n cosole.log(\"Event is fired\"); \n console.log(e.target); \n console.log(extra); \n console.log(this); \n}" }, { "code": null, "e": 44934, "s": 44796, "text": "Bind the event handler method in the constructor of the component. This will ensure the availability of this in the event handler method." }, { "code": null, "e": 45026, "s": 44934, "text": "constructor(props) { \n super(props); \n this.logContent = this.logContent.bind(this); \n}" }, { "code": null, "e": 45188, "s": 45026, "text": "If the event handler is defined in alternate lambda syntax, then the binding is not needed. this keyword will be automatically bound to the event handler method." }, { "code": null, "e": 45261, "s": 45188, "text": "Set the event handler method for the specific event as specified below βˆ’" }, { "code": null, "e": 45298, "s": 45261, "text": "<div onClick={this.log}> ... </div>\n" }, { "code": null, "e": 45408, "s": 45298, "text": "To set extra arguments, bind the event handler method and then pass the extra information as second argument." }, { "code": null, "e": 45463, "s": 45408, "text": "<div onClick={this.log.bind(this, extra)}> ... </div>\n" }, { "code": null, "e": 45507, "s": 45463, "text": "The alternate lambda syntax is as follows βˆ’" }, { "code": null, "e": 45554, "s": 45507, "text": "<div onClick={this.log(extra, e)}> ... </div>\n" }, { "code": null, "e": 45560, "s": 45554, "text": "Here," }, { "code": null, "e": 45591, "s": 45560, "text": "Create a event-aware component" }, { "code": null, "e": 45622, "s": 45591, "text": "Create a event-aware component" }, { "code": null, "e": 45662, "s": 45622, "text": "Introduce events in Expense manager app" }, { "code": null, "e": 45702, "s": 45662, "text": "Introduce events in Expense manager app" }, { "code": null, "e": 45965, "s": 45702, "text": "State management is one of the important and unavoidable features of any dynamic application. React provides a simple and flexible API to support state management in a React component. Let us understand how to maintain state in React application in this chapter." }, { "code": null, "e": 46386, "s": 45965, "text": "State represents the value of a dynamic properties of a React component at a given instance. React provides a dynamic data store for each component. The internal data represents the state of a React component and can be accessed using this.state member variable of the component. Whenever the state of the component is changed, the component will re-render itself by calling the render() method along with the new state." }, { "code": null, "e": 46895, "s": 46386, "text": "A simple example to better understand the state management is to analyse a real-time clock component. The clock component primary job is to show the date and time of a location at the given instance. As the current time will change every second, the clock component should maintain the current date and time in it’s state. As the state of the clock component changes every second, the clock’s render() method will be called every second and the render() method show the current time using it’s current state." }, { "code": null, "e": 46950, "s": 46895, "text": "The simple representation of the state is as follows βˆ’" }, { "code": null, "e": 46988, "s": 46950, "text": "{ \n date: '2020-10-10 10:10:10' \n}\n" }, { "code": null, "e": 47047, "s": 46988, "text": "Let us create a new Clock component later in this chapter." }, { "code": null, "e": 47053, "s": 47047, "text": "Here," }, { "code": null, "e": 47074, "s": 47053, "text": "State management API" }, { "code": null, "e": 47095, "s": 47074, "text": "State management API" }, { "code": null, "e": 47115, "s": 47095, "text": "Stateless component" }, { "code": null, "e": 47135, "s": 47115, "text": "Stateless component" }, { "code": null, "e": 47170, "s": 47135, "text": "State management using React Hooks" }, { "code": null, "e": 47205, "s": 47170, "text": "State management using React Hooks" }, { "code": null, "e": 47226, "s": 47205, "text": "Component Life cycle" }, { "code": null, "e": 47247, "s": 47226, "text": "Component Life cycle" }, { "code": null, "e": 47286, "s": 47247, "text": "Component life cycle using React Hooks" }, { "code": null, "e": 47325, "s": 47286, "text": "Component life cycle using React Hooks" }, { "code": null, "e": 47345, "s": 47325, "text": "Layout in component" }, { "code": null, "e": 47365, "s": 47345, "text": "Layout in component" }, { "code": null, "e": 47376, "s": 47365, "text": "Pagination" }, { "code": null, "e": 47387, "s": 47376, "text": "Pagination" }, { "code": null, "e": 47399, "s": 47387, "text": "Material UI" }, { "code": null, "e": 47411, "s": 47399, "text": "Material UI" }, { "code": null, "e": 47789, "s": 47411, "text": "Http client programming enables the application to connect and fetch data from http server through JavaScript. It reduces the data transfer between client and server as it fetches only the required data instead of the whole design and subsequently improves the network speed. It improves the user experience and becomes an indispensable feature of every modern web application." }, { "code": null, "e": 47972, "s": 47789, "text": "Nowadays, lot of server side application exposes its functionality through REST API (functionality over HTTP protocol) and allows any client application to consume the functionality." }, { "code": null, "e": 48318, "s": 47972, "text": "React does not provide it’s own http programming api but it supports browser’s built-in fetch() api as well as third party client library like axios to do client side programming. Let us learn how to do http programming in React application in this chapter. Developer should have a basic knowledge in Http programming to understand this chapter." }, { "code": null, "e": 48619, "s": 48318, "text": "The prerequisite to do Http programming is the basic knowledge of Http protocol and REST API technique. Http programming involves two part, server and client. React provides support to create client side application. Express a popular web framework provides support to create server side application." }, { "code": null, "e": 48780, "s": 48619, "text": "Let us first create a Expense Rest Api server using express framework and then access it from our ExpenseManager application using browser’s built-in fetch api." }, { "code": null, "e": 48845, "s": 48780, "text": "Open a command prompt and create a new folder, express-rest-api." }, { "code": null, "e": 48897, "s": 48845, "text": "cd /go/to/workspace \nmkdir apiserver \ncd apiserver\n" }, { "code": null, "e": 48957, "s": 48897, "text": "Initialize a new node application using the below command βˆ’" }, { "code": null, "e": 48967, "s": 48957, "text": "npm init\n" }, { "code": null, "e": 49153, "s": 48967, "text": "The npm init will prompt and ask us to enter basic project details. Let us enter apiserver for project name and server.js for entry point. Leave other configuration with default option." }, { "code": null, "e": 50059, "s": 49153, "text": "This utility will walk you through creating a package.json file.\nIt only covers the most common items, and tries to guess sensible defaults.\n\nSee `npm help json` for definitive documentation on these fields and exactly what they do.\n\nUse `npm install <pkg>` afterwards to install a package and\nsave it as a dependency in the package.json file.\n\nPress ^C at any time to quit.\npackage name: (apiserver)\nversion: (1.0.0)\ndescription: Rest api for Expense Application\nentry point: (index.js) server.js\ntest command:\ngit repository:\nkeywords:\nauthor:\nlicense: (ISC)\nAbout to write to \\path\\to\\workspace\\expense-rest-api\\package.json:\n{\n \"name\": \"expense-rest-api\",\n \"version\": \"1.0.0\",\n \"description\": \"Rest api for Expense Application\",\n \"main\": \"server.js\",\n \"scripts\": {\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n },\n \"author\": \"\",\n \"license\": \"ISC\"\n}\nIs this OK? (yes) yes" }, { "code": null, "e": 50124, "s": 50059, "text": "Next, install express, nedb & cors modules using below command βˆ’" }, { "code": null, "e": 50155, "s": 50124, "text": "npm install express nedb cors\n" }, { "code": null, "e": 50206, "s": 50155, "text": "express is used to create server side application." }, { "code": null, "e": 50257, "s": 50206, "text": "express is used to create server side application." }, { "code": null, "e": 50309, "s": 50257, "text": "nedb is a datastore used to store the expense data." }, { "code": null, "e": 50361, "s": 50309, "text": "nedb is a datastore used to store the expense data." }, { "code": null, "e": 50444, "s": 50361, "text": "cors is a middleware for express framework to configure the client access details." }, { "code": null, "e": 50527, "s": 50444, "text": "cors is a middleware for express framework to configure the client access details." }, { "code": null, "e": 50702, "s": 50527, "text": "Next, let us create a file, data.csv and populate it with initial expense data for testing purposes. The structure of the file is that it contains one expense entry per line." }, { "code": null, "e": 51027, "s": 50702, "text": "Pizza,80,2020-10-10,Food\nGrape Juice,30,2020-10-12,Food\nCinema,210,2020-10-16,Entertainment\nJava Programming book,242,2020-10-15,Academic\nMango Juice,35,2020-10-16,Food\nDress,2000,2020-10-25,Cloth\nTour,2555,2020-10-29,Entertainment\nMeals,300,2020-10-30,Food\nMobile,3500,2020-11-02,Gadgets\nExam Fees,1245,2020-11-04,Academic\n" }, { "code": null, "e": 51236, "s": 51027, "text": "Next, create a file expensedb.js and include code to load the initial expense data into the data store. The code checks the data store for initial data and load only if the data is not available in the store." }, { "code": null, "e": 52214, "s": 51236, "text": "var store = require(\"nedb\")\nvar fs = require('fs');\nvar expenses = new store({ filename: \"expense.db\", autoload: true })\nexpenses.find({}, function (err, docs) {\n if (docs.length == 0) {\n loadExpenses();\n }\n})\nfunction loadExpenses() {\n readCsv(\"data.csv\", function (data) {\n console.log(data);\n\n data.forEach(function (rec, idx) {\n item = {}\n item.name = rec[0];\n item.amount = parseFloat(rec[1]);\n item.spend_date = new Date(rec[2]);\n item.category = rec[3];\n\n expenses.insert(item, function (err, doc) {\n console.log('Inserted', doc.item_name, 'with ID', doc._id);\n })\n })\n })\n}\nfunction readCsv(file, callback) {\n fs.readFile(file, 'utf-8', function (err, data) {\n if (err) throw err;\n var lines = data.split('\\r\\n');\n var result = lines.map(function (line) {\n return line.split(',');\n });\n callback(result);\n });\n}\nmodule.exports = expenses" }, { "code": null, "e": 52326, "s": 52214, "text": "Next, create a file, server.js and include the actual code to list, add, update and delete the expense entries." }, { "code": null, "e": 54158, "s": 52326, "text": "var express = require(\"express\")\nvar cors = require('cors')\nvar expenseStore = require(\"./expensedb.js\")\nvar app = express()\napp.use(cors());\nvar bodyParser = require(\"body-parser\");\napp.use(bodyParser.urlencoded({ extended: false }));\napp.use(bodyParser.json());\nvar HTTP_PORT = 8000\napp.listen(HTTP_PORT, () => {\n console.log(\"Server running on port %PORT%\".replace(\"%PORT%\", HTTP_PORT))\n});\napp.get(\"/\", (req, res, next) => {\n res.json({ \"message\": \"Ok\" })\n});\napp.get(\"/api/expenses\", (req, res, next) => {\n expenseStore.find({}, function (err, docs) {\n res.json(docs);\n });\n});\napp.get(\"/api/expense/:id\", (req, res, next) => {\n var id = req.params.id;\n expenseStore.find({ _id: id }, function (err, docs) {\n res.json(docs);\n })\n});\napp.post(\"/api/expense/\", (req, res, next) => {\n var errors = []\n if (!req.body.item) {\n errors.push(\"No item specified\");\n }\n var data = {\n name: req.body.name,\n amount: req.body.amount,\n category: req.body.category,\n spend_date: req.body.spend_date,\n }\n expenseStore.insert(data, function (err, docs) {\n return res.json(docs);\n });\n})\napp.put(\"/api/expense/:id\", (req, res, next) => {\n var id = req.params.id;\n var errors = []\n if (!req.body.item) {\n errors.push(\"No item specified\");\n }\n var data = {\n _id: id,\n name: req.body.name,\n amount: req.body.amount,\n category: req.body.category,\n spend_date: req.body.spend_date,\n }\n expenseStore.update( { _id: id }, data, function (err, docs) {\n return res.json(data);\n });\n})\napp.delete(\"/api/expense/:id\", (req, res, next) => {\n var id = req.params.id;\n expenseStore.remove({ _id: id }, function (err, numDeleted) {\n res.json({ \"message\": \"deleted\" })\n });\n})\napp.use(function (req, res) {\n res.status(404);\n});" }, { "code": null, "e": 54198, "s": 54158, "text": "Now, it is time to run the application." }, { "code": null, "e": 54213, "s": 54198, "text": "npm run start\n" }, { "code": null, "e": 54287, "s": 54213, "text": "Next, open a browser and enter http://localhost:8000/ in the address bar." }, { "code": null, "e": 54313, "s": 54287, "text": "{ \n \"message\": \"Ok\" \n}\n" }, { "code": null, "e": 54363, "s": 54313, "text": "It confirms that our application is working fine." }, { "code": null, "e": 54507, "s": 54363, "text": "Finally, change the url to http://localhost:8000/api/expense and press enter. The browser will show the initial expense entries in JSON format." }, { "code": null, "e": 54685, "s": 54507, "text": "[\n ...\n {\n \"name\": \"Pizza\",\n \"amount\": 80,\n \"spend_date\": \"2020-10-10T00:00:00.000Z\",\n \"category\": \"Food\",\n \"_id\": \"5H8rK8lLGJPVZ3gD\"\n },\n ...\n]" }, { "code": null, "e": 54809, "s": 54685, "text": "Let us use our newly created expense server in our Expense manager application through fetch() api in the upcoming section." }, { "code": null, "e": 54887, "s": 54809, "text": "Let us create a new application to showcase client side programming in React." }, { "code": null, "e": 55048, "s": 54887, "text": "First, create a new react application, react-http-app using Create React App or Rollup bundler by following instruction in Creating a React application chapter." }, { "code": null, "e": 55100, "s": 55048, "text": "Next, open the application in your favorite editor." }, { "code": null, "e": 55169, "s": 55100, "text": "Next, create src folder under the root directory of the application." }, { "code": null, "e": 55218, "s": 55169, "text": "Next, create components folder under src folder." }, { "code": null, "e": 55326, "s": 55218, "text": "Next, create a file, ExpenseEntryItemList.css under src/components folder and include generic table styles." }, { "code": null, "e": 55850, "s": 55326, "text": "html {\n font-family: sans-serif;\n}\ntable {\n border-collapse: collapse;\n border: 2px solid rgb(200,200,200);\n letter-spacing: 1px;\n font-size: 0.8rem;\n}\ntd, th {\n border: 1px solid rgb(190,190,190);\n padding: 10px 20px;\n}\nth {\n background-color: rgb(235,235,235);\n}\ntd, th {\n text-align: left;\n}\ntr:nth-child(even) td {\n background-color: rgb(250,250,250);\n}\ntr:nth-child(odd) td {\n background-color: rgb(245,245,245);\n}\ncaption {\n padding: 10px;\n}\ntr.highlight td { \n background-color: #a6a8bd;\n}" }, { "code": null, "e": 55942, "s": 55850, "text": "Next, create a file, ExpenseEntryItemList.js under src/components folder and start editing." }, { "code": null, "e": 55970, "s": 55942, "text": "Next, import React library." }, { "code": null, "e": 55998, "s": 55970, "text": "import React from 'react';\n" }, { "code": null, "e": 56074, "s": 55998, "text": "Next, create a class, ExpenseEntryItemList and call constructor with props." }, { "code": null, "e": 56178, "s": 56074, "text": "class ExpenseEntryItemList extends React.Component {\n constructor(props) {\n super(props);\n }\n}" }, { "code": null, "e": 56241, "s": 56178, "text": "Next, initialize the state with empty list in the constructor." }, { "code": null, "e": 56291, "s": 56241, "text": "this.state = {\n isLoaded: false,\n items: []\n}" }, { "code": null, "e": 56420, "s": 56291, "text": "Next, create a method, setItems to format the items received from remote server and then set it into the state of the component." }, { "code": null, "e": 56779, "s": 56420, "text": "setItems(remoteItems) {\n var items = [];\n remoteItems.forEach((item) => {\n let newItem = {\n id: item._id,\n name: item.name,\n amount: item.amount,\n spendDate: item.spend_date,\n category: item.category\n }\n items.push(newItem)\n });\n this.setState({\n isLoaded: true,\n items: items\n });\n}" }, { "code": null, "e": 56852, "s": 56779, "text": "Next, add a method, fetchRemoteItems to fetch the items from the server." }, { "code": null, "e": 57174, "s": 56852, "text": "fetchRemoteItems() {\n fetch(\"http://localhost:8000/api/expenses\")\n .then(res => res.json())\n .then(\n (result) => {\n this.setItems(result);\n },\n (error) => {\n this.setState({\n isLoaded: false,\n error\n });\n }\n )\n}" }, { "code": null, "e": 57180, "s": 57174, "text": "Here," }, { "code": null, "e": 57240, "s": 57180, "text": "fetch api is used to fetch the item from the remote server." }, { "code": null, "e": 57300, "s": 57240, "text": "fetch api is used to fetch the item from the remote server." }, { "code": null, "e": 57361, "s": 57300, "text": "setItems is used to format and store the items in the state." }, { "code": null, "e": 57422, "s": 57361, "text": "setItems is used to format and store the items in the state." }, { "code": null, "e": 57502, "s": 57422, "text": "Next, add a method, deleteRemoteItem to delete the item from the remote server." }, { "code": null, "e": 57717, "s": 57502, "text": "deleteRemoteItem(id) {\n fetch('http://localhost:8000/api/expense/' + id, { method: 'DELETE' })\n .then(res => res.json())\n .then(\n () => {\n this.fetchRemoteItems()\n }\n )\n}" }, { "code": null, "e": 57723, "s": 57717, "text": "Here," }, { "code": null, "e": 57794, "s": 57723, "text": "fetch api is used to delete and fetch the item from the remote server." }, { "code": null, "e": 57865, "s": 57794, "text": "fetch api is used to delete and fetch the item from the remote server." }, { "code": null, "e": 57932, "s": 57865, "text": "setItems is again used to format and store the items in the state." }, { "code": null, "e": 57999, "s": 57932, "text": "setItems is again used to format and store the items in the state." }, { "code": null, "e": 58111, "s": 57999, "text": "Next, call the componentDidMount life cycle api to load the items into the component during its mounting phase." }, { "code": null, "e": 58165, "s": 58111, "text": "componentDidMount() { \n this.fetchRemoteItems(); \n}" }, { "code": null, "e": 58228, "s": 58165, "text": "Next, write an event handler to remove the item from the list." }, { "code": null, "e": 58336, "s": 58228, "text": "handleDelete = (id, e) => { \n e.preventDefault(); \n console.log(id); \n\n this.deleteRemoteItem(id); \n}" }, { "code": null, "e": 58367, "s": 58336, "text": "Next, write the render method." }, { "code": null, "e": 59291, "s": 58367, "text": "render() {\n let lists = [];\n if (this.state.isLoaded) {\n lists = this.state.items.map((item) =>\n <tr key={item.id} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}>\n <td>{item.name}</td>\n <td>{item.amount}</td>\n <td>{new Date(item.spendDate).toDateString()}</td>\n <td>{item.category}</td>\n <td><a href=\"#\" onClick={(e) => this.handleDelete(item.id, e)}>Remove</a></td>\n </tr>\n );\n }\n return (\n <div>\n <table onMouseOver={this.handleMouseOver}>\n <thead>\n <tr>\n <th>Item</th>\n <th>Amount</th>\n <th>Date</th>\n <th>Category</th>\n <th>Remove</th>\n </tr>\n </thead>\n <tbody>\n {lists}\n </tbody>\n </table>\n </div>\n );\n}" }, { "code": null, "e": 59322, "s": 59291, "text": "Finally, export the component." }, { "code": null, "e": 59360, "s": 59322, "text": "export default ExpenseEntryItemList;\n" }, { "code": null, "e": 59451, "s": 59360, "text": "Next, create a file, index.js under the src folder and use ExpenseEntryItemList component." }, { "code": null, "e": 59718, "s": 59451, "text": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport ExpenseEntryItemList from './components/ExpenseEntryItemList';\n\nReactDOM.render(\n <React.StrictMode>\n <ExpenseEntryItemList />\n </React.StrictMode>,\n document.getElementById('root')\n);" }, { "code": null, "e": 59800, "s": 59718, "text": "Finally, create a public folder under the root folder and create index.html file." }, { "code": null, "e": 60035, "s": 59800, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>React App</title>\n </head>\n <body>\n <div id=\"root\"></div>\n <script type=\"text/JavaScript\" src=\"./index.js\"></script>\n </body>\n</html>" }, { "code": null, "e": 60102, "s": 60035, "text": "Next, open a new terminal window and start our server application." }, { "code": null, "e": 60143, "s": 60102, "text": "cd /go/to/server/application \nnpm start\n" }, { "code": null, "e": 60197, "s": 60143, "text": "Next, serve the client application using npm command." }, { "code": null, "e": 60208, "s": 60197, "text": "npm start\n" }, { "code": null, "e": 60299, "s": 60208, "text": "Next, open the browser and enter http://localhost:3000 in the address bar and press enter." }, { "code": null, "e": 60351, "s": 60299, "text": "Try to remove the item by clicking the remove link." }, { "code": null, "e": 60756, "s": 60351, "text": "The nature of form programming needs the state to be maintained. Because, the input field information will get changed as the user interacts with the form. But as we learned earlier, React library does not store or maintain any state information by itself and component has to use state management api to manage state. Considering this, React provides two types of components to support form programming." }, { "code": null, "e": 61031, "s": 60756, "text": "Controlled component βˆ’ In controlled component, React provides a special attribute, value for all input elements and controls the input elements. The value attribute can be used to get and set the value of the input element. It has to be in sync with state of the component." }, { "code": null, "e": 61306, "s": 61031, "text": "Controlled component βˆ’ In controlled component, React provides a special attribute, value for all input elements and controls the input elements. The value attribute can be used to get and set the value of the input element. It has to be in sync with state of the component." }, { "code": null, "e": 61548, "s": 61306, "text": "Uncontrolled component βˆ’ In uncontrolled component, React provides minimal support for form programming. It has to use Ref concept (another react concept to get a DOM element in the React component during runtime) to do the form programming." }, { "code": null, "e": 61790, "s": 61548, "text": "Uncontrolled component βˆ’ In uncontrolled component, React provides minimal support for form programming. It has to use Ref concept (another react concept to get a DOM element in the React component during runtime) to do the form programming." }, { "code": null, "e": 61892, "s": 61790, "text": "Let us learn the form programming using controlled as well as uncontrolled component in this chapter." }, { "code": null, "e": 61913, "s": 61892, "text": "Controlled component" }, { "code": null, "e": 61934, "s": 61913, "text": "Controlled component" }, { "code": null, "e": 61957, "s": 61934, "text": "Uncontrolled Component" }, { "code": null, "e": 61980, "s": 61957, "text": "Uncontrolled Component" }, { "code": null, "e": 61987, "s": 61980, "text": "Formik" }, { "code": null, "e": 61994, "s": 61987, "text": "Formik" }, { "code": null, "e": 62411, "s": 61994, "text": "In web application, Routing is a process of binding a web URL to a specific resource in the web application. In React, it is binding an URL to a component. React does not support routing natively as it is basically an user interface library. React community provides many third party component to handle routing in the React application. Let us learn React Router, a top choice routing library for React application." }, { "code": null, "e": 62498, "s": 62411, "text": "Let us learn how to install React Router component in our Expense Manager application." }, { "code": null, "e": 62566, "s": 62498, "text": "Open a command prompt and go to the root folder of our application." }, { "code": null, "e": 62593, "s": 62566, "text": "cd /go/to/expense/manager\n" }, { "code": null, "e": 62639, "s": 62593, "text": "Install the react router using below command." }, { "code": null, "e": 62676, "s": 62639, "text": "npm install react-router-dom --save\n" }, { "code": null, "e": 62757, "s": 62676, "text": "React router provides four components to manage navigation in React application." }, { "code": null, "e": 62836, "s": 62757, "text": "Router βˆ’ Router is th top level component. It encloses the entire application." }, { "code": null, "e": 62924, "s": 62836, "text": "Link βˆ’ Similar to anchor tag in html. It sets the target url along with reference text." }, { "code": null, "e": 62950, "s": 62924, "text": "<Link to=\"/\">Home</Link>\n" }, { "code": null, "e": 63000, "s": 62950, "text": "Here, to attribute is used to set the target url." }, { "code": null, "e": 63261, "s": 63000, "text": "Switch & Route βˆ’ Both are used together. Maps the target url to the component. Switch is the parent component and Route is the child component. Switch component can have multiple Route component and each Route component mapping a particular url to a component." }, { "code": null, "e": 63451, "s": 63261, "text": "<Switch>\n <Route exact path=\"/\">\n <Home />\n </Route>\n <Route path=\"/home\">\n <Home />\n </Route>\n <Route path=\"/list\">\n <ExpenseEntryItemList />\n </Route>\n</Switch>" }, { "code": null, "e": 63713, "s": 63451, "text": "Here, path attribute is used to match the url. Basically, Switch works similar to traditional switch statement in a programming language. It matches the target url with each child route (path attribute) one by one in sequence and invoke the first matched route." }, { "code": null, "e": 64019, "s": 63713, "text": "Along with router component, React router provides option to get set and get dynamic information from the url. For example, in an article website, the url may have article type attached to it and the article type needs to be dynamically extracted and has to be used to fetch the specific type of articles." }, { "code": null, "e": 64199, "s": 64019, "text": "<Link to=\"/article/c\">C Programming</Link>\n<Link to=\"/article/java\">Java Programming</Link>\n\n...\n...\n\n<Switch>\n <Route path=\"article/:tag\" children={<ArticleList />} />\n</Switch>" }, { "code": null, "e": 64247, "s": 64199, "text": "Then, in the child component (class component)," }, { "code": null, "e": 64550, "s": 64247, "text": "import { withRouter } from \"react-router\"\n\nclass ArticleList extends React.Component {\n ...\n ...\n static getDerivedStateFromProps(props, state) {\n let newState = {\n tag: props.match.params.tag\n }\n return newState;\n }\n ...\n ...\n}\nexport default WithRouter(ArticleList)" }, { "code": null, "e": 64642, "s": 64550, "text": "Here, WithRouter enables ArticleList component to access the tag information through props." }, { "code": null, "e": 64702, "s": 64642, "text": "The same can be done differently in functional components βˆ’" }, { "code": null, "e": 64829, "s": 64702, "text": "function ArticleList() {\n let { tag } = useParams();\n return (\n <div>\n <h3>ID: {id}</h3>\n </div>\n );\n}" }, { "code": null, "e": 64905, "s": 64829, "text": "Here, useParams is a custom React Hooks provided by React Router component." }, { "code": null, "e": 65064, "s": 64905, "text": "React router supports nested routing as well. React router provides another React Hooks, useRouteMatch() to extract parent route information in nested routes." }, { "code": null, "e": 65861, "s": 65064, "text": "function ArticleList() {\n // get the parent url and the matched path\n let { path, url } = useRouteMatch();\n\n return (\n <div>\n <h2>Articles</h2>\n <ul>\n <li>\n <Link to={`${url}/pointer`}>C with pointer</Link>\n </li>\n <li>\n <Link to={`${url}/basics`}>C basics</Link>\n </li>\n </ul>\n\n <Switch>\n <Route exact path={path}>\n <h3>Please select an article.</h3>\n </Route>\n <Route path={`${path}/:article`}>\n <Article />\n </Route>\n </Switch>\n </div>\n );\n}\nfunction Article() {\n let { article } = useParams();\n return (\n <div>\n <h3>The select article is {article}</h3>\n </div>\n );\n}" }, { "code": null, "e": 66036, "s": 65861, "text": "Here, useRouteMatch returns the matched path and the target url. url can be used to create next level of links and path can be used to map next level of components / screens." }, { "code": null, "e": 66193, "s": 66036, "text": "Let us learn how to do routing by creating the possible routing in our expense manager application. The minimum screens of the application are given below βˆ’" }, { "code": null, "e": 66252, "s": 66193, "text": "Home screen βˆ’ Landing or initial screen of the application" }, { "code": null, "e": 66311, "s": 66252, "text": "Home screen βˆ’ Landing or initial screen of the application" }, { "code": null, "e": 66377, "s": 66311, "text": "Expense list screen βˆ’ Shows the expense items in a tabular format" }, { "code": null, "e": 66443, "s": 66377, "text": "Expense list screen βˆ’ Shows the expense items in a tabular format" }, { "code": null, "e": 66501, "s": 66443, "text": "Expense add screen βˆ’ Add interface to add an expense item" }, { "code": null, "e": 66559, "s": 66501, "text": "Expense add screen βˆ’ Add interface to add an expense item" }, { "code": null, "e": 66722, "s": 66559, "text": "First, create a new react application, react-router-app using Create React App or Rollup bundler by following instruction in Creating a React application chapter." }, { "code": null, "e": 66774, "s": 66722, "text": "Next, open the application in your favorite editor." }, { "code": null, "e": 66843, "s": 66774, "text": "Next, create src folder under the root directory of the application." }, { "code": null, "e": 66892, "s": 66843, "text": "Next, create components folder under src folder." }, { "code": null, "e": 66968, "s": 66892, "text": "Next, create a file, Home.js under src/components folder and start editing." }, { "code": null, "e": 66996, "s": 66968, "text": "Next, import React library." }, { "code": null, "e": 67024, "s": 66996, "text": "import React from 'react';\n" }, { "code": null, "e": 67069, "s": 67024, "text": "Next, import Link from React router library." }, { "code": null, "e": 67110, "s": 67069, "text": "import { Link } from 'react-router-dom'\n" }, { "code": null, "e": 67170, "s": 67110, "text": "Next, create a class, Home and call constructor with props." }, { "code": null, "e": 67258, "s": 67170, "text": "class Home extends React.Component {\n constructor(props) {\n super(props);\n }\n}" }, { "code": null, "e": 67355, "s": 67258, "text": "Next, add render() method and show the welcome message and links to add and list expense screen." }, { "code": null, "e": 67598, "s": 67355, "text": "render() {\n return (\n <div>\n <p>Welcome to the React tutorial</p>\n <p><Link to=\"/list\">Click here</Link> to view expense list</p>\n <p><Link to=\"/add\">Click here</Link> to add new expenses</p>\n </div>\n )\n}" }, { "code": null, "e": 67629, "s": 67598, "text": "Finally, export the component." }, { "code": null, "e": 67651, "s": 67629, "text": "export default Home;\n" }, { "code": null, "e": 67715, "s": 67651, "text": "The complete source code of the Home component is given below βˆ’" }, { "code": null, "e": 68162, "s": 67715, "text": "import React from 'react';\nimport { Link } from 'react-router-dom'\n\nclass Home extends React.Component {\n constructor(props) {\n super(props);\n }\n render() {\n return (\n <div>\n <p>Welcome to the React tutorial</p>\n <p><Link to=\"/list\">Click here</Link> to view expense list</p>\n <p><Link to=\"/add\">Click here</Link> to add new expenses</p>\n </div>\n )\n }\n}\nexport default Home;" }, { "code": null, "e": 68275, "s": 68162, "text": "Next, create ExpenseEntryItemList.js file under src/components folder and create ExpenseEntryItemList component." }, { "code": null, "e": 68725, "s": 68275, "text": "import React from 'react';\nimport { Link } from 'react-router-dom'\n\nclass ExpenseEntryItemList extends React.Component {\n constructor(props) {\n super(props);\n }\n render() {\n return (\n <div>\n <h1>Expenses</h1>\n <p><Link to=\"/add\">Click here</Link> to add new expenses</p>\n <div>\n Expense list\n </div>\n </div>\n )\n }\n}\nexport default ExpenseEntryItemList;" }, { "code": null, "e": 68838, "s": 68725, "text": "Next, create ExpenseEntryItemForm.js file under src/components folder and create ExpenseEntryItemForm component." }, { "code": null, "e": 69302, "s": 68838, "text": "import React from 'react';\nimport { Link } from 'react-router-dom'\n\nclass ExpenseEntryItemForm extends React.Component {\n constructor(props) {\n super(props);\n }\n render() {\n return (\n <div>\n <h1>Add Expense item</h1>\n <p><Link to=\"/list\">Click here</Link> to view new expense list</p>\n <div>\n Expense form\n </div>\n </div>\n )\n }\n}\nexport default ExpenseEntryItemForm;" }, { "code": null, "e": 69387, "s": 69302, "text": "Next, create a file, App.css under src/components folder and add generic css styles." }, { "code": null, "e": 69857, "s": 69387, "text": "html {\n font-family: sans-serif;\n}\na{\n text-decoration: none;\n}\np, li, a{\n font-size: 14px;\n}\nnav ul {\n width: 100%;\n list-style-type: none;\n margin: 0;\n padding: 0;\n overflow: hidden;\n background-color: rgb(235,235,235);\n}\nnav li {\n float: left;\n}\nnav li a {\n display: block;\n color: black;\n text-align: center;\n padding: 14px 16px;\n text-decoration: none;\n font-size: 16px;\n}\nnav li a:hover {\n background-color: rgb(187, 202, 211);\n}" }, { "code": null, "e": 70084, "s": 69857, "text": "Next, create a file, App.js under src/components folder and start editing. The purpose of the App component is to handle all the screen in one component. It will configure routing and enable navigation to all other components." }, { "code": null, "e": 70133, "s": 70084, "text": "Next, import React library and other components." }, { "code": null, "e": 70323, "s": 70133, "text": "import React from 'react';\n\nimport Home from './Home'\nimport ExpenseEntryItemList from './ExpenseEntryItemList'\nimport ExpenseEntryItemForm from './ExpenseEntryItemForm'\n\nimport './App.css'" }, { "code": null, "e": 70361, "s": 70323, "text": "Next, import React router components." }, { "code": null, "e": 70453, "s": 70361, "text": "import {\n BrowserRouter as Router,\n Link,\n Switch,\n Route\n} from 'react-router-dom'" }, { "code": null, "e": 70508, "s": 70453, "text": "Next, write the render() method and configure routing." }, { "code": null, "e": 71319, "s": 70508, "text": "function App() {\n return (\n <Router>\n <div>\n <nav>\n <ul>\n <li>\n <Link to=\"/\">Home</Link>\n </li>\n <li>\n <Link to=\"/list\">List Expenses</Link>\n </li>\n <li>\n <Link to=\"/add\">Add Expense</Link>\n </li>\n </ul>\n </nav>\n\n <Switch>\n <Route path=\"/list\">\n <ExpenseEntryItemList />\n </Route>\n <Route path=\"/add\">\n <ExpenseEntryItemForm />\n </Route>\n <Route path=\"/\">\n <Home />\n </Route>\n </Switch>\n </div>\n </Router>\n );\n}" }, { "code": null, "e": 71393, "s": 71319, "text": "Next, create a file, index.js under the src folder and use App component." }, { "code": null, "e": 71606, "s": 71393, "text": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport App from './components/App';\n\nReactDOM.render(\n <React.StrictMode>\n <App />\n </React.StrictMode>,\n document.getElementById('root')\n);" }, { "code": null, "e": 71688, "s": 71606, "text": "Finally, create a public folder under the root folder and create index.html file." }, { "code": null, "e": 71930, "s": 71688, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>React router app</title>\n </head>\n <body>\n <div id=\"root\"></div>\n <script type=\"text/JavaScript\" src=\"./index.js\"></script>\n </body>\n</html>" }, { "code": null, "e": 71977, "s": 71930, "text": "Next, serve the application using npm command." }, { "code": null, "e": 71988, "s": 71977, "text": "npm start\n" }, { "code": null, "e": 72079, "s": 71988, "text": "Next, open the browser and enter http://localhost:3000 in the address bar and press enter." }, { "code": null, "e": 72146, "s": 72079, "text": "Try to navigate the links and confirm that the routing is working." }, { "code": null, "e": 72558, "s": 72146, "text": "React redux is an advanced state management library for React. As we learned earlier, React only supports component level state management. In a big and complex application, large number of components are used. React recommends to move the state to the top level component and pass the state to the nested component using properties. It helps to some extent but it becomes complex when the components increases." }, { "code": null, "e": 72781, "s": 72558, "text": "React redux chips in and helps to maintain state at the application level. React redux allows any component to access the state at any time. Also, it allows any component to change the state of the application at any time." }, { "code": null, "e": 72872, "s": 72781, "text": "Let us learn about the how to write a React application using React redux in this chapter." }, { "code": null, "e": 73171, "s": 72872, "text": "React redux maintains the state of the application in a single place called Redux store. React component can get the latest state from the store as well as change the state at any time. Redux provides a simple process to get and set the current state of the application and involves below concepts." }, { "code": null, "e": 73236, "s": 73171, "text": "Store βˆ’ The central place to store the state of the application." }, { "code": null, "e": 73529, "s": 73236, "text": "Actions βˆ’ Action is an plain object with the type of the action to be done and the input (called payload) necessary to do the action. For example, action for adding an item in the store contains ADD_ITEM as type and an object with item’s details as payload. The action can be represented as βˆ’" }, { "code": null, "e": 73589, "s": 73529, "text": "{ \n type: 'ADD_ITEM', \n payload: { name: '..', ... }\n}\n" }, { "code": null, "e": 73889, "s": 73589, "text": "Reducers βˆ’ Reducers are pure functions used to create a new state based on the existing state and the current action. It returns the newly created state. For example, in add item scenario, it creates a new item list and merges the item from the state and new item and returns the newly created list." }, { "code": null, "e": 74081, "s": 73889, "text": "Action creators βˆ’ Action creator creates an action with proper action type and data necessary for the action and returns the action. For example, addItem action creator returns below object βˆ’" }, { "code": null, "e": 74141, "s": 74081, "text": "{ \n type: 'ADD_ITEM', \n payload: { name: '..', ... }\n}\n" }, { "code": null, "e": 74316, "s": 74141, "text": "Component βˆ’ Component can connect to the store to get the current state and dispatch action to the store so that the store executes the action and updates it’s current state." }, { "code": null, "e": 74389, "s": 74316, "text": "The workflow of a typical redux store can be represented as shown below." }, { "code": null, "e": 74496, "s": 74389, "text": "React component subscribes to the store and get the latest state during initialization of the application." }, { "code": null, "e": 74585, "s": 74496, "text": "To change the state, React component creates necessary action and dispatches the action." }, { "code": null, "e": 74690, "s": 74585, "text": "Reducer creates a new state based on the action and returns it. Store updates itself with the new state." }, { "code": null, "e": 74777, "s": 74690, "text": "Once the state changes, store sends the updated state to all its subscribed component." }, { "code": null, "e": 74923, "s": 74777, "text": "Redux provides a single api, connect which will connect a components to the store and allows the component to get and set the state of the store." }, { "code": null, "e": 74961, "s": 74923, "text": "The signature of the connect API is βˆ’" }, { "code": null, "e": 75041, "s": 74961, "text": "function connect(mapStateToProps?, mapDispatchToProps?, mergeProps?, options?)\n" }, { "code": null, "e": 75208, "s": 75041, "text": "All parameters are optional and it returns a HOC (higher order component). A higher order component is a function which wraps a component and returns a new component." }, { "code": null, "e": 75305, "s": 75208, "text": "let hoc = connect(mapStateToProps, mapDispatchToProps) \nlet connectedComponent = hoc(component)\n" }, { "code": null, "e": 75378, "s": 75305, "text": "Let us see the first two parameters which will be enough for most cases." }, { "code": null, "e": 75437, "s": 75378, "text": "mapStateToProps βˆ’ Accepts a function with below signature." }, { "code": null, "e": 75496, "s": 75437, "text": "mapStateToProps βˆ’ Accepts a function with below signature." }, { "code": null, "e": 75526, "s": 75496, "text": "(state, ownProps?) => Object\n" }, { "code": null, "e": 75681, "s": 75526, "text": "Here, state refers current state of the store and Object refers the new props of the component. It gets called whenever the state of the store is updated." }, { "code": null, "e": 75724, "s": 75681, "text": "(state) => { prop1: this.state.anyvalue }\n" }, { "code": null, "e": 75786, "s": 75724, "text": "mapDispatchToProps βˆ’ Accepts a function with below signature." }, { "code": null, "e": 75848, "s": 75786, "text": "mapDispatchToProps βˆ’ Accepts a function with below signature." }, { "code": null, "e": 75890, "s": 75848, "text": "Object | (dispatch, ownProps?) => Object\n" }, { "code": null, "e": 76051, "s": 75890, "text": "Here, dispatch refers the dispatch object used to dispatch action in the redux store and Object refers one or more dispatch functions as props of the component." }, { "code": null, "e": 76231, "s": 76051, "text": "(dispatch) => {\n addDispatcher: (dispatch) => dispatch({ type: 'ADD_ITEM', payload: { } }),\n removeispatcher: (dispatch) => dispatch({ type: 'REMOVE_ITEM', payload: { } }),\n}\n" }, { "code": null, "e": 76428, "s": 76231, "text": "React Redux provides a Provider component and its sole purpose to make the Redux store available to its all nested components connected to store using connect API. The sample code is given below βˆ’" }, { "code": null, "e": 76741, "s": 76428, "text": "import React from 'react'\nimport ReactDOM from 'react-dom'\nimport { Provider } from 'react-redux'\nimport { App } from './App'\nimport createStore from './createReduxStore'\n\nconst store = createStore()\n\nReactDOM.render(\n <Provider store={store}>\n <App />\n </Provider>,\n document.getElementById('root')\n)" }, { "code": null, "e": 76845, "s": 76741, "text": "Now, all the component inside the App component can get access to the Redux store by using connect API." }, { "code": null, "e": 76968, "s": 76845, "text": "Let us recreate our expense manager application and uses the React redux concept to maintain the state of the application." }, { "code": null, "e": 77132, "s": 76968, "text": "First, create a new react application, react-message-app using Create React App or Rollup bundler by following instruction in Creating a React application chapter." }, { "code": null, "e": 77177, "s": 77132, "text": "Next, install Redux and React redux library." }, { "code": null, "e": 77215, "s": 77177, "text": "npm install redux react-redux --save\n" }, { "code": null, "e": 77290, "s": 77215, "text": "Next, install uuid library to generate unique identifier for new expenses." }, { "code": null, "e": 77315, "s": 77290, "text": "npm install uuid --save\n" }, { "code": null, "e": 77367, "s": 77315, "text": "Next, open the application in your favorite editor." }, { "code": null, "e": 77436, "s": 77367, "text": "Next, create src folder under the root directory of the application." }, { "code": null, "e": 77482, "s": 77436, "text": "Next, create actions folder under src folder." }, { "code": null, "e": 77556, "s": 77482, "text": "Next, create a file, types.js under src/actions folder and start editing." }, { "code": null, "e": 77631, "s": 77556, "text": "Next, add two action type, one for add expense and one for remove expense." }, { "code": null, "e": 77723, "s": 77631, "text": "export const ADD_EXPENSE = 'ADD_EXPENSE'; \nexport const DELETE_EXPENSE = 'DELETE_EXPENSE';\n" }, { "code": null, "e": 77811, "s": 77723, "text": "Next, create a file, index.js under src/actions folder to add action and start editing." }, { "code": null, "e": 77858, "s": 77811, "text": "Next, import uuid to create unique identifier." }, { "code": null, "e": 77896, "s": 77858, "text": "import { v4 as uuidv4 } from 'uuid';\n" }, { "code": null, "e": 77923, "s": 77896, "text": "Next, import action types." }, { "code": null, "e": 77979, "s": 77923, "text": "import { ADD_EXPENSE, DELETE_EXPENSE } from './types';\n" }, { "code": null, "e": 78063, "s": 77979, "text": "Next, add a new function to return action type for adding an expense and export it." }, { "code": null, "e": 78258, "s": 78063, "text": "export const addExpense = ({ name, amount, spendDate, category }) => ({\n type: ADD_EXPENSE,\n payload: {\n id: uuidv4(),\n name,\n amount,\n spendDate,\n category\n }\n});" }, { "code": null, "e": 78383, "s": 78258, "text": "Here, the function expects expense object and return action type of ADD_EXPENSE along with a payload of expense information." }, { "code": null, "e": 78469, "s": 78383, "text": "Next, add a new function to return action type for deleting an expense and export it." }, { "code": null, "e": 78564, "s": 78469, "text": "export const deleteExpense = id => ({\n type: DELETE_EXPENSE,\n payload: {\n id\n }\n});" }, { "code": null, "e": 78707, "s": 78564, "text": "Here, the function expects id of the expense item to be deleted and return action type of β€˜DELETE_EXPENSE’ along with a payload of expense id." }, { "code": null, "e": 78763, "s": 78707, "text": "The complete source code of the action is given below βˆ’" }, { "code": null, "e": 79146, "s": 78763, "text": "import { v4 as uuidv4 } from 'uuid';\nimport { ADD_EXPENSE, DELETE_EXPENSE } from './types';\n\nexport const addExpense = ({ name, amount, spendDate, category }) => ({\n type: ADD_EXPENSE,\n payload: {\n id: uuidv4(),\n name,\n amount,\n spendDate,\n category\n }\n});\nexport const deleteExpense = id => ({\n type: DELETE_EXPENSE,\n payload: {\n id\n }\n});" }, { "code": null, "e": 79200, "s": 79146, "text": "Next, create a new folder, reducers under src folder." }, { "code": null, "e": 79294, "s": 79200, "text": "Next, create a file, index.js under src/reducers to write reducer function and start editing." }, { "code": null, "e": 79325, "s": 79294, "text": "Next, import the action types." }, { "code": null, "e": 79390, "s": 79325, "text": "import { ADD_EXPENSE, DELETE_EXPENSE } from '../actions/types';\n" }, { "code": null, "e": 79505, "s": 79390, "text": "Next, add a function, expensesReducer to do the actual feature of adding and updating expenses in the redux store." }, { "code": null, "e": 79808, "s": 79505, "text": "export default function expensesReducer(state = [], action) {\n switch (action.type) {\n case ADD_EXPENSE:\n return [...state, action.payload];\n case DELETE_EXPENSE:\n return state.filter(expense => expense.id !== action.payload.id);\n default:\n return state;\n }\n}" }, { "code": null, "e": 79865, "s": 79808, "text": "The complete source code of the reducer is given below βˆ’" }, { "code": null, "e": 80233, "s": 79865, "text": "import { ADD_EXPENSE, DELETE_EXPENSE } from '../actions/types';\n\nexport default function expensesReducer(state = [], action) {\n switch (action.type) {\n case ADD_EXPENSE:\n return [...state, action.payload];\n case DELETE_EXPENSE:\n return state.filter(expense => expense.id !== action.payload.id);\n default:\n return state;\n }\n}" }, { "code": null, "e": 80305, "s": 80233, "text": "Here, the reducer checks the action type and execute the relevant code." }, { "code": null, "e": 80354, "s": 80305, "text": "Next, create components folder under src folder." }, { "code": null, "e": 80471, "s": 80354, "text": "Next, create a file, ExpenseEntryItemList.css under src/components folder and add generic style for the html tables." }, { "code": null, "e": 80994, "s": 80471, "text": "html {\n font-family: sans-serif;\n}\ntable {\n border-collapse: collapse;\n border: 2px solid rgb(200,200,200);\n letter-spacing: 1px;\n font-size: 0.8rem;\n}\ntd, th {\n border: 1px solid rgb(190,190,190);\n padding: 10px 20px;\n}\nth {\n background-color: rgb(235,235,235);\n}\ntd, th {\n text-align: left;\n}\ntr:nth-child(even) td {\n background-color: rgb(250,250,250);\n}\ntr:nth-child(odd) td {\n background-color: rgb(245,245,245);\n}\ncaption {\n padding: 10px;\n}\ntr.highlight td { \n background-color: #a6a8bd;\n}" }, { "code": null, "e": 81086, "s": 80994, "text": "Next, create a file, ExpenseEntryItemList.js under src/components folder and start editing." }, { "code": null, "e": 81130, "s": 81086, "text": "Next, import React and React redux library." }, { "code": null, "e": 81198, "s": 81130, "text": "import React from 'react'; \nimport { connect } from 'react-redux';\n" }, { "code": null, "e": 81242, "s": 81198, "text": "Next, import ExpenseEntryItemList.css file." }, { "code": null, "e": 81280, "s": 81242, "text": "import './ExpenseEntryItemList.css';\n" }, { "code": null, "e": 81310, "s": 81280, "text": "Next, import action creators." }, { "code": null, "e": 81397, "s": 81310, "text": "import { deleteExpense } from '../actions'; \nimport { addExpense } from '../actions';\n" }, { "code": null, "e": 81473, "s": 81397, "text": "Next, create a class, ExpenseEntryItemList and call constructor with props." }, { "code": null, "e": 81577, "s": 81473, "text": "class ExpenseEntryItemList extends React.Component {\n constructor(props) {\n super(props);\n }\n}" }, { "code": null, "e": 81616, "s": 81577, "text": "Next, create mapStateToProps function." }, { "code": null, "e": 81694, "s": 81616, "text": "const mapStateToProps = state => {\n return {\n expenses: state\n };\n};" }, { "code": null, "e": 81762, "s": 81694, "text": "Here, we copied the input state to expenses props of the component." }, { "code": null, "e": 81804, "s": 81762, "text": "Next, create mapDispatchToProps function." }, { "code": null, "e": 82018, "s": 81804, "text": "const mapDispatchToProps = dispatch => {\n return {\n onAddExpense: expense => {\n dispatch(addExpense(expense));\n },\n onDelete: id => {\n dispatch(deleteExpense(id));\n }\n };\n};" }, { "code": null, "e": 82216, "s": 82018, "text": "Here, we created two function, one to dispatch add expense (addExpense) function and another to dispatch delete expense (deleteExpense) function and mapped those function to props of the component." }, { "code": null, "e": 82262, "s": 82216, "text": "Next, export the component using connect api." }, { "code": null, "e": 82353, "s": 82262, "text": "export default connect(\n mapStateToProps,\n mapDispatchToProps\n)(ExpenseEntryItemList);" }, { "code": null, "e": 82412, "s": 82353, "text": "Now, the component gets three new properties given below βˆ’" }, { "code": null, "e": 82439, "s": 82412, "text": "expenses βˆ’ list of expense" }, { "code": null, "e": 82466, "s": 82439, "text": "expenses βˆ’ list of expense" }, { "code": null, "e": 82522, "s": 82466, "text": "onAddExpense βˆ’ function to dispatch addExpense function" }, { "code": null, "e": 82578, "s": 82522, "text": "onAddExpense βˆ’ function to dispatch addExpense function" }, { "code": null, "e": 82633, "s": 82578, "text": "onDelete βˆ’ function to dispatch deleteExpense function" }, { "code": null, "e": 82688, "s": 82633, "text": "onDelete βˆ’ function to dispatch deleteExpense function" }, { "code": null, "e": 82779, "s": 82688, "text": "Next, add few expense into the redux store in the constructor using onAddExpense property." }, { "code": null, "e": 84027, "s": 82779, "text": "if (this.props.expenses.length == 0)\n{\n const items = [\n { id: 1, name: \"Pizza\", amount: 80, spendDate: \"2020-10-10\", category: \"Food\" },\n { id: 2, name: \"Grape Juice\", amount: 30, spendDate: \"2020-10-12\", category: \"Food\" },\n { id: 3, name: \"Cinema\", amount: 210, spendDate: \"2020-10-16\", category: \"Entertainment\" },\n { id: 4, name: \"Java Programming book\", amount: 242, spendDate: \"2020-10-15\", category: \"Academic\" },\n { id: 5, name: \"Mango Juice\", amount: 35, spendDate: \"2020-10-16\", category: \"Food\" },\n { id: 6, name: \"Dress\", amount: 2000, spendDate: \"2020-10-25\", category: \"Cloth\" },\n { id: 7, name: \"Tour\", amount: 2555, spendDate: \"2020-10-29\", category: \"Entertainment\" },\n { id: 8, name: \"Meals\", amount: 300, spendDate: \"2020-10-30\", category: \"Food\" },\n { id: 9, name: \"Mobile\", amount: 3500, spendDate: \"2020-11-02\", category: \"Gadgets\" },\n { id: 10, name: \"Exam Fees\", amount: 1245, spendDate: \"2020-11-04\", category: \"Academic\" }\n ]\n items.forEach((item) => {\n this.props.onAddExpense(\n { \n name: item.name, \n amount: item.amount, \n spendDate: item.spendDate, \n category: item.category \n }\n );\n })\n}" }, { "code": null, "e": 84099, "s": 84027, "text": "Next, add an event handler to delete the expense item using expense id." }, { "code": null, "e": 84179, "s": 84099, "text": "handleDelete = (id,e) => {\n e.preventDefault();\n this.props.onDelete(id);\n}" }, { "code": null, "e": 84286, "s": 84179, "text": "Here, the event handler calls the onDelete dispatcher, which call deleteExpense along with the expense id." }, { "code": null, "e": 84352, "s": 84286, "text": "Next, add a method to calculate the total amount of all expenses." }, { "code": null, "e": 84510, "s": 84352, "text": "getTotal() {\n let total = 0;\n for (var i = 0; i < this.props.expenses.length; i++) {\n total += this.props.expenses[i].amount\n }\n return total;\n}" }, { "code": null, "e": 84585, "s": 84510, "text": "Next, add render() method and list the expense item in the tabular format." }, { "code": null, "e": 85599, "s": 84585, "text": "render() {\n const lists = this.props.expenses.map(\n (item) =>\n <tr key={item.id}>\n <td>{item.name}</td>\n <td>{item.amount}</td>\n <td>{new Date(item.spendDate).toDateString()}</td>\n <td>{item.category}</td>\n <td><a href=\"#\"\n onClick={(e) => this.handleDelete(item.id, e)}>Remove</a></td>\n </tr>\n );\n return (\n <div>\n <table>\n <thead>\n <tr>\n <th>Item</th>\n <th>Amount</th>\n <th>Date</th>\n <th>Category</th>\n <th>Remove</th>\n </tr>\n </thead>\n <tbody>\n {lists}\n <tr>\n <td colSpan=\"1\" style={{ textAlign: \"right\" }}>Total Amount</td>\n <td colSpan=\"4\" style={{ textAlign: \"left\" }}>\n {this.getTotal()}\n </td>\n </tr>\n </tbody>\n </table>\n </div>\n );\n}" }, { "code": null, "e": 85681, "s": 85599, "text": "Here, we set the event handler handleDelete to remove the expense from the store." }, { "code": null, "e": 85761, "s": 85681, "text": "The complete source code of the ExpenseEntryItemList component is given below βˆ’" }, { "code": null, "e": 89215, "s": 85761, "text": "import React from 'react';\nimport { connect } from 'react-redux';\nimport './ExpenseEntryItemList.css';\nimport { deleteExpense } from '../actions';\nimport { addExpense } from '../actions';\n\nclass ExpenseEntryItemList extends React.Component {\n constructor(props) {\n super(props);\n\n if (this.props.expenses.length == 0){\n const items = [\n { id: 1, name: \"Pizza\", amount: 80, spendDate: \"2020-10-10\", category: \"Food\" },\n { id: 2, name: \"Grape Juice\", amount: 30, spendDate: \"2020-10-12\", category: \"Food\" },\n { id: 3, name: \"Cinema\", amount: 210, spendDate: \"2020-10-16\", category: \"Entertainment\" },\n { id: 4, name: \"Java Programming book\", amount: 242, spendDate: \"2020-10-15\", category: \"Academic\" },\n { id: 5, name: \"Mango Juice\", amount: 35, spendDate: \"2020-10-16\", category: \"Food\" },\n { id: 6, name: \"Dress\", amount: 2000, spendDate: \"2020-10-25\", category: \"Cloth\" },\n { id: 7, name: \"Tour\", amount: 2555, spendDate: \"2020-10-29\", category: \"Entertainment\" },\n { id: 8, name: \"Meals\", amount: 300, spendDate: \"2020-10-30\", category: \"Food\" },\n { id: 9, name: \"Mobile\", amount: 3500, spendDate: \"2020-11-02\", category: \"Gadgets\" },\n { id: 10, name: \"Exam Fees\", amount: 1245, spendDate: \"2020-11-04\", category: \"Academic\" }\n ]\n items.forEach((item) => {\n this.props.onAddExpense(\n { \n name: item.name, \n amount: item.amount, \n spendDate: item.spendDate, \n category: item.category \n }\n );\n })\n }\n }\n handleDelete = (id,e) => {\n e.preventDefault();\n this.props.onDelete(id);\n }\n getTotal() {\n let total = 0;\n for (var i = 0; i < this.props.expenses.length; i++) {\n total += this.props.expenses[i].amount\n }\n return total;\n }\n render() {\n const lists = this.props.expenses.map((item) =>\n <tr key={item.id}>\n <td>{item.name}</td>\n <td>{item.amount}</td>\n <td>{new Date(item.spendDate).toDateString()}</td>\n <td>{item.category}</td>\n <td><a href=\"#\"\n onClick={(e) => this.handleDelete(item.id, e)}>Remove</a></td>\n </tr>\n );\n return (\n <div>\n <table>\n <thead>\n <tr>\n <th>Item</th>\n <th>Amount</th>\n <th>Date</th>\n <th>Category</th>\n <th>Remove</th>\n </tr>\n </thead>\n <tbody>\n {lists}\n <tr>\n <td colSpan=\"1\" style={{ textAlign: \"right\" }}>Total Amount</td>\n <td colSpan=\"4\" style={{ textAlign: \"left\" }}>\n {this.getTotal()}\n </td>\n </tr>\n </tbody>\n </table>\n </div>\n );\n }\n}\nconst mapStateToProps = state => {\n return {\n expenses: state\n };\n};\nconst mapDispatchToProps = dispatch => {\n return {\n onAddExpense: expense => {\n dispatch(addExpense(expense));\n },\n onDelete: id => {\n dispatch(deleteExpense(id));\n }\n };\n};\nexport default connect(\n mapStateToProps,\n mapDispatchToProps\n)(ExpenseEntryItemList);" }, { "code": null, "e": 89315, "s": 89215, "text": "Next, create a file, App.js under the src/components folder and use ExpenseEntryItemList component." }, { "code": null, "e": 89580, "s": 89315, "text": "import React, { Component } from 'react';\nimport ExpenseEntryItemList from './ExpenseEntryItemList';\n\nclass App extends Component {\n render() {\n return (\n <div>\n <ExpenseEntryItemList />\n </div>\n );\n }\n}\nexport default App;" }, { "code": null, "e": 89628, "s": 89580, "text": "Next, create a file, index.js under src folder." }, { "code": null, "e": 89995, "s": 89628, "text": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport { createStore } from 'redux';\nimport { Provider } from 'react-redux';\nimport rootReducer from './reducers';\nimport App from './components/App';\n\nconst store = createStore(rootReducer);\n\nReactDOM.render(\n <Provider store={store}>\n <App />\n </Provider>,\n document.getElementById('root')\n);" }, { "code": null, "e": 90001, "s": 89995, "text": "Here," }, { "code": null, "e": 90064, "s": 90001, "text": "Create a store using createStore by attaching the our reducer." }, { "code": null, "e": 90127, "s": 90064, "text": "Create a store using createStore by attaching the our reducer." }, { "code": null, "e": 90282, "s": 90127, "text": "Used Provider component from React redux library and set the store as props, which enables all the nested component to connect to store using connect api." }, { "code": null, "e": 90437, "s": 90282, "text": "Used Provider component from React redux library and set the store as props, which enables all the nested component to connect to store using connect api." }, { "code": null, "e": 90519, "s": 90437, "text": "Finally, create a public folder under the root folder and create index.html file." }, { "code": null, "e": 90766, "s": 90519, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>React Containment App</title>\n </head>\n <body>\n <div id=\"root\"></div>\n <script type=\"text/JavaScript\" src=\"./index.js\"></script>\n </body>\n</html>" }, { "code": null, "e": 90813, "s": 90766, "text": "Next, serve the application using npm command." }, { "code": null, "e": 90824, "s": 90813, "text": "npm start\n" }, { "code": null, "e": 90915, "s": 90824, "text": "Next, open the browser and enter http://localhost:3000 in the address bar and press enter." }, { "code": null, "e": 90979, "s": 90915, "text": "Clicking the remove link will remove the item from redux store." }, { "code": null, "e": 91455, "s": 90979, "text": "Animation is an exciting feature of modern web application. It gives a refreshing feel to the application. React community provides many excellent react based animation library like React Motion, React Reveal, react-animations, etc., React itself provides an animation library, React Transition Group as an add-on option earlier. It is an independent library enhancing the earlier version of the library. Let us learn React Transition Group animation library in this chapter." }, { "code": null, "e": 91800, "s": 91455, "text": "React Transition Group library is a simple implementation of animation. It does not do any animation out of the box. Instead, it exposes the core animation related information. Every animation is basically transition of an element from one state to another. The library exposes minimum possible state of every element and they are given below βˆ’" }, { "code": null, "e": 91809, "s": 91800, "text": "Entering" }, { "code": null, "e": 91817, "s": 91809, "text": "Entered" }, { "code": null, "e": 91825, "s": 91817, "text": "Exiting" }, { "code": null, "e": 91832, "s": 91825, "text": "Exited" }, { "code": null, "e": 92246, "s": 91832, "text": "The library provides options to set CSS style for each state and animate the element based on the style when the element moves from one state to another. The library provides in props to set the current state of the element. If in props value is true, then it means the element is moving from entering state to exiting state. If in props value is false, then it means the element is moving from exiting to exited." }, { "code": null, "e": 92444, "s": 92246, "text": "Transition is the basic component provided by the React Transition Group to animate an element. Let us create a simple application and try to fade in / fade out an element using Transition element." }, { "code": null, "e": 92610, "s": 92444, "text": "First, create a new react application, react-animation-app using Create React App or Rollup bundler by following instruction in Creating a React application chapter." }, { "code": null, "e": 92656, "s": 92610, "text": "Next, install React Transition Group library." }, { "code": null, "e": 92718, "s": 92656, "text": "cd /go/to/project \nnpm install react-transition-group --save\n" }, { "code": null, "e": 92770, "s": 92718, "text": "Next, open the application in your favorite editor." }, { "code": null, "e": 92839, "s": 92770, "text": "Next, create src folder under the root directory of the application." }, { "code": null, "e": 92888, "s": 92839, "text": "Next, create components folder under src folder." }, { "code": null, "e": 92970, "s": 92888, "text": "Next, create a file, HelloWorld.js under src/components folder and start editing." }, { "code": null, "e": 93012, "s": 92970, "text": "Next, import React and animation library." }, { "code": null, "e": 93093, "s": 93012, "text": "import React from 'react'; \nimport { Transition } from 'react-transition-group'\n" }, { "code": null, "e": 93132, "s": 93093, "text": "Next, create the HelloWorld component." }, { "code": null, "e": 93226, "s": 93132, "text": "class HelloWorld extends React.Component {\n constructor(props) {\n super(props);\n }\n}" }, { "code": null, "e": 93307, "s": 93226, "text": "Next, define transition related styles as JavaScript objects in the constructor." }, { "code": null, "e": 93566, "s": 93307, "text": "this.duration = 2000;\nthis.defaultStyle = {\n transition: `opacity ${this.duration}ms ease-in-out`,\n opacity: 0,\n}\nthis.transitionStyles = {\n entering: { opacity: 1 },\n entered: { opacity: 1 },\n exiting: { opacity: 0 },\n exited: { opacity: 0 },\n};" }, { "code": null, "e": 93572, "s": 93566, "text": "Here," }, { "code": null, "e": 93616, "s": 93572, "text": "defaultStyles sets the transition animation" }, { "code": null, "e": 93660, "s": 93616, "text": "defaultStyles sets the transition animation" }, { "code": null, "e": 93711, "s": 93660, "text": "transitionStyles set the styles for various states" }, { "code": null, "e": 93762, "s": 93711, "text": "transitionStyles set the styles for various states" }, { "code": null, "e": 93826, "s": 93762, "text": "Next, set the initial state for the element in the constructor." }, { "code": null, "e": 93861, "s": 93826, "text": "this.state = { \n inProp: true \n}" }, { "code": null, "e": 93937, "s": 93861, "text": "Next, simulate the animation by changing the inProp values every 3 seconds." }, { "code": null, "e": 94096, "s": 93937, "text": "setInterval(() => {\n this.setState((state, props) => {\n let newState = {\n inProp: !state.inProp\n };\n return newState;\n })\n}, 3000);" }, { "code": null, "e": 94128, "s": 94096, "text": "Next, create a render function." }, { "code": null, "e": 94162, "s": 94128, "text": "render() { \n return ( \n ); \n}" }, { "code": null, "e": 94371, "s": 94162, "text": "Next, add Transition component. Use this.state.inProp for in prop and this.duration for timeout prop. Transition component expects a function, which returns the user interface. It is basically a Render props." }, { "code": null, "e": 94566, "s": 94371, "text": "render() {\n return (\n <Transition in={this.state.inProp} timeout={this.duration}>\n {state => ({\n ... component's user interface.\n })\n </Transition>\n );\n}" }, { "code": null, "e": 94692, "s": 94566, "text": "Next, write the components user interface inside a container and set the defaultStyle and transitionStyles for the container." }, { "code": null, "e": 95024, "s": 94692, "text": "render() {\n return (\n <Transition in={this.state.inProp} timeout={this.duration}>\n {state => (\n <div style={{\n ...this.defaultStyle,\n ...this.transitionStyles[state]\n }}>\n <h1>Hello World!</h1>\n </div>\n )}\n </Transition>\n );\n}" }, { "code": null, "e": 95055, "s": 95024, "text": "Finally, expose the component." }, { "code": null, "e": 95082, "s": 95055, "text": "export default HelloWorld\n" }, { "code": null, "e": 95140, "s": 95082, "text": "The complete source code of the component is as follows βˆ’" }, { "code": null, "e": 96299, "s": 95140, "text": "import React from \"react\";\nimport { Transition } from 'react-transition-group';\n\nclass HelloWorld extends React.Component {\n constructor(props) {\n super(props);\n this.duration = 2000;\n this.defaultStyle = {\n transition: `opacity ${this.duration}ms ease-in-out`,\n opacity: 0,\n }\n this.transitionStyles = {\n entering: { opacity: 1 },\n entered: { opacity: 1 },\n exiting: { opacity: 0 },\n exited: { opacity: 0 },\n };\n this.state = {\n inProp: true\n }\n setInterval(() => {\n this.setState((state, props) => {\n let newState = {\n inProp: !state.inProp\n };\n return newState;\n })\n }, 3000);\n }\n render() {\n return (\n <Transition in={this.state.inProp} timeout={this.duration}>\n {state => (\n <div style={{\n ...this.defaultStyle,\n ...this.transitionStyles[state]\n }}>\n <h1>Hello World!</h1>\n </div>\n )}\n </Transition>\n );\n }\n}\nexport default HelloWorld;" }, { "code": null, "e": 96380, "s": 96299, "text": "Next, create a file, index.js under the src folder and use HelloWorld component." }, { "code": null, "e": 96620, "s": 96380, "text": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport HelloWorld from './components/HelloWorld';\n\nReactDOM.render(\n <React.StrictMode \n <HelloWorld / \n </React.StrictMode ,\n document.getElementById('root')\n);" }, { "code": null, "e": 96702, "s": 96620, "text": "Finally, create a public folder under the root folder and create index.html file." }, { "code": null, "e": 96949, "s": 96702, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>React Containment App</title>\n </head>\n <body>\n <div id=\"root\"></div>\n <script type=\"text/JavaScript\" src=\"./index.js\"></script>\n </body>\n</html>" }, { "code": null, "e": 96996, "s": 96949, "text": "Next, serve the application using npm command." }, { "code": null, "e": 97007, "s": 96996, "text": "npm start\n" }, { "code": null, "e": 97098, "s": 97007, "text": "Next, open the browser and enter http://localhost:3000 in the address bar and press enter." }, { "code": null, "e": 97162, "s": 97098, "text": "Clicking the remove link will remove the item from redux store." }, { "code": null, "e": 97366, "s": 97162, "text": "CSSTransition is built on top of Transition component and it improves Transition component by introducing classNames prop. classNames prop refers the css class name used for various state of the element." }, { "code": null, "e": 97427, "s": 97366, "text": "For example, classNames=hello prop refers below css classes." }, { "code": null, "e": 97627, "s": 97427, "text": ".hello-enter {\n opacity: 0;\n}\n.hello-enter-active {\n opacity: 1;\n transition: opacity 200ms;\n}\n.hello-exit {\n opacity: 1;\n}\n.hello-exit-active {\n opacity: 0;\n transition: opacity 200ms;\n}" }, { "code": null, "e": 97712, "s": 97627, "text": "Let us create a new component HelloWorldCSSTransition using CSSTransition component." }, { "code": null, "e": 97785, "s": 97712, "text": "First, open our react-animation-app application in your favorite editor." }, { "code": null, "e": 97896, "s": 97785, "text": "Next, create a new file, HelloWorldCSSTransition.css under src/components folder and enter transition classes." }, { "code": null, "e": 98208, "s": 97896, "text": ".hello-enter {\n opacity: 1;\n transition: opacity 2000ms ease-in-out;\n}\n.hello-enter-active {\n opacity: 1;\n transition: opacity 2000ms ease-in-out;\n}\n.hello-exit {\n opacity: 0;\n transition: opacity 2000ms ease-in-out;\n}\n.hello-exit-active {\n opacity: 0;\n transition: opacity 2000ms ease-in-out;\n}" }, { "code": null, "e": 98307, "s": 98208, "text": "Next, create a new file, HelloWorldCSSTransition.js under src/components folder and start editing." }, { "code": null, "e": 98349, "s": 98307, "text": "Next, import React and animation library." }, { "code": null, "e": 98432, "s": 98349, "text": "import React from 'react'; \nimport { CSSTransition } from 'react-transition-group'" }, { "code": null, "e": 98474, "s": 98432, "text": "Next, import HelloWorldCSSTransition.css." }, { "code": null, "e": 98513, "s": 98474, "text": "import './HelloWorldCSSTransition.css'" }, { "code": null, "e": 98552, "s": 98513, "text": "Next, create the HelloWorld component." }, { "code": null, "e": 98659, "s": 98552, "text": "class HelloWorldCSSTransition extends React.Component {\n constructor(props) {\n super(props);\n }\n}" }, { "code": null, "e": 98719, "s": 98659, "text": "Next, define duration of the transition in the constructor." }, { "code": null, "e": 98742, "s": 98719, "text": "this.duration = 2000;\n" }, { "code": null, "e": 98806, "s": 98742, "text": "Next, set the initial state for the element in the constructor." }, { "code": null, "e": 98841, "s": 98806, "text": "this.state = { \n inProp: true \n}" }, { "code": null, "e": 98917, "s": 98841, "text": "Next, simulate the animation by changing the inProp values every 3 seconds." }, { "code": null, "e": 99076, "s": 98917, "text": "setInterval(() => {\n this.setState((state, props) => {\n let newState = {\n inProp: !state.inProp\n };\n return newState;\n })\n}, 3000);" }, { "code": null, "e": 99108, "s": 99076, "text": "Next, create a render function." }, { "code": null, "e": 99141, "s": 99108, "text": "render() { \n return (\n ); \n}" }, { "code": null, "e": 99335, "s": 99141, "text": "Next, add CSSTransition component. Use this.state.inProp for in prop, this.duration for timeout prop and hello for classNames prop. CSSTransition component expects user interface as child prop." }, { "code": null, "e": 99530, "s": 99335, "text": "render() {\n return (\n <CSSTransition in={this.state.inProp} timeout={this.duration} \n classNames=\"hello\">\n // ... user interface code ... \n </CSSTransition>\n );\n}" }, { "code": null, "e": 99573, "s": 99530, "text": "Next, write the components user interface." }, { "code": null, "e": 99781, "s": 99573, "text": "render() {\n return (\n <CSSTransition in={this.state.inProp} timeout={this.duration} \n classNames=\"hello\">\n <div>\n <h1>Hello World!</h1>\n </div>\n </CSSTransition>\n );\n}" }, { "code": null, "e": 99812, "s": 99781, "text": "Finally, expose the component." }, { "code": null, "e": 99853, "s": 99812, "text": "export default HelloWorldCSSTransition;\n" }, { "code": null, "e": 99912, "s": 99853, "text": "The complete source code of the component is given below βˆ’" }, { "code": null, "e": 100715, "s": 99912, "text": "import React from 'react';\nimport { CSSTransition } from 'react-transition-group'\nimport './HelloWorldCSSTransition.css' \n\nclass HelloWorldCSSTransition extends React.Component {\n constructor(props) {\n super(props);\n this.duration = 2000;\n this.state = {\n inProp: true\n }\n setInterval(() => {\n this.setState((state, props) => {\n let newState = {\n inProp: !state.inProp\n };\n return newState;\n })\n }, 3000);\n }\n render() {\n return (\n <CSSTransition in={this.state.inProp} timeout={this.duration} \n classNames=\"hello\">\n <div>\n <h1>Hello World!</h1>\n </div>\n </CSSTransition>\n );\n }\n}\nexport default HelloWorldCSSTransition;" }, { "code": null, "e": 100796, "s": 100715, "text": "Next, create a file, index.js under the src folder and use HelloWorld component." }, { "code": null, "e": 101069, "s": 100796, "text": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport HelloWorldCSSTransition from './components/HelloWorldCSSTransition';\n\nReactDOM.render(\n <React.StrictMode>\n <HelloWorldCSSTransition />\n </React.StrictMode>,\n document.getElementById('root')\n);" }, { "code": null, "e": 101116, "s": 101069, "text": "Next, serve the application using npm command." }, { "code": null, "e": 101127, "s": 101116, "text": "npm start\n" }, { "code": null, "e": 101218, "s": 101127, "text": "Next, open the browser and enter http://localhost:3000 in the address bar and press enter." }, { "code": null, "e": 101272, "s": 101218, "text": "The message will fade in and out for every 3 seconds." }, { "code": null, "e": 101499, "s": 101272, "text": "TransitionGroup is a container component, which manages multiple transition component in a list. For example, while each item in a list use CSSTransition, TransitionGroup can be used to group all the item for proper animation." }, { "code": null, "e": 101896, "s": 101499, "text": "<TransitionGroup>\n {items.map(({ id, text }) => (\n <CSSTransition key={id} timeout={500} classNames=\"item\" >\n <Button\n onClick={() =>\n setItems(items =>\n items.filter(item => item.id !== id)\n )\n }\n >\n &times;\n </Button>\n {text}\n </CSSTransition>\n ))}\n</TransitionGroup>" }, { "code": null, "e": 102244, "s": 101896, "text": "Testing is one of the processes to make sure that the functionality created in any application is working in accordance with the business logic and coding specification. React recommends React testing library to test React components and jest test runner to run the test. The react-testing-library allows the components to be checked in isolation." }, { "code": null, "e": 102305, "s": 102244, "text": "It can be installed in the application using below command βˆ’" }, { "code": null, "e": 102374, "s": 102305, "text": "npm install --save @testing-library/react @testing-library/jest-dom\n" }, { "code": null, "e": 102544, "s": 102374, "text": "Create React app configures React testing library and jest test runner by default. So, testing a React application created using Create React App is just a command away." }, { "code": null, "e": 102583, "s": 102544, "text": "cd /go/to/react/application \nnpm test\n" }, { "code": null, "e": 102776, "s": 102583, "text": "The npm test command is similar to npm build command. Both re-compiles as and when the developer changes the code. Once the command is executed in the command prompt, it emits below questions." }, { "code": null, "e": 103158, "s": 102776, "text": "No tests found related to files changed since last commit.\nPress `a` to run all tests, or run Jest with `--watchAll`.\n\nWatch Usage\n β€Ί Press a to run all tests.\n β€Ί Press f to run only failed tests.\n β€Ί Press q to quit watch mode.\n β€Ί Press p to filter by a filename regex pattern.\n β€Ί Press t to filter by a test name regex pattern.\n β€Ί Press Enter to trigger a test run. \n" }, { "code": null, "e": 103255, "s": 103158, "text": "Pressing a will try to run all the test script and finally summaries the result as shown below βˆ’" }, { "code": null, "e": 103434, "s": 103255, "text": "Test Suites: 1 passed, 1 total\nTests: 1 passed, 1 total\nSnapshots: 0 total\nTime: 4.312 s, estimated 12 s\nRan all test suites.\n\nWatch Usage: Press w to show more. \n" }, { "code": null, "e": 103573, "s": 103434, "text": "Let us write a custom React application using Rollup bundler and test it using React testing library and jest test runner in this chapter." }, { "code": null, "e": 103714, "s": 103573, "text": "First, create a new react application, react-test-app using Rollup bundler by following instruction in Creating a React application chapter." }, { "code": null, "e": 103749, "s": 103714, "text": "Next, install the testing library." }, { "code": null, "e": 103844, "s": 103749, "text": "cd /go/to/react-test-app \nnpm install --save @testing-library/react @testing-library/jest-dom\n" }, { "code": null, "e": 103896, "s": 103844, "text": "Next, open the application in your favorite editor." }, { "code": null, "e": 104022, "s": 103896, "text": "Next, create a file, HelloWorld.test.js under src/components folder to write test for HelloWorld component and start editing." }, { "code": null, "e": 104050, "s": 104022, "text": "Next, import react library." }, { "code": null, "e": 104078, "s": 104050, "text": "import React from 'react';\n" }, { "code": null, "e": 104112, "s": 104078, "text": "Next, import the testing library." }, { "code": null, "e": 104205, "s": 104112, "text": "import { render, screen } from '@testing-library/react'; import '@testing-library/jest-dom';" }, { "code": null, "e": 104244, "s": 104205, "text": "Next, import our HelloWorld component." }, { "code": null, "e": 104284, "s": 104244, "text": "import HelloWorld from './HelloWorld';\n" }, { "code": null, "e": 104363, "s": 104284, "text": "Next, write a test to check the existence of Hello World text in the document." }, { "code": null, "e": 104519, "s": 104363, "text": "test('test scenario 1', () => {\n render(<HelloWorld />);\n const element = screen.getByText(/Hello World/i);\n expect(element).toBeInTheDocument();\n});" }, { "code": null, "e": 104578, "s": 104519, "text": "The complete source code of the test code is given below βˆ’" }, { "code": null, "e": 104894, "s": 104578, "text": "import React from 'react';\nimport { render, screen } from '@testing-library/react';\nimport '@testing-library/jest-dom';\nimport HelloWorld from './HelloWorld';\n\ntest('test scenario 1', () => {\n render(<HelloWorld />);\n const element = screen.getByText(/Hello World/i);\n expect(element).toBeInTheDocument();\n});" }, { "code": null, "e": 104972, "s": 104894, "text": "Next, install jest test runner, if it is not installed already in the system." }, { "code": null, "e": 104993, "s": 104972, "text": "npm install jest -g\n" }, { "code": null, "e": 105055, "s": 104993, "text": "Next, run jest command in the root folder of the application." }, { "code": null, "e": 105061, "s": 105055, "text": "jest\n" }, { "code": null, "e": 105123, "s": 105061, "text": "Next, run jest command in the root folder of the application." }, { "code": null, "e": 105319, "s": 105123, "text": "PASS src/components/HelloWorld.test.js\n √ test scenario 1 (29 ms)\n\nTest Suites: 1 passed, 1 total\nTests: 1 passed, 1 total\nSnapshots: 0 total\nTime: 5.148 s\nRan all test suites.\n" }, { "code": null, "e": 105422, "s": 105319, "text": "Let us learn the basic command available in Create React App command line application in this chapter." }, { "code": null, "e": 105491, "s": 105422, "text": "Create React App provides multiple ways to create React application." }, { "code": null, "e": 105509, "s": 105491, "text": "Using npx script." }, { "code": null, "e": 105585, "s": 105509, "text": "npx create-react-app <react-app-name>\nnpx create-react-app hello-react-app\n" }, { "code": null, "e": 105612, "s": 105585, "text": "Using npm package manager." }, { "code": null, "e": 105684, "s": 105612, "text": "npm init react-app <react-app-name>\nnpm init react-app hello-react-app\n" }, { "code": null, "e": 105712, "s": 105684, "text": "Using yarn package manager." }, { "code": null, "e": 105786, "s": 105712, "text": "yarn init react-app <react-app-name>\nyarn init react-app hello-react-app\n" }, { "code": null, "e": 106115, "s": 105786, "text": "Create React App creates React application using default template. Template refers the initial code with certain build-in functionality. There are hundreds of template with many advanced features are available in npm package server. Create React App allows the users to select the template through –template command line switch." }, { "code": null, "e": 106162, "s": 106115, "text": "create-react-app my-app --template typescript\n" }, { "code": null, "e": 106253, "s": 106162, "text": "Above command will create react app using cra-template-typescript package from npm server." }, { "code": null, "e": 106401, "s": 106253, "text": "React dependency package can be installed using normal npm or yarn package command as React uses the project structure recommended by npm and yarn." }, { "code": null, "e": 106428, "s": 106401, "text": "Using npm package manager." }, { "code": null, "e": 106465, "s": 106428, "text": "npm install --save react-router-dom\n" }, { "code": null, "e": 106493, "s": 106465, "text": "Using yarn package manager." }, { "code": null, "e": 106520, "s": 106493, "text": "yarn add react-router-dom\n" }, { "code": null, "e": 106633, "s": 106520, "text": "React application can be started using npm or yarn command depending on the package manager used in the project." }, { "code": null, "e": 106660, "s": 106633, "text": "Using npm package manager." }, { "code": null, "e": 106671, "s": 106660, "text": "npm start\n" }, { "code": null, "e": 106699, "s": 106671, "text": "Using yarn package manager." }, { "code": null, "e": 106711, "s": 106699, "text": "yarn start\n" }, { "code": null, "e": 106965, "s": 106711, "text": "To run the application in secure mode (HTTPS), set an environment variable, HTTPS and set it to true before starting the application. For example, in windows command prompt (cmd.exe), the below command set HTTPS and starts the application is HTTPS mode." }, { "code": null, "e": 106994, "s": 106965, "text": "set HTTPS=true && npm start\n" }, { "code": null, "e": 107087, "s": 106994, "text": "Let us learn how to do production build and deployment of React application in this chapter." }, { "code": null, "e": 107290, "s": 107087, "text": "Once a React application development is done, application needs to be bundled and deployed to a production server. Let us learn the command available to build and deploy the application in this chapter." }, { "code": null, "e": 107366, "s": 107290, "text": "A single command is enough to create a production build of the application." }, { "code": null, "e": 108125, "s": 107366, "text": "npm run build\n> expense-manager@0.1.0 build path\\to\\expense-manager\n> react-scripts build\n\nCreating an optimized production build...\nCompiled with warnings.\n\nFile sizes after gzip:\n\n 41.69 KB build\\static\\js\\2.a164da11.chunk.js\n 2.24 KB build\\static\\js\\main.de70a883.chunk.js\n 1.4 KB build\\static\\js\\3.d8a9fc85.chunk.js\n 1.17 KB build\\static\\js\\runtime-main.560bee6e.js\n 493 B build\\static\\css\\main.e75e7bbe.chunk.css\n\nThe project was built assuming it is hosted at /.\nYou can control this with the homepage field in your package.json.\n\nThe build folder is ready to be deployed.\nYou may serve it with a static server:\n\n npm install -g serve\n serve -s build\n\nFind out more about deployment here:\n\n https://cra.link/deployment\n" }, { "code": null, "e": 108212, "s": 108125, "text": "Once the application is build, the application is available under build/static folder." }, { "code": null, "e": 108458, "s": 108212, "text": "By default, profiling option is disable and can be enabled through –profile command line option. –profile will include profiling information in the code. The profiling information can be used along with React DevTools to analyse the application." }, { "code": null, "e": 108486, "s": 108458, "text": "npm run build -- --profile\n" }, { "code": null, "e": 108619, "s": 108486, "text": "Once the application is build, it can be deployed to any web server. Let us learn how to deploy a React application in this chapter." }, { "code": null, "e": 108726, "s": 108619, "text": "Local deployment can be done using serve package. Let us first install serve package using below command βˆ’" }, { "code": null, "e": 108749, "s": 108726, "text": "npm install -g server\n" }, { "code": null, "e": 108811, "s": 108749, "text": "To start the application using serve, use the below command βˆ’" }, { "code": null, "e": 108854, "s": 108811, "text": "cd /go/to/app/root/folder \nserve -s build\n" }, { "code": null, "e": 108966, "s": 108854, "text": "By default, serve serve the application using port 5000. The application can be viewed @ http://localhost:5000." }, { "code": null, "e": 109168, "s": 108966, "text": "Production deployment can be easily done by copying the files under build/static folder to the production application’s root directory. It will work in all web server including Apache, IIS, Nginx, etc." }, { "code": null, "e": 109433, "s": 109168, "text": "By default, the production build is created assuming that the application will be hosted in the root folder of a web application. If the application needs to be hosted in a subfolder, then use below configuration in the package.json and then build the application." }, { "code": null, "e": 109501, "s": 109433, "text": "{ ... \"homepage\": \"http://domainname.com/path/to/subfolder\", ... }\n" }, { "code": null, "e": 109656, "s": 109501, "text": "Let us create a sample expense manager application by applying the concepts that we have learned in this tutorial. Some of the concepts are listed below βˆ’" }, { "code": null, "e": 109703, "s": 109656, "text": "React basics (component, jsx, props and state)" }, { "code": null, "e": 109750, "s": 109703, "text": "React basics (component, jsx, props and state)" }, { "code": null, "e": 109776, "s": 109750, "text": "Router using react-router" }, { "code": null, "e": 109802, "s": 109776, "text": "Router using react-router" }, { "code": null, "e": 109836, "s": 109802, "text": "Http client programming (Web API)" }, { "code": null, "e": 109870, "s": 109836, "text": "Http client programming (Web API)" }, { "code": null, "e": 109900, "s": 109870, "text": "Form programming using Formik" }, { "code": null, "e": 109930, "s": 109900, "text": "Form programming using Formik" }, { "code": null, "e": 109968, "s": 109930, "text": "Advanced state management using Redux" }, { "code": null, "e": 110006, "s": 109968, "text": "Advanced state management using Redux" }, { "code": null, "e": 110032, "s": 110006, "text": "Async / await programming" }, { "code": null, "e": 110058, "s": 110032, "text": "Async / await programming" }, { "code": null, "e": 110127, "s": 110058, "text": "Some of the features of our sample expense manager application are βˆ’" }, { "code": null, "e": 110168, "s": 110127, "text": "Listing all the expenses from the server" }, { "code": null, "e": 110209, "s": 110168, "text": "Listing all the expenses from the server" }, { "code": null, "e": 110229, "s": 110209, "text": "Add an expense item" }, { "code": null, "e": 110249, "s": 110229, "text": "Add an expense item" }, { "code": null, "e": 110272, "s": 110249, "text": "Delete an expense item" }, { "code": null, "e": 110295, "s": 110272, "text": "Delete an expense item" }, { "code": null, "e": 110301, "s": 110295, "text": "Here," }, { "code": null, "e": 110321, "s": 110301, "text": "Expense manager API" }, { "code": null, "e": 110341, "s": 110321, "text": "Expense manager API" }, { "code": null, "e": 110367, "s": 110341, "text": "Install necessary modules" }, { "code": null, "e": 110393, "s": 110367, "text": "Install necessary modules" }, { "code": null, "e": 110410, "s": 110393, "text": "State management" }, { "code": null, "e": 110427, "s": 110410, "text": "State management" }, { "code": null, "e": 110441, "s": 110427, "text": "List expenses" }, { "code": null, "e": 110455, "s": 110441, "text": "List expenses" }, { "code": null, "e": 110467, "s": 110455, "text": "Add expense" }, { "code": null, "e": 110479, "s": 110467, "text": "Add expense" }, { "code": null, "e": 110514, "s": 110479, "text": "\n 20 Lectures \n 1.5 hours \n" }, { "code": null, "e": 110528, "s": 110514, "text": " Anadi Sharma" }, { "code": null, "e": 110563, "s": 110528, "text": "\n 60 Lectures \n 4.5 hours \n" }, { "code": null, "e": 110583, "s": 110563, "text": " Skillbakerystudios" }, { "code": null, "e": 110618, "s": 110583, "text": "\n 165 Lectures \n 13 hours \n" }, { "code": null, "e": 110641, "s": 110618, "text": " Paul Carlo Tordecilla" }, { "code": null, "e": 110676, "s": 110641, "text": "\n 63 Lectures \n 9.5 hours \n" }, { "code": null, "e": 110692, "s": 110676, "text": " TELCOMA Global" }, { "code": null, "e": 110725, "s": 110692, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 110743, "s": 110725, "text": " Mohd Raqif Warsi" }, { "code": null, "e": 110750, "s": 110743, "text": " Print" }, { "code": null, "e": 110761, "s": 110750, "text": " Add Notes" } ]
Python - Google Maps
Python provides modules which can be used to translate addresses available in google map directly to geographic coordinates. It is helpful in finding business addresses and locating the closeness of different addresses. We use a module named pygeocoder which provides the functionalities to receive addresses and geocodes. This module is installed through pip using the following command. pip install pygeocoder We submit a business name as input and the program gives the complete address as the output. The module uses data from google maps in the background to retrieve the result. from pygeocoder import Geocoder business_name = "Workafella Business Centre - Hitec city" print "Searching %s" %business_name results = Geocoder.geocode(business_name) for result in results: print result When we run the above program, we get the following output βˆ’ Searching Workafella Business Centre - Hitec city Western pearl building 1st floor, Hitech City Rd, Opposite HDFC Bank, Kondapur, Hyderabad, Telangana 500084, India 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2547, "s": 2326, "text": "Python provides modules which can be used to translate addresses available in google map directly to geographic coordinates. It is helpful in finding business addresses and locating the closeness of different addresses. " }, { "code": null, "e": 2717, "s": 2547, "text": "We use a module named pygeocoder which provides the functionalities to receive addresses and geocodes. This module is installed through pip using the following command. " }, { "code": null, "e": 2741, "s": 2717, "text": "pip install pygeocoder " }, { "code": null, "e": 2916, "s": 2741, "text": " We submit a business name as input and the program gives the complete address as the output. The module uses data from google maps in the background to retrieve the result. " }, { "code": null, "e": 3125, "s": 2916, "text": "from pygeocoder import Geocoder\n\nbusiness_name = \"Workafella Business Centre - Hitec city\"\nprint \"Searching %s\" %business_name\nresults = Geocoder.geocode(business_name)\nfor result in results:\n print result" }, { "code": null, "e": 3186, "s": 3125, "text": "When we run the above program, we get the following output βˆ’" }, { "code": null, "e": 3353, "s": 3186, "text": "Searching Workafella Business Centre - Hitec city\nWestern pearl building 1st floor, Hitech City Rd, \nOpposite HDFC Bank, Kondapur, Hyderabad, Telangana 500084, India\n" }, { "code": null, "e": 3390, "s": 3353, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3406, "s": 3390, "text": " Malhar Lathkar" }, { "code": null, "e": 3439, "s": 3406, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3458, "s": 3439, "text": " Arnab Chakraborty" }, { "code": null, "e": 3493, "s": 3458, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3515, "s": 3493, "text": " In28Minutes Official" }, { "code": null, "e": 3549, "s": 3515, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3577, "s": 3549, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3612, "s": 3577, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3626, "s": 3612, "text": " Lets Kode It" }, { "code": null, "e": 3659, "s": 3626, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3676, "s": 3659, "text": " Abhilash Nelson" }, { "code": null, "e": 3683, "s": 3676, "text": " Print" }, { "code": null, "e": 3694, "s": 3683, "text": " Add Notes" } ]
Batch Script - DIR
This batch command lists the contents of a directory. dir The following example shows the different variants of the dir command. @echo off Rem All the directory listings from C:\ will be routed to the file lists.txt dir C:\>C:\lists.txt Rem Lists all directories and subdirectories recursively dir /s Rem Lists the contents of the directory and all subdirectories recursively, one file per line, displaying complete path for each listed file or directory. dir /s /b Rem Lists all files with .txt extension. dir *.txt Rem Includes hidden files and system files in the listing. dir /a Rem Lists hidden files only. dir /ah All actions are performed as per the remarks in the batch file. Print Add Notes Bookmark this page
[ { "code": null, "e": 2223, "s": 2169, "text": "This batch command lists the contents of a directory." }, { "code": null, "e": 2228, "s": 2223, "text": "dir\n" }, { "code": null, "e": 2299, "s": 2228, "text": "The following example shows the different variants of the dir command." }, { "code": null, "e": 2791, "s": 2299, "text": "@echo off\nRem All the directory listings from C:\\ will be routed to the file lists.txt\ndir C:\\>C:\\lists.txt\nRem Lists all directories and subdirectories recursively\ndir /s\nRem Lists the contents of the directory and all subdirectories recursively, one \nfile per line, displaying complete path for each listed file or directory.\ndir /s /b\nRem Lists all files with .txt extension.\ndir *.txt\nRem Includes hidden files and system files in the listing.\ndir /a\nRem Lists hidden files only.\ndir /ah" }, { "code": null, "e": 2855, "s": 2791, "text": "All actions are performed as per the remarks in the batch file." }, { "code": null, "e": 2862, "s": 2855, "text": " Print" }, { "code": null, "e": 2873, "s": 2862, "text": " Add Notes" } ]
Use Cython to get more than 30X speedup on your Python code | by George Seif | Towards Data Science
Want to be inspired? Come join my Super Quotes newsletter. 😎 Python is a community favourite programming language! It’s by far one of the easiest to use as code is written in an intuitive, human-readable way. Yet you’ll often hear the same complaint about Python over and over again, especially from the C code gurus out there: Python is slow. And they’re not wrong. Relative to many other programming languages, Python is slow. Benchmark game has some solid benchmarks for comparing the speed of various programming languages on different tasks. There’s a couple of different ways to speed things up that I’ve written about before: (1) Use multi-processing libraries to use all the CPU cores (2) If you’re using Numpy, Pandas, or Scikit-Learn, use Rapids to accelerate the processing on GPU. Those are great if what you’re doing can, in fact, be parallelized, such as data pre-processing or matrix operations. But what if your code is pure Python? What if you have a big for-loop that you just have to use and can’t put into a matrix because the data has to be processed in sequence? Is there a way to speedup Python itself? That’s where Cython comes in to speed up our raw Python code. At its core, Cython is an intermediate step between Python and C/C++. It allows you to write pure Python code with some minor modifications, which is then translated directly into C code. The only adjustment you make to your Python code is adding type information to every variable. Normally, we might declare a variable in Python like this: x = 0.5 With Cython, we’re going to add a type to that variable: cdef float x = 0.5 This tells Cython that our variable is floating point, just like we would do in C. With pure Python, the variable’s type is determined on the fly. The explicit declaration of the type in Cython is what makes the conversion to C possible, since explicit type declarations are required+. Installing Cython requires just a single line of pip: pip install cython When using Cython, there are two different sets of types, for variables and functions. For variables we have: cdef int a, b, c cdef char *s cdef float x = 0.5 (single precision) cdef double x = 63.4 (double precision) cdef list names cdef dict goals_for_each_play cdef object card_deck Notice how all of these types come from C/C++! For the functions we have: def β€” regular python function, calls from Python only. cdef β€” Cython only functions which can’t be accessed from python-only code i.e must be called within Cython cpdef β€” C and Python. Can be accessed from both C and Python With an understanding of Cython types in hand, we can go right ahead and implement our speedup! The first thing we’ll do is set up a Python code benchmark: a for-loop used to compute the factorial of a number. The raw Python code is shown below: Our Cython equivalent of the same function looks very similar. First, we’ll make sure that our Cython code file has a .pyx extension. The only change to the code itself is that we’ve declared the type of each and every variable and function. Notice how the function has a cpdef to make sure we can call it from Python. Also see how even our looping variable i has a type. You’ll need to set the type for all of the variables in the function, so that the C compiler knows what type to use! Next, create a setup.py file which will compile the Cython code into C code: And perform the compilation: python setup.py build_ext --inplace Boom! Our C code has been compiled and is ready to use! You’ll see that in the folder where your Cython code is, you have all the files needed to run C code, including the run_cython.c file. If you’re curious, take a look at it to see the C code that Cython generated! Now we’re ready to test out our new, super fast C code! Check out the code below, which implements a speed test to compare the raw Python code to the Cython one. The code is very straight forward. We’re importing our files in the same way as regular Python, and running the functions in the same way as regular Python! Cython will get you good speedups on almost any raw Python code, without too much extra effort at all. The key thing to note is that the more loops you’re going through, and the more data you’re crunching, the more Cython can help. Check out the table below which shows how much speed Cython gave us for different factorial values. We got over 36X speedup with Cython! Follow me on twitter where I post all about the latest and greatest AI, Technology, and Science! Connect with me on LinkedIn too!
[ { "code": null, "e": 233, "s": 172, "text": "Want to be inspired? Come join my Super Quotes newsletter. 😎" }, { "code": null, "e": 381, "s": 233, "text": "Python is a community favourite programming language! It’s by far one of the easiest to use as code is written in an intuitive, human-readable way." }, { "code": null, "e": 516, "s": 381, "text": "Yet you’ll often hear the same complaint about Python over and over again, especially from the C code gurus out there: Python is slow." }, { "code": null, "e": 539, "s": 516, "text": "And they’re not wrong." }, { "code": null, "e": 719, "s": 539, "text": "Relative to many other programming languages, Python is slow. Benchmark game has some solid benchmarks for comparing the speed of various programming languages on different tasks." }, { "code": null, "e": 805, "s": 719, "text": "There’s a couple of different ways to speed things up that I’ve written about before:" }, { "code": null, "e": 865, "s": 805, "text": "(1) Use multi-processing libraries to use all the CPU cores" }, { "code": null, "e": 965, "s": 865, "text": "(2) If you’re using Numpy, Pandas, or Scikit-Learn, use Rapids to accelerate the processing on GPU." }, { "code": null, "e": 1083, "s": 965, "text": "Those are great if what you’re doing can, in fact, be parallelized, such as data pre-processing or matrix operations." }, { "code": null, "e": 1298, "s": 1083, "text": "But what if your code is pure Python? What if you have a big for-loop that you just have to use and can’t put into a matrix because the data has to be processed in sequence? Is there a way to speedup Python itself?" }, { "code": null, "e": 1360, "s": 1298, "text": "That’s where Cython comes in to speed up our raw Python code." }, { "code": null, "e": 1548, "s": 1360, "text": "At its core, Cython is an intermediate step between Python and C/C++. It allows you to write pure Python code with some minor modifications, which is then translated directly into C code." }, { "code": null, "e": 1702, "s": 1548, "text": "The only adjustment you make to your Python code is adding type information to every variable. Normally, we might declare a variable in Python like this:" }, { "code": null, "e": 1710, "s": 1702, "text": "x = 0.5" }, { "code": null, "e": 1767, "s": 1710, "text": "With Cython, we’re going to add a type to that variable:" }, { "code": null, "e": 1786, "s": 1767, "text": "cdef float x = 0.5" }, { "code": null, "e": 2072, "s": 1786, "text": "This tells Cython that our variable is floating point, just like we would do in C. With pure Python, the variable’s type is determined on the fly. The explicit declaration of the type in Cython is what makes the conversion to C possible, since explicit type declarations are required+." }, { "code": null, "e": 2126, "s": 2072, "text": "Installing Cython requires just a single line of pip:" }, { "code": null, "e": 2145, "s": 2126, "text": "pip install cython" }, { "code": null, "e": 2232, "s": 2145, "text": "When using Cython, there are two different sets of types, for variables and functions." }, { "code": null, "e": 2255, "s": 2232, "text": "For variables we have:" }, { "code": null, "e": 2272, "s": 2255, "text": "cdef int a, b, c" }, { "code": null, "e": 2285, "s": 2272, "text": "cdef char *s" }, { "code": null, "e": 2323, "s": 2285, "text": "cdef float x = 0.5 (single precision)" }, { "code": null, "e": 2363, "s": 2323, "text": "cdef double x = 63.4 (double precision)" }, { "code": null, "e": 2379, "s": 2363, "text": "cdef list names" }, { "code": null, "e": 2409, "s": 2379, "text": "cdef dict goals_for_each_play" }, { "code": null, "e": 2431, "s": 2409, "text": "cdef object card_deck" }, { "code": null, "e": 2505, "s": 2431, "text": "Notice how all of these types come from C/C++! For the functions we have:" }, { "code": null, "e": 2560, "s": 2505, "text": "def β€” regular python function, calls from Python only." }, { "code": null, "e": 2668, "s": 2560, "text": "cdef β€” Cython only functions which can’t be accessed from python-only code i.e must be called within Cython" }, { "code": null, "e": 2729, "s": 2668, "text": "cpdef β€” C and Python. Can be accessed from both C and Python" }, { "code": null, "e": 2825, "s": 2729, "text": "With an understanding of Cython types in hand, we can go right ahead and implement our speedup!" }, { "code": null, "e": 2975, "s": 2825, "text": "The first thing we’ll do is set up a Python code benchmark: a for-loop used to compute the factorial of a number. The raw Python code is shown below:" }, { "code": null, "e": 3217, "s": 2975, "text": "Our Cython equivalent of the same function looks very similar. First, we’ll make sure that our Cython code file has a .pyx extension. The only change to the code itself is that we’ve declared the type of each and every variable and function." }, { "code": null, "e": 3464, "s": 3217, "text": "Notice how the function has a cpdef to make sure we can call it from Python. Also see how even our looping variable i has a type. You’ll need to set the type for all of the variables in the function, so that the C compiler knows what type to use!" }, { "code": null, "e": 3541, "s": 3464, "text": "Next, create a setup.py file which will compile the Cython code into C code:" }, { "code": null, "e": 3570, "s": 3541, "text": "And perform the compilation:" }, { "code": null, "e": 3606, "s": 3570, "text": "python setup.py build_ext --inplace" }, { "code": null, "e": 3662, "s": 3606, "text": "Boom! Our C code has been compiled and is ready to use!" }, { "code": null, "e": 3875, "s": 3662, "text": "You’ll see that in the folder where your Cython code is, you have all the files needed to run C code, including the run_cython.c file. If you’re curious, take a look at it to see the C code that Cython generated!" }, { "code": null, "e": 4037, "s": 3875, "text": "Now we’re ready to test out our new, super fast C code! Check out the code below, which implements a speed test to compare the raw Python code to the Cython one." }, { "code": null, "e": 4194, "s": 4037, "text": "The code is very straight forward. We’re importing our files in the same way as regular Python, and running the functions in the same way as regular Python!" }, { "code": null, "e": 4426, "s": 4194, "text": "Cython will get you good speedups on almost any raw Python code, without too much extra effort at all. The key thing to note is that the more loops you’re going through, and the more data you’re crunching, the more Cython can help." }, { "code": null, "e": 4563, "s": 4426, "text": "Check out the table below which shows how much speed Cython gave us for different factorial values. We got over 36X speedup with Cython!" } ]
JUnit - Parameterized Test
JUnit 4 has introduced a new feature called parameterized tests. Parameterized tests allow a developer to run the same test over and over again using different values. There are five steps that you need to follow to create a parameterized test. Annotate test class with @RunWith(Parameterized.class). Annotate test class with @RunWith(Parameterized.class). Create a public static method annotated with @Parameters that returns a Collection of Objects (as Array) as test data set. Create a public static method annotated with @Parameters that returns a Collection of Objects (as Array) as test data set. Create a public constructor that takes in what is equivalent to one "row" of test data. Create a public constructor that takes in what is equivalent to one "row" of test data. Create an instance variable for each "column" of test data. Create an instance variable for each "column" of test data. Create your test case(s) using the instance variables as the source of the test data. Create your test case(s) using the instance variables as the source of the test data. The test case will be invoked once for each row of data. Let us see parameterized tests in action. Create a java class to be tested, say, PrimeNumberChecker.java in C:\>JUNIT_WORKSPACE. public class PrimeNumberChecker { public Boolean validate(final Integer primeNumber) { for (int i = 2; i < (primeNumber / 2); i++) { if (primeNumber % i == 0) { return false; } } return true; } } Create a java test class, say, PrimeNumberCheckerTest.java. Create a java class file named PrimeNumberCheckerTest.java in C:\>JUNIT_WORKSPACE. import java.util.Arrays; import java.util.Collection; import org.junit.Test; import org.junit.Before; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.junit.runner.RunWith; import static org.junit.Assert.assertEquals; @RunWith(Parameterized.class) public class PrimeNumberCheckerTest { private Integer inputNumber; private Boolean expectedResult; private PrimeNumberChecker primeNumberChecker; @Before public void initialize() { primeNumberChecker = new PrimeNumberChecker(); } // Each parameter should be placed as an argument here // Every time runner triggers, it will pass the arguments // from parameters we defined in primeNumbers() method public PrimeNumberCheckerTest(Integer inputNumber, Boolean expectedResult) { this.inputNumber = inputNumber; this.expectedResult = expectedResult; } @Parameterized.Parameters public static Collection primeNumbers() { return Arrays.asList(new Object[][] { { 2, true }, { 6, false }, { 19, true }, { 22, false }, { 23, true } }); } // This test will run 4 times since we have 5 parameters defined @Test public void testPrimeNumberChecker() { System.out.println("Parameterized Number is : " + inputNumber); assertEquals(expectedResult, primeNumberChecker.validate(inputNumber)); } } Create a java class file named TestRunner.java in C:\>JUNIT_WORKSPACE to execute test case(s). import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(PrimeNumberCheckerTest.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Compile the PrimeNumberChecker, PrimeNumberCheckerTest and Test Runner classes using javac. C:\JUNIT_WORKSPACE>javac PrimeNumberChecker.java PrimeNumberCheckerTest.java TestRunner.java Now run the Test Runner, which will run the test cases defined in the provided Test Case class. C:\JUNIT_WORKSPACE>java TestRunner Verify the output. Parameterized Number is : 2 Parameterized Number is : 6 Parameterized Number is : 19 Parameterized Number is : 22 Parameterized Number is : 23 true 24 Lectures 2.5 hours Nishita Bhatt 56 Lectures 7.5 hours Dinesh Varyani Print Add Notes Bookmark this page
[ { "code": null, "e": 2217, "s": 1972, "text": "JUnit 4 has introduced a new feature called parameterized tests. Parameterized tests allow a developer to run the same test over and over again using different values. There are five steps that you need to follow to create a parameterized test." }, { "code": null, "e": 2273, "s": 2217, "text": "Annotate test class with @RunWith(Parameterized.class)." }, { "code": null, "e": 2329, "s": 2273, "text": "Annotate test class with @RunWith(Parameterized.class)." }, { "code": null, "e": 2452, "s": 2329, "text": "Create a public static method annotated with @Parameters that returns a Collection of Objects (as Array) as test data set." }, { "code": null, "e": 2575, "s": 2452, "text": "Create a public static method annotated with @Parameters that returns a Collection of Objects (as Array) as test data set." }, { "code": null, "e": 2663, "s": 2575, "text": "Create a public constructor that takes in what is equivalent to one \"row\" of test data." }, { "code": null, "e": 2751, "s": 2663, "text": "Create a public constructor that takes in what is equivalent to one \"row\" of test data." }, { "code": null, "e": 2811, "s": 2751, "text": "Create an instance variable for each \"column\" of test data." }, { "code": null, "e": 2871, "s": 2811, "text": "Create an instance variable for each \"column\" of test data." }, { "code": null, "e": 2957, "s": 2871, "text": "Create your test case(s) using the instance variables as the source of the test data." }, { "code": null, "e": 3043, "s": 2957, "text": "Create your test case(s) using the instance variables as the source of the test data." }, { "code": null, "e": 3142, "s": 3043, "text": "The test case will be invoked once for each row of data. Let us see parameterized tests in action." }, { "code": null, "e": 3229, "s": 3142, "text": "Create a java class to be tested, say, PrimeNumberChecker.java in C:\\>JUNIT_WORKSPACE." }, { "code": null, "e": 3479, "s": 3229, "text": "public class PrimeNumberChecker {\n public Boolean validate(final Integer primeNumber) {\n for (int i = 2; i < (primeNumber / 2); i++) {\n if (primeNumber % i == 0) {\n return false;\n }\n }\n return true;\n }\n}" }, { "code": null, "e": 3622, "s": 3479, "text": "Create a java test class, say, PrimeNumberCheckerTest.java. Create a java class file named PrimeNumberCheckerTest.java in C:\\>JUNIT_WORKSPACE." }, { "code": null, "e": 5059, "s": 3622, "text": "import java.util.Arrays;\nimport java.util.Collection;\n \nimport org.junit.Test;\nimport org.junit.Before;\n\nimport org.junit.runners.Parameterized;\nimport org.junit.runners.Parameterized.Parameters;\nimport org.junit.runner.RunWith;\nimport static org.junit.Assert.assertEquals;\n\n@RunWith(Parameterized.class)\npublic class PrimeNumberCheckerTest {\n private Integer inputNumber;\n private Boolean expectedResult;\n private PrimeNumberChecker primeNumberChecker;\n\n @Before\n public void initialize() {\n primeNumberChecker = new PrimeNumberChecker();\n }\n\n // Each parameter should be placed as an argument here\n // Every time runner triggers, it will pass the arguments\n // from parameters we defined in primeNumbers() method\n\t\n public PrimeNumberCheckerTest(Integer inputNumber, Boolean expectedResult) {\n this.inputNumber = inputNumber;\n this.expectedResult = expectedResult;\n }\n\n @Parameterized.Parameters\n public static Collection primeNumbers() {\n return Arrays.asList(new Object[][] {\n { 2, true },\n { 6, false },\n { 19, true },\n { 22, false },\n { 23, true }\n });\n }\n\n // This test will run 4 times since we have 5 parameters defined\n @Test\n public void testPrimeNumberChecker() {\n System.out.println(\"Parameterized Number is : \" + inputNumber);\n assertEquals(expectedResult, \n primeNumberChecker.validate(inputNumber));\n }\n}" }, { "code": null, "e": 5154, "s": 5059, "text": "Create a java class file named TestRunner.java in C:\\>JUNIT_WORKSPACE to execute test case(s)." }, { "code": null, "e": 5586, "s": 5154, "text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(PrimeNumberCheckerTest.class);\n\n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n\t\t\n System.out.println(result.wasSuccessful());\n }\n} \t" }, { "code": null, "e": 5678, "s": 5586, "text": "Compile the PrimeNumberChecker, PrimeNumberCheckerTest and Test Runner classes using javac." }, { "code": null, "e": 5772, "s": 5678, "text": "C:\\JUNIT_WORKSPACE>javac PrimeNumberChecker.java PrimeNumberCheckerTest.java\nTestRunner.java\n" }, { "code": null, "e": 5868, "s": 5772, "text": "Now run the Test Runner, which will run the test cases defined in the provided Test Case class." }, { "code": null, "e": 5904, "s": 5868, "text": "C:\\JUNIT_WORKSPACE>java TestRunner\n" }, { "code": null, "e": 5923, "s": 5904, "text": "Verify the output." }, { "code": null, "e": 6072, "s": 5923, "text": "Parameterized Number is : 2\nParameterized Number is : 6\nParameterized Number is : 19\nParameterized Number is : 22\nParameterized Number is : 23\ntrue\n" }, { "code": null, "e": 6107, "s": 6072, "text": "\n 24 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6122, "s": 6107, "text": " Nishita Bhatt" }, { "code": null, "e": 6157, "s": 6122, "text": "\n 56 Lectures \n 7.5 hours \n" }, { "code": null, "e": 6173, "s": 6157, "text": " Dinesh Varyani" }, { "code": null, "e": 6180, "s": 6173, "text": " Print" }, { "code": null, "e": 6191, "s": 6180, "text": " Add Notes" } ]
DynamoDB - Access Control
DynamoDB uses credentials you provide to authenticate requests. These credentials are required and must include permissions for AWS resource access. These permissions span virtually every aspect of DynamoDB down to the minor features of an operation or functionality. In this section, we will discuss regarding the various permissions and resource access in DynamoDB. On signup, you provided a password and email, which serve as root credentials. DynamoDB associates this data with your AWS account, and uses it to give complete access to all resources. AWS recommends you use your root credentials only for the creation of an administration account. This allows you to create IAM accounts/users with less privileges. IAM users are other accounts spawned with the IAM service. Their access permissions/privileges include access to secure pages and certain custom permissions like table modification. The access keys provide another option for additional accounts and access. Use them to grant access, and also to avoid manual granting of access in certain situations. Federated users provide yet another option by allowing access through an identity provider. AWS resources remain under ownership of an account. Permissions policies govern the permissions granted to spawn or access resources. Administrators associate permissions policies with IAM identities, meaning roles, groups, users, and services. They also attach permissions to resources. Permissions specify users, resources, and actions. Note administrators are merely accounts with administrator privileges. Tables remain the main resources in DynamoDB. Subresources serve as additional resources, e.g., streams and indices. These resources use unique names, some of which are mentioned in the following table βˆ’ A resource owner is defined as an AWS account which spawned the resource, or principal entity account responsible for request authentication in resource creation. Consider how this functions within the DynamoDB environment βˆ’ In using root credentials to create a table, your account remains resource owner. In using root credentials to create a table, your account remains resource owner. In creating an IAM user and granting the user permission to create a table, your account remains the resource owner. In creating an IAM user and granting the user permission to create a table, your account remains the resource owner. In creating an IAM user and granting the user, and anyone capable of assuming the role, permission to create a table, your account remains the resource owner. In creating an IAM user and granting the user, and anyone capable of assuming the role, permission to create a table, your account remains the resource owner. Management of access mainly requires attention to a permissions policy describing users and resource access. You associate policies with IAM identities or resources. However, DynamoDB only supports IAM/identity policies. Identity-based (IAM) policies allow you to grant privileges in the following ways βˆ’ Attach permissions to users or groups. Attach permissions to roles for cross-account permissions. Other AWS allow resource-based policies. These policies permit access to things like an S3 bucket. Policies define actions, effects, resources, and principals; and grant permission to perform these operations. Note βˆ’ The API operations may require permissions for multiple actions. Take a closer look at the following policy elements βˆ’ Resource βˆ’ An ARN identifies this. Resource βˆ’ An ARN identifies this. Action βˆ’ Keywords identify these resource operations, and whether to allow or deny. Action βˆ’ Keywords identify these resource operations, and whether to allow or deny. Effect βˆ’ It specifies the effect for a user request for an action, meaning allow or deny with denial as the default. Effect βˆ’ It specifies the effect for a user request for an action, meaning allow or deny with denial as the default. Principal βˆ’ This identifies the user attached to the policy. Principal βˆ’ This identifies the user attached to the policy. In granting permissions, you can specify conditions for when policies become active such as on a particular date. Express conditions with condition keys, which include AWS systemwide keys and DynamoDB keys. These keys are discussed in detail later in the tutorial. A user requires certain basic permissions to use the console. They also require permissions for the console in other standard services βˆ’ CloudWatch Data Pipeline Identity and Access Management Notification Service Lambda If the IAM policy proves too limited, the user cannot use the console effectively. Also, you do not need to worry about user permissions for those only calling the CLI or API. AWS covers common operations in permissions with standalone IAM managed policies. They provide key permissions allowing you to avoid deep investigations into what you must grant. Some of them are as follows βˆ’ AmazonDynamoDBReadOnlyAccess βˆ’ It gives read-only access via the console. AmazonDynamoDBReadOnlyAccess βˆ’ It gives read-only access via the console. AmazonDynamoDBFullAccess βˆ’ It gives full access via the console. AmazonDynamoDBFullAccess βˆ’ It gives full access via the console. AmazonDynamoDBFullAccesswithDataPipeline βˆ’ It gives full access via the console and permits export/import with Data Pipeline. AmazonDynamoDBFullAccesswithDataPipeline βˆ’ It gives full access via the console and permits export/import with Data Pipeline. You can also ofcourse make custom policies. You can grant permissions with the Javascript shell. The following program shows a typical permissions policy βˆ’ { "Version": "2016-05-22", "Statement": [ { "Sid": "DescribeQueryScanToolsTable", "Effect": "Deny", "Action": [ "dynamodb:DescribeTable", "dynamodb:Query", "dynamodb:Scan" ], "Resource": "arn:aws:dynamodb:us-west-2:account-id:table/Tools" } ] } You can review the three examples which are as follows βˆ’ Block the user from executing any table action. { "Version": "2016-05-23", "Statement": [ { "Sid": "AllAPIActionsOnTools", "Effect": "Deny", "Action": "dynamodb:*", "Resource": "arn:aws:dynamodb:us-west-2:155556789012:table/Tools" } ] } Block access to a table and its indices. { "Version": "2016-05-23", "Statement": [ { "Sid": "AccessAllIndexesOnTools", "Effect": "Deny", "Action": [ "dynamodb:*" ], "Resource": [ "arn:aws:dynamodb:us-west-2:155556789012:table/Tools", "arn:aws:dynamodb:us-west-2:155556789012:table/Tools/index/*" ] } ] } Block a user from making a reserved capacity offering purchase. { "Version": "2016-05-23", "Statement": [ { "Sid": "BlockReservedCapacityPurchases", "Effect": "Deny", "Action": "dynamodb:PurchaseReservedCapacityOfferings", "Resource": "arn:aws:dynamodb:us-west-2:155556789012:*" } ] } You can also use the GUI console to create IAM policies. To begin with, choose Tables from the navigation pane. In the table list, choose the target table and follow these steps. Step 1 βˆ’ Select the Access control tab. Step 2 βˆ’ Select the identity provider, actions, and policy attributes. Select Create policy after entering all settings. Step 3 βˆ’ Choose Attach policy instructions, and complete each required step to associate the policy with the appropriate IAM role. 16 Lectures 1.5 hours Harshit Srivastava 49 Lectures 3.5 hours Niyazi Erdogan 48 Lectures 3 hours Niyazi Erdogan 13 Lectures 1 hours Harshit Srivastava 45 Lectures 4 hours Pranjal Srivastava, Harshit Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2659, "s": 2391, "text": "DynamoDB uses credentials you provide to authenticate requests. These credentials are required and must include permissions for AWS resource access. These permissions span virtually every aspect of DynamoDB down to the minor features of an operation or functionality." }, { "code": null, "e": 2759, "s": 2659, "text": "In this section, we will discuss regarding the various permissions and resource access in DynamoDB." }, { "code": null, "e": 2945, "s": 2759, "text": "On signup, you provided a password and email, which serve as root credentials. DynamoDB associates this data with your AWS account, and uses it to give complete access to all resources." }, { "code": null, "e": 3291, "s": 2945, "text": "AWS recommends you use your root credentials only for the creation of an administration account. This allows you to create IAM accounts/users with less privileges. IAM users are other accounts spawned with the IAM service. Their access permissions/privileges include access to secure pages and certain custom permissions like table modification." }, { "code": null, "e": 3551, "s": 3291, "text": "The access keys provide another option for additional accounts and access. Use them to grant access, and also to avoid manual granting of access in certain situations. Federated users provide yet another option by allowing access through an identity provider." }, { "code": null, "e": 3839, "s": 3551, "text": "AWS resources remain under ownership of an account. Permissions policies govern the permissions granted to spawn or access resources. Administrators associate permissions policies with IAM identities, meaning roles, groups, users, and services. They also attach permissions to resources." }, { "code": null, "e": 3961, "s": 3839, "text": "Permissions specify users, resources, and actions. Note administrators are merely accounts with administrator privileges." }, { "code": null, "e": 4165, "s": 3961, "text": "Tables remain the main resources in DynamoDB. Subresources serve as additional resources, e.g., streams and indices. These resources use unique names, some of which are mentioned in the following table βˆ’" }, { "code": null, "e": 4390, "s": 4165, "text": "A resource owner is defined as an AWS account which spawned the resource, or principal entity account responsible for request authentication in resource creation. Consider how this functions within the DynamoDB environment βˆ’" }, { "code": null, "e": 4472, "s": 4390, "text": "In using root credentials to create a table, your account remains resource owner." }, { "code": null, "e": 4554, "s": 4472, "text": "In using root credentials to create a table, your account remains resource owner." }, { "code": null, "e": 4671, "s": 4554, "text": "In creating an IAM user and granting the user permission to create a table, your account remains the resource owner." }, { "code": null, "e": 4788, "s": 4671, "text": "In creating an IAM user and granting the user permission to create a table, your account remains the resource owner." }, { "code": null, "e": 4947, "s": 4788, "text": "In creating an IAM user and granting the user, and anyone capable of assuming the role, permission to create a table, your account remains the resource owner." }, { "code": null, "e": 5106, "s": 4947, "text": "In creating an IAM user and granting the user, and anyone capable of assuming the role, permission to create a table, your account remains the resource owner." }, { "code": null, "e": 5327, "s": 5106, "text": "Management of access mainly requires attention to a permissions policy describing users and resource access. You associate policies with IAM identities or resources. However, DynamoDB only supports IAM/identity policies." }, { "code": null, "e": 5411, "s": 5327, "text": "Identity-based (IAM) policies allow you to grant privileges in the following ways βˆ’" }, { "code": null, "e": 5450, "s": 5411, "text": "Attach permissions to users or groups." }, { "code": null, "e": 5509, "s": 5450, "text": "Attach permissions to roles for cross-account permissions." }, { "code": null, "e": 5608, "s": 5509, "text": "Other AWS allow resource-based policies. These policies permit access to things like an S3 bucket." }, { "code": null, "e": 5719, "s": 5608, "text": "Policies define actions, effects, resources, and principals; and grant permission to perform these operations." }, { "code": null, "e": 5791, "s": 5719, "text": "Note βˆ’ The API operations may require permissions for multiple actions." }, { "code": null, "e": 5845, "s": 5791, "text": "Take a closer look at the following policy elements βˆ’" }, { "code": null, "e": 5880, "s": 5845, "text": "Resource βˆ’ An ARN identifies this." }, { "code": null, "e": 5915, "s": 5880, "text": "Resource βˆ’ An ARN identifies this." }, { "code": null, "e": 5999, "s": 5915, "text": "Action βˆ’ Keywords identify these resource operations, and whether to allow or deny." }, { "code": null, "e": 6083, "s": 5999, "text": "Action βˆ’ Keywords identify these resource operations, and whether to allow or deny." }, { "code": null, "e": 6200, "s": 6083, "text": "Effect βˆ’ It specifies the effect for a user request for an action, meaning allow or deny with denial as the default." }, { "code": null, "e": 6317, "s": 6200, "text": "Effect βˆ’ It specifies the effect for a user request for an action, meaning allow or deny with denial as the default." }, { "code": null, "e": 6378, "s": 6317, "text": "Principal βˆ’ This identifies the user attached to the policy." }, { "code": null, "e": 6439, "s": 6378, "text": "Principal βˆ’ This identifies the user attached to the policy." }, { "code": null, "e": 6704, "s": 6439, "text": "In granting permissions, you can specify conditions for when policies become active such as on a particular date. Express conditions with condition keys, which include AWS systemwide keys and DynamoDB keys. These keys are discussed in detail later in the tutorial." }, { "code": null, "e": 6841, "s": 6704, "text": "A user requires certain basic permissions to use the console. They also require permissions for the console in other standard services βˆ’" }, { "code": null, "e": 6852, "s": 6841, "text": "CloudWatch" }, { "code": null, "e": 6866, "s": 6852, "text": "Data Pipeline" }, { "code": null, "e": 6897, "s": 6866, "text": "Identity and Access Management" }, { "code": null, "e": 6918, "s": 6897, "text": "Notification Service" }, { "code": null, "e": 6925, "s": 6918, "text": "Lambda" }, { "code": null, "e": 7101, "s": 6925, "text": "If the IAM policy proves too limited, the user cannot use the console effectively. Also, you do not need to worry about user permissions for those only calling the CLI or API." }, { "code": null, "e": 7280, "s": 7101, "text": "AWS covers common operations in permissions with standalone IAM managed policies. They provide key permissions allowing you to avoid deep investigations into what you must grant." }, { "code": null, "e": 7310, "s": 7280, "text": "Some of them are as follows βˆ’" }, { "code": null, "e": 7384, "s": 7310, "text": "AmazonDynamoDBReadOnlyAccess βˆ’ It gives read-only access via the console." }, { "code": null, "e": 7458, "s": 7384, "text": "AmazonDynamoDBReadOnlyAccess βˆ’ It gives read-only access via the console." }, { "code": null, "e": 7523, "s": 7458, "text": "AmazonDynamoDBFullAccess βˆ’ It gives full access via the console." }, { "code": null, "e": 7588, "s": 7523, "text": "AmazonDynamoDBFullAccess βˆ’ It gives full access via the console." }, { "code": null, "e": 7714, "s": 7588, "text": "AmazonDynamoDBFullAccesswithDataPipeline βˆ’ It gives full access via the console and permits export/import with Data Pipeline." }, { "code": null, "e": 7840, "s": 7714, "text": "AmazonDynamoDBFullAccesswithDataPipeline βˆ’ It gives full access via the console and permits export/import with Data Pipeline." }, { "code": null, "e": 7884, "s": 7840, "text": "You can also ofcourse make custom policies." }, { "code": null, "e": 7996, "s": 7884, "text": "You can grant permissions with the Javascript shell. The following program shows a typical permissions policy βˆ’" }, { "code": null, "e": 8367, "s": 7996, "text": "{ \n \"Version\": \"2016-05-22\", \n \"Statement\": [ \n { \n \"Sid\": \"DescribeQueryScanToolsTable\", \n \"Effect\": \"Deny\", \n \n \"Action\": [ \n \"dynamodb:DescribeTable\", \n \"dynamodb:Query\", \n \"dynamodb:Scan\" \n ], \n \"Resource\": \"arn:aws:dynamodb:us-west-2:account-id:table/Tools\" \n } \n ] \n}" }, { "code": null, "e": 8424, "s": 8367, "text": "You can review the three examples which are as follows βˆ’" }, { "code": null, "e": 8472, "s": 8424, "text": "Block the user from executing any table action." }, { "code": null, "e": 8728, "s": 8472, "text": "{ \n \"Version\": \"2016-05-23\", \n \"Statement\": [ \n { \n \"Sid\": \"AllAPIActionsOnTools\", \n \"Effect\": \"Deny\", \n \"Action\": \"dynamodb:*\", \n \"Resource\": \"arn:aws:dynamodb:us-west-2:155556789012:table/Tools\" \n } \n ] \n}" }, { "code": null, "e": 8769, "s": 8728, "text": "Block access to a table and its indices." }, { "code": null, "e": 9157, "s": 8769, "text": "{ \n \"Version\": \"2016-05-23\", \n \"Statement\": [ \n { \n \"Sid\": \"AccessAllIndexesOnTools\", \n \"Effect\": \"Deny\", \n \"Action\": [\n \"dynamodb:*\" \n ], \n \"Resource\": [ \n \"arn:aws:dynamodb:us-west-2:155556789012:table/Tools\", \n \"arn:aws:dynamodb:us-west-2:155556789012:table/Tools/index/*\" \n ] \n } \n ] \n}" }, { "code": null, "e": 9221, "s": 9157, "text": "Block a user from making a reserved capacity offering purchase." }, { "code": null, "e": 9509, "s": 9221, "text": "{ \n \"Version\": \"2016-05-23\", \n \"Statement\": [ \n { \n \"Sid\": \"BlockReservedCapacityPurchases\", \n \"Effect\": \"Deny\", \n \"Action\": \"dynamodb:PurchaseReservedCapacityOfferings\", \n \"Resource\": \"arn:aws:dynamodb:us-west-2:155556789012:*\" \n } \n ] \n}" }, { "code": null, "e": 9688, "s": 9509, "text": "You can also use the GUI console to create IAM policies. To begin with, choose Tables from the navigation pane. In the table list, choose the target table and follow these steps." }, { "code": null, "e": 9728, "s": 9688, "text": "Step 1 βˆ’ Select the Access control tab." }, { "code": null, "e": 9849, "s": 9728, "text": "Step 2 βˆ’ Select the identity provider, actions, and policy attributes. Select Create policy after entering all settings." }, { "code": null, "e": 9980, "s": 9849, "text": "Step 3 βˆ’ Choose Attach policy instructions, and complete each required step to associate the policy with the appropriate IAM role." }, { "code": null, "e": 10015, "s": 9980, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 10035, "s": 10015, "text": " Harshit Srivastava" }, { "code": null, "e": 10070, "s": 10035, "text": "\n 49 Lectures \n 3.5 hours \n" }, { "code": null, "e": 10086, "s": 10070, "text": " Niyazi Erdogan" }, { "code": null, "e": 10119, "s": 10086, "text": "\n 48 Lectures \n 3 hours \n" }, { "code": null, "e": 10135, "s": 10119, "text": " Niyazi Erdogan" }, { "code": null, "e": 10168, "s": 10135, "text": "\n 13 Lectures \n 1 hours \n" }, { "code": null, "e": 10188, "s": 10168, "text": " Harshit Srivastava" }, { "code": null, "e": 10221, "s": 10188, "text": "\n 45 Lectures \n 4 hours \n" }, { "code": null, "e": 10261, "s": 10221, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 10268, "s": 10261, "text": " Print" }, { "code": null, "e": 10279, "s": 10268, "text": " Add Notes" } ]
Extract Content from Java Class File
How to extract content from a java .class file using java. Following is the program to extract content from a java .class file using java. import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.tika.exception.TikaException; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.ParseContext; import org.apache.tika.parser.asm.ClassParser; import org.apache.tika.sax.BodyContentHandler; import org.xml.sax.SAXException; public class ExtractContentFromJavaClass { public static void main(String[] args) throws IOException,SAXException, TikaException { //detecting the file type BodyContentHandler handler = new BodyContentHandler(); Metadata metadata = new Metadata(); FileInputStream inputstream = new FileInputStream(new File( "C:/tika/classFileExample.class")); ParseContext pcontext = new ParseContext(); //Html parser ClassParser ClassParser = new ClassParser(); ClassParser.parse(inputstream, handler, metadata,pcontext); System.out.println("Contents of the document:" + handler.toString()); System.out.println("Metadata of the document:"); String[] metadataNames = metadata.names(); for(String name : metadataNames) { System.out.println(name + " : " + metadata.get(name)); } } } Contents of the document:public synchronized class ClassFileExample { public void ClassFileExample(); public static void main(String[]); } Metadata of the document: dc:title : ClassFileExample resourceName : ClassFileExample.class title : ClassFileExample Print Add Notes Bookmark this page
[ { "code": null, "e": 2127, "s": 2068, "text": "How to extract content from a java .class file using java." }, { "code": null, "e": 2207, "s": 2127, "text": "Following is the program to extract content from a java .class file using java." }, { "code": null, "e": 3451, "s": 2207, "text": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\n\nimport org.apache.tika.exception.TikaException;\nimport org.apache.tika.metadata.Metadata;\nimport org.apache.tika.parser.ParseContext;\nimport org.apache.tika.parser.asm.ClassParser;\nimport org.apache.tika.sax.BodyContentHandler;\nimport org.xml.sax.SAXException;\n\npublic class ExtractContentFromJavaClass {\n public static void main(String[] args) throws IOException,SAXException, TikaException {\n \n //detecting the file type\n BodyContentHandler handler = new BodyContentHandler();\n \n Metadata metadata = new Metadata();\n FileInputStream inputstream = new FileInputStream(new File(\n \"C:/tika/classFileExample.class\"));\n ParseContext pcontext = new ParseContext();\n \n //Html parser\n ClassParser ClassParser = new ClassParser();\n \n ClassParser.parse(inputstream, handler, metadata,pcontext);\n System.out.println(\"Contents of the document:\" + handler.toString());\n System.out.println(\"Metadata of the document:\");\n String[] metadataNames = metadata.names();\n\n for(String name : metadataNames) {\n System.out.println(name + \" : \" + metadata.get(name)); \n }\n }\n}" }, { "code": null, "e": 3727, "s": 3451, "text": "Contents of the document:public synchronized class ClassFileExample { \n public void ClassFileExample(); \n public static void main(String[]); \n} \n\nMetadata of the document: \ndc:title : ClassFileExample \nresourceName : ClassFileExample.class \ntitle : ClassFileExample\n" }, { "code": null, "e": 3734, "s": 3727, "text": " Print" }, { "code": null, "e": 3745, "s": 3734, "text": " Add Notes" } ]
Check if a string can be repeated to make another string - GeeksforGeeks
13 May, 2021 Given two strings a and b, the task is to check how many times the string a can be repeated to generate the string b. If b cannot be generated by repeating a then print -1.Examples: Input: a = β€œgeeks”, b = β€œgeeksgeeks” Output: 2 β€œgeeks” can be repeated twice to generate β€œgeeksgeeks”Input: a = β€œdf”, b = β€œdfgrt” Output: -1 Approach: If len(b) % len(a) != 0 then print -1 as b cannot be generated by repeating a. Else set count = len(b) / len(a) and repeat a count number of times. If a = b then print count.Else print -1. If a = b then print count. Else print -1. Below is the implementation of the above approach: C++ Java Python 3 C# PHP Javascript // CPP implementation of the approach#include<bits/stdc++.h>using namespace std; // Function to return the count of repetitions// of string a to generate string bint getCount(string a, string b){ // If b cannot be generated by repeating a if(b.length() % a.length() != 0) return -1; int count = b.length() /a.length(); // Repeat a count number of times string str = ""; for(int i = 0; i < count; i++) { str = str + a; } if(str == b) return count; return -1;} // Driver codeint main(){ string a = "geeks"; string b = "geeksgeeks"; cout << (getCount(a, b)); return 0;} // This code is contributed by// Surendra_Gangwar // Java implementation of the approach class GfG{ // Function to return the count of repetitions // of string a to generate string b static int getCount(String a, String b) { // If b cannot be generated by repeating a if(b.length() % a.length() != 0) return -1; int count = b.length() / a.length(); // Repeat a count number of times String str = ""; for(int i = 0; i < count; i++) { str = str + a; } if(str.equals(b)) return count; return -1; } // Driver code public static void main(String []args) { String a = "geeks"; String b = "geeksgeeks"; System.out.println(getCount(a, b)); }} // This code is contributed by Rituraj Jain # Python3 implementation of the approach # Function to return the count of repetitions# of string a to generate string bdef getCount(a, b): # If b cannot be generated by repeating a if(len(b) % len(a) != 0): return -1; count = int(len(b) / len(a)) # Repeat a count number of times a = a * count if(a == b): return count return -1; # Driver codeif __name__ == '__main__': a = 'geeks' b = 'geeksgeeks' print(getCount(a, b)) // C# implementation of the approachusing System; class GfG{ // Function to return the count of repetitions // of string a to generate string b static int getCount(String a, String b) { // If b cannot be generated by repeating a if(b.Length % a.Length != 0) return -1; int count = b.Length / a.Length; // Repeat a count number of times String str = ""; for(int i = 0; i < count; i++) { str = str + a; } if(str.Equals(b)) return count; return -1; } // Driver code public static void Main(String []args) { String a = "geeks"; String b = "geeksgeeks"; Console.WriteLine(getCount(a, b)); }} // This code contributed by Rajput-Ji <?php// PHP implementation of the approach // Function to return the count of repetitions// of string a to generate string bfunction getCount($a, $b){ // If b cannot be generated by repeating a if(strlen($b) % strlen($a) != 0) return -1; $count = floor(strlen($b) / strlen($a)); // Repeat a count number of times // Repeat a count number of times $str = ""; for($i = 0; $i < $count; $i++) { $str = $str . $a ; } if(strcmp($a,$b)) return $count; return -1;} // Driver code$a = 'geeks';$b = 'geeksgeeks';echo getCount($a, $b); // This code is contributed by Ryuga?> <script> // Javascript implementation of the approach // Function to return the count of repetitions // of string a to generate string b function getCount( a, b) { // If b cannot be generated by repeating a if (b.length % a.length != 0) return -1; var count = parseInt(b.length / a.length); // Repeat a count number of times var str = ""; for (i = 0; i < count; i++) { str = str + a; } if (str == (b)) return count; return -1; } // Driver code var a = "geeks"; var b = "geeksgeeks"; document.write(getCount(a, b)); // This code is contributed by todaysgaurav </script> 2 SURENDRA_GANGWAR ankthon rituraj_jain Rajput-Ji todaysgaurav Pattern Searching Python Programs Strings Strings Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Minimize number of cuts required to break N length stick into N unit length sticks How to validate HTML tag using Regular Expression How to validate GUID (Globally Unique Identifier) using Regular Expression Check whether two strings contain same characters in same order How to check Aadhaar number is valid or not using Regular Expression Python program to convert a list to string Defaultdict in Python Python | Split string into list of characters Python | Get dictionary keys as a list Python | Convert a list to dictionary
[ { "code": null, "e": 25408, "s": 25380, "text": "\n13 May, 2021" }, { "code": null, "e": 25592, "s": 25408, "text": "Given two strings a and b, the task is to check how many times the string a can be repeated to generate the string b. If b cannot be generated by repeating a then print -1.Examples: " }, { "code": null, "e": 25735, "s": 25592, "text": "Input: a = β€œgeeks”, b = β€œgeeksgeeks” Output: 2 β€œgeeks” can be repeated twice to generate β€œgeeksgeeks”Input: a = β€œdf”, b = β€œdfgrt” Output: -1 " }, { "code": null, "e": 25749, "s": 25737, "text": "Approach: " }, { "code": null, "e": 25828, "s": 25749, "text": "If len(b) % len(a) != 0 then print -1 as b cannot be generated by repeating a." }, { "code": null, "e": 25938, "s": 25828, "text": "Else set count = len(b) / len(a) and repeat a count number of times. If a = b then print count.Else print -1." }, { "code": null, "e": 25965, "s": 25938, "text": "If a = b then print count." }, { "code": null, "e": 25980, "s": 25965, "text": "Else print -1." }, { "code": null, "e": 26033, "s": 25980, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26037, "s": 26033, "text": "C++" }, { "code": null, "e": 26042, "s": 26037, "text": "Java" }, { "code": null, "e": 26051, "s": 26042, "text": "Python 3" }, { "code": null, "e": 26054, "s": 26051, "text": "C#" }, { "code": null, "e": 26058, "s": 26054, "text": "PHP" }, { "code": null, "e": 26069, "s": 26058, "text": "Javascript" }, { "code": "// CPP implementation of the approach#include<bits/stdc++.h>using namespace std; // Function to return the count of repetitions// of string a to generate string bint getCount(string a, string b){ // If b cannot be generated by repeating a if(b.length() % a.length() != 0) return -1; int count = b.length() /a.length(); // Repeat a count number of times string str = \"\"; for(int i = 0; i < count; i++) { str = str + a; } if(str == b) return count; return -1;} // Driver codeint main(){ string a = \"geeks\"; string b = \"geeksgeeks\"; cout << (getCount(a, b)); return 0;} // This code is contributed by// Surendra_Gangwar", "e": 26761, "s": 26069, "text": null }, { "code": "// Java implementation of the approach class GfG{ // Function to return the count of repetitions // of string a to generate string b static int getCount(String a, String b) { // If b cannot be generated by repeating a if(b.length() % a.length() != 0) return -1; int count = b.length() / a.length(); // Repeat a count number of times String str = \"\"; for(int i = 0; i < count; i++) { str = str + a; } if(str.equals(b)) return count; return -1; } // Driver code public static void main(String []args) { String a = \"geeks\"; String b = \"geeksgeeks\"; System.out.println(getCount(a, b)); }} // This code is contributed by Rituraj Jain", "e": 27579, "s": 26761, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the count of repetitions# of string a to generate string bdef getCount(a, b): # If b cannot be generated by repeating a if(len(b) % len(a) != 0): return -1; count = int(len(b) / len(a)) # Repeat a count number of times a = a * count if(a == b): return count return -1; # Driver codeif __name__ == '__main__': a = 'geeks' b = 'geeksgeeks' print(getCount(a, b))", "e": 28070, "s": 27579, "text": null }, { "code": "// C# implementation of the approachusing System; class GfG{ // Function to return the count of repetitions // of string a to generate string b static int getCount(String a, String b) { // If b cannot be generated by repeating a if(b.Length % a.Length != 0) return -1; int count = b.Length / a.Length; // Repeat a count number of times String str = \"\"; for(int i = 0; i < count; i++) { str = str + a; } if(str.Equals(b)) return count; return -1; } // Driver code public static void Main(String []args) { String a = \"geeks\"; String b = \"geeksgeeks\"; Console.WriteLine(getCount(a, b)); }} // This code contributed by Rajput-Ji", "e": 28880, "s": 28070, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to return the count of repetitions// of string a to generate string bfunction getCount($a, $b){ // If b cannot be generated by repeating a if(strlen($b) % strlen($a) != 0) return -1; $count = floor(strlen($b) / strlen($a)); // Repeat a count number of times // Repeat a count number of times $str = \"\"; for($i = 0; $i < $count; $i++) { $str = $str . $a ; } if(strcmp($a,$b)) return $count; return -1;} // Driver code$a = 'geeks';$b = 'geeksgeeks';echo getCount($a, $b); // This code is contributed by Ryuga?>", "e": 29523, "s": 28880, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the count of repetitions // of string a to generate string b function getCount( a, b) { // If b cannot be generated by repeating a if (b.length % a.length != 0) return -1; var count = parseInt(b.length / a.length); // Repeat a count number of times var str = \"\"; for (i = 0; i < count; i++) { str = str + a; } if (str == (b)) return count; return -1; } // Driver code var a = \"geeks\"; var b = \"geeksgeeks\"; document.write(getCount(a, b)); // This code is contributed by todaysgaurav </script>", "e": 30237, "s": 29523, "text": null }, { "code": null, "e": 30239, "s": 30237, "text": "2" }, { "code": null, "e": 30258, "s": 30241, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 30266, "s": 30258, "text": "ankthon" }, { "code": null, "e": 30279, "s": 30266, "text": "rituraj_jain" }, { "code": null, "e": 30289, "s": 30279, "text": "Rajput-Ji" }, { "code": null, "e": 30302, "s": 30289, "text": "todaysgaurav" }, { "code": null, "e": 30320, "s": 30302, "text": "Pattern Searching" }, { "code": null, "e": 30336, "s": 30320, "text": "Python Programs" }, { "code": null, "e": 30344, "s": 30336, "text": "Strings" }, { "code": null, "e": 30352, "s": 30344, "text": "Strings" }, { "code": null, "e": 30370, "s": 30352, "text": "Pattern Searching" }, { "code": null, "e": 30468, "s": 30370, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30551, "s": 30468, "text": "Minimize number of cuts required to break N length stick into N unit length sticks" }, { "code": null, "e": 30601, "s": 30551, "text": "How to validate HTML tag using Regular Expression" }, { "code": null, "e": 30676, "s": 30601, "text": "How to validate GUID (Globally Unique Identifier) using Regular Expression" }, { "code": null, "e": 30740, "s": 30676, "text": "Check whether two strings contain same characters in same order" }, { "code": null, "e": 30809, "s": 30740, "text": "How to check Aadhaar number is valid or not using Regular Expression" }, { "code": null, "e": 30852, "s": 30809, "text": "Python program to convert a list to string" }, { "code": null, "e": 30874, "s": 30852, "text": "Defaultdict in Python" }, { "code": null, "e": 30920, "s": 30874, "text": "Python | Split string into list of characters" }, { "code": null, "e": 30959, "s": 30920, "text": "Python | Get dictionary keys as a list" } ]
Classic for Loop Implementation
Following is the classic β€˜for’ statement which is available in most programming languages. for(variable declaration;expression;Increment) { statement #1 statement #2 ... } The Batch Script language does not have a direct β€˜for’ statement which is similar to the above syntax, but one can still do an implementation of the classic β€˜for’ loop statement using if statements and labels. Following is the general flow of the classic β€˜for’ loop statement. Let’s look at the general syntax implementation of the classic for loop in batch scripting. Set counter :label If (expression) exit loop Do_something Increment counter Go back to :label The entire code for the β€˜for’ implementation is placed inside of a label. The entire code for the β€˜for’ implementation is placed inside of a label. The counters variables must be set or initialized before the β€˜for’ loop implementation starts. The counters variables must be set or initialized before the β€˜for’ loop implementation starts. The expression for the β€˜for’ loop is done using the β€˜if’ statement. If the expression evaluates to be true then an exit is executed to come out of the loop. The expression for the β€˜for’ loop is done using the β€˜if’ statement. If the expression evaluates to be true then an exit is executed to come out of the loop. A counter needs to be properly incremented inside of the β€˜if’ statement so that the β€˜for’ implementation can continue if the expression evaluation is false. A counter needs to be properly incremented inside of the β€˜if’ statement so that the β€˜for’ implementation can continue if the expression evaluation is false. Finally, we will go back to our label so that we can evaluate our β€˜if’ statement again. Finally, we will go back to our label so that we can evaluate our β€˜if’ statement again. Following is an example of how to carry out the implementation of the classic β€˜for’ loop statement. @echo off SET /A i = 1 :loop IF %i%==5 GOTO END echo The value of i is %i% SET /a i=%i%+1 GOTO :LOOP :END The above command produces the following output. The value of i is 1 The value of i is 2 The value of i is 3 The value of i is 4 Print Add Notes Bookmark this page
[ { "code": null, "e": 2260, "s": 2169, "text": "Following is the classic β€˜for’ statement which is available in most programming languages." }, { "code": null, "e": 2351, "s": 2260, "text": "for(variable declaration;expression;Increment) {\n statement #1\n statement #2\n ...\n}\n" }, { "code": null, "e": 2561, "s": 2351, "text": "The Batch Script language does not have a direct β€˜for’ statement which is similar to the above syntax, but one can still do an implementation of the classic β€˜for’ loop statement using if statements and labels." }, { "code": null, "e": 2628, "s": 2561, "text": "Following is the general flow of the classic β€˜for’ loop statement." }, { "code": null, "e": 2720, "s": 2628, "text": "Let’s look at the general syntax implementation of the classic for loop in batch scripting." }, { "code": null, "e": 2816, "s": 2720, "text": "Set counter\n:label\n\nIf (expression) exit loop\nDo_something\nIncrement counter\nGo back to :label\n" }, { "code": null, "e": 2890, "s": 2816, "text": "The entire code for the β€˜for’ implementation is placed inside of a label." }, { "code": null, "e": 2964, "s": 2890, "text": "The entire code for the β€˜for’ implementation is placed inside of a label." }, { "code": null, "e": 3059, "s": 2964, "text": "The counters variables must be set or initialized before the β€˜for’ loop implementation starts." }, { "code": null, "e": 3154, "s": 3059, "text": "The counters variables must be set or initialized before the β€˜for’ loop implementation starts." }, { "code": null, "e": 3311, "s": 3154, "text": "The expression for the β€˜for’ loop is done using the β€˜if’ statement. If the expression evaluates to be true then an exit is executed to come out of the loop." }, { "code": null, "e": 3468, "s": 3311, "text": "The expression for the β€˜for’ loop is done using the β€˜if’ statement. If the expression evaluates to be true then an exit is executed to come out of the loop." }, { "code": null, "e": 3625, "s": 3468, "text": "A counter needs to be properly incremented inside of the β€˜if’ statement so that the β€˜for’ implementation can continue if the expression evaluation is false." }, { "code": null, "e": 3782, "s": 3625, "text": "A counter needs to be properly incremented inside of the β€˜if’ statement so that the β€˜for’ implementation can continue if the expression evaluation is false." }, { "code": null, "e": 3870, "s": 3782, "text": "Finally, we will go back to our label so that we can evaluate our β€˜if’ statement again." }, { "code": null, "e": 3958, "s": 3870, "text": "Finally, we will go back to our label so that we can evaluate our β€˜if’ statement again." }, { "code": null, "e": 4058, "s": 3958, "text": "Following is an example of how to carry out the implementation of the classic β€˜for’ loop statement." }, { "code": null, "e": 4172, "s": 4058, "text": "@echo off \nSET /A i = 1 \n:loop \n\nIF %i%==5 GOTO END \necho The value of i is %i% \nSET /a i=%i%+1 \nGOTO :LOOP \n:END" }, { "code": null, "e": 4221, "s": 4172, "text": "The above command produces the following output." }, { "code": null, "e": 4305, "s": 4221, "text": "The value of i is 1 \nThe value of i is 2 \nThe value of i is 3 \nThe value of i is 4\n" }, { "code": null, "e": 4312, "s": 4305, "text": " Print" }, { "code": null, "e": 4323, "s": 4312, "text": " Add Notes" } ]
What is Two-Stream Self-Attention in XLNet | by Xu LIANG | Towards Data Science
In my previous post What is XLNet and why it outperforms BERT, I mainly talked about the difference between XLNet (AR language model) and BERT (AE language model) and the Permutation Language Modeling. I believe that having an intuitive understanding of XLNet is far important than the implementation detail, so I only explained the Permutation Language Modeling and don’t mention another important part, the Two-Stream Self-Attention architecture. But as Jiaming Chen mentioned in the comment, the Two-Stream Self-Attention is another highlight in the XLNet paper, so I wrote this post to explain the Two-Stream Self-Attention as clearly as possible. The content is structured as follows. A quick review of Permutation Language Modeling What problems the permutation brought? Does BERT have such problem? How XLNet solve the problem? Attention mask: How XLNet implement permutation? Special term: AR language model: autoregressive language model AE language model: autoencoder language model In order to make this post more independent, here I give a brief summary of What is XLNet and why it outperforms BERT. XLNet proposed that using Permutation Language Modeling to make the AR language model learn from bi-directional context. By this way, it can avoid the disadvantages brought by the MASK method in AE language model. The permutation method is to get permutations of a sequence, and using the previous t-1 tokens as the context to predict the t-th position token. For example, we have a sentence[x1, x2, x3, x4]and x3 is the t-th position token that we want to predict. First, we get permutations of the sentence. [('x1', 'x2', 'x3', 'x4'), ('x1', 'x2', 'x4', 'x3'), ('x1', 'x3', 'x2', 'x4'), ('x1', 'x3', 'x4', 'x2'), ('x1', 'x4', 'x2', 'x3'), ('x1', 'x4', 'x3', 'x2'), ('x2', 'x1', 'x3', 'x4'), ('x2', 'x1', 'x4', 'x3'), ('x2', 'x3', 'x1', 'x4'), ('x2', 'x3', 'x4', 'x1'), ('x2', 'x4', 'x1', 'x3'), ('x2', 'x4', 'x3', 'x1'), ('x3', 'x1', 'x2', 'x4'), ('x3', 'x1', 'x4', 'x2'), ('x3', 'x2', 'x1', 'x4'), ('x3', 'x2', 'x4', 'x1'), ('x3', 'x4', 'x1', 'x2'), ('x3', 'x4', 'x2', 'x1'), ('x4', 'x1', 'x2', 'x3'), ('x4', 'x1', 'x3', 'x2'), ('x4', 'x2', 'x1', 'x3'), ('x4', 'x2', 'x3', 'x1'), ('x4', 'x3', 'x1', 'x2'), ('x4', 'x3', 'x2', 'x1')] Then we select some samples as the training data. (In the paper, it randomly selects samples from permutations) ('x1', 'x2', 'x4', 'x3'),('x1', 'x4', 'x3', 'x2'),('x2', 'x3', 'x4', 'x1'),('x4', 'x2', 'x3', 'x1'),('x3', 'x2', 'x4', 'x1'), We can see every token have the chance that appears before x3. So the AR model can learn the bi-directional information from these context tokens. If you are still not clear about permutations, you could read the previous post. The permutation can make AR model see the context from two directions, but it also brought problems that the original transformer cannot solve. Z: a factorization order p_ΞΈ: likelihood function x_zt: the t-th token in the factorization order x_z<t: the tokens before t-th token This is the objective function for permutation language modeling, which means takes t-1 tokens as the context and to predict the t-th token. There are two requirements that a standard Transformer cannot do: to predict the token x_t, the model should only see the position of x_t, not the content of x_t (I will explain what is content in the next section)to predict the token x_t, the model should encode all tokens before x_t as the content to predict the token x_t, the model should only see the position of x_t, not the content of x_t (I will explain what is content in the next section) to predict the token x_t, the model should encode all tokens before x_t as the content Especially the first requirements, transformer incorporate position encoding into the token embedding. So it cannot separate the position information from the token embedding. BERT is an AE language model, it does not need separate position information like the AR language model. Unlike the XLNet need position information to predict t-th token, BERT uses [MASK] to represent which token to predict (we can think [MASK] is just a placeholder). For example, if BERT use x2, x1 and x4 to predict x3, the embedding of x2, x1, x4 contains the position information and other information related to [MASK]. So the model has a high chance to predict that [MASK] is x3. Here I will give a more detail explanation about information. BERT embedding(information learned by BERT) contains two kinds of information, the position information, and the content information (I just split it into two parts for simplicity). The position information is easy to understand that it tells the model the position of the current token. The content information (semantics and syntactic) contains the β€œmeaning” of the current token. An intuitive example you have seen is kind β€” man + woman = queen . XLNet proposes Two-Stream Self-Attention to solve the problem. As the name indicates, it contains two kinds of self-attention. One is the content stream attention, which is the standard self-attention in Transformer. Another is the query stream attention. XLNet introduces it to replace the [MASK] token in BERT. For example, if BERT wants to predict x3 with knowledge of the context words x1 and x2, it can use [MASK] to represent the x3 token. The [MASK] is just a placeholder. And the embedding of x1 and x2 contains the position information to help the model to β€œknow” [MASK] is x3. Things are different come to XLNet. One token x3 will server two kinds of roles. When it is used as content to predict other tokens, we can use the content representation (learned by content stream attention) to represent x3. But if we want to predict x3, we should only know its position and not its content. That’s why XLNet uses query representation (learned by query stream attention) to preserve context information before x3 and only the position information of x3. In order to intuitively understand the Two-Stream Self-Attention, we can just think XLNet replace the [MASK] in BERT with query representation. They just choose different approaches to do the same thing. When I first read the paper, I can not stop wondering about the implementation details about permutation during training. So I will talk this a little in case you are interested. In the first part, β€œA quick review of Permutation Language Modeling”, I give an example that permutations of a sentence[x1, x2, x3, x4] will look like below. [('x1', 'x2', 'x3', 'x4'), ('x1', 'x2', 'x4', 'x3'), ('x1', 'x3', 'x2', 'x4'), ('x1', 'x3', 'x4', 'x2'), ('x1', 'x4', 'x2', 'x3'), ('x1', 'x4', 'x3', 'x2'), ('x2', 'x1', 'x3', 'x4'), ('x2', 'x1', 'x4', 'x3'), ('x2', 'x3', 'x1', 'x4'), ('x2', 'x3', 'x4', 'x1'), ('x2', 'x4', 'x1', 'x3'), ('x2', 'x4', 'x3', 'x1'), ('x3', 'x1', 'x2', 'x4'), ('x3', 'x1', 'x4', 'x2'), ('x3', 'x2', 'x1', 'x4'), ('x3', 'x2', 'x4', 'x1'), ('x3', 'x4', 'x1', 'x2'), ('x3', 'x4', 'x2', 'x1'), ('x4', 'x1', 'x2', 'x3'), ('x4', 'x1', 'x3', 'x2'), ('x4', 'x2', 'x1', 'x3'), ('x4', 'x2', 'x3', 'x1'), ('x4', 'x3', 'x1', 'x2'), ('x4', 'x3', 'x2', 'x1')] It is very easy to misunderstand that we need to get the random order of a sentence and input it into the model. But this is not true. The order of input sentence is [x1, x2, x3, x4] , and XLNet use attention mask to permute the factorization order. The original order of the sentence is [x1, x2, x3, x4]. And we randomly get a factorization order as [x3, x2, x4, x1]. The upper left corner is the calculation of content representation. If we want to predict the content representation of x1, we should have all 4 tokens content information. KV = [h1, h2, h3, h4] and Q = h1. The lower-left corner is the calculation of query representation. If we want to predict the query representation of x1, we cannot see the content representation of x1 itself. KV = [h2, h3, h4] and Q = g1. The right corner is the whole calculation process. I explain it from bottom to top. First the h and g are initialized as e(xi) and w. And after the content mask and query mask, the two-stream attention will output the first layer output h^(1) and g^(1) and then calculate the second layer. Notice the right content mask and query mask. Both of them are matrices. In the content mask, the first row has 4 red points. It means that the first token (x1) can see (attend to) all other tokens including itself( x3->x2->x4->x1). The second row has 2 red points. It means that the second token (x2) can see (attend to) two tokens (x3->x2). And so on other rows. The only difference between the content mask and query mask is those diagonal elements in the query mask are 0, which means the tokens cannot see themselves. Let’s sum it up. The input sentence has only one order. But we can use different attention mask to implement different factorization order. In this post, I mainly explained what is the problem that XLNet face and how to use Two-Stream Self-Attention to solve it. I also mention some implement details about attention mask for the permutation. As for the result comparison, you can find the latest post from XLNet team, which do a more fair comparison than the paper does. Check out my other posts on Medium with a categorized view!GitHub: BrambleXuLinkedIn: Xu LiangBlog: BrambleXu paper: https://arxiv.org/abs/1906.08237 implementation: pytorch_transformers/modeling_xlnet.py What is XLNet and why it outperforms BERT Paper Dissected: β€œXLNet: Generalized Autoregressive Pretraining for Language Understanding” Explained, this mainly talked about transformer-xl. A Fair Comparison Study of XLNet and BERT with Large Models
[ { "code": null, "e": 249, "s": 47, "text": "In my previous post What is XLNet and why it outperforms BERT, I mainly talked about the difference between XLNet (AR language model) and BERT (AE language model) and the Permutation Language Modeling." }, { "code": null, "e": 699, "s": 249, "text": "I believe that having an intuitive understanding of XLNet is far important than the implementation detail, so I only explained the Permutation Language Modeling and don’t mention another important part, the Two-Stream Self-Attention architecture. But as Jiaming Chen mentioned in the comment, the Two-Stream Self-Attention is another highlight in the XLNet paper, so I wrote this post to explain the Two-Stream Self-Attention as clearly as possible." }, { "code": null, "e": 737, "s": 699, "text": "The content is structured as follows." }, { "code": null, "e": 785, "s": 737, "text": "A quick review of Permutation Language Modeling" }, { "code": null, "e": 824, "s": 785, "text": "What problems the permutation brought?" }, { "code": null, "e": 853, "s": 824, "text": "Does BERT have such problem?" }, { "code": null, "e": 882, "s": 853, "text": "How XLNet solve the problem?" }, { "code": null, "e": 931, "s": 882, "text": "Attention mask: How XLNet implement permutation?" }, { "code": null, "e": 945, "s": 931, "text": "Special term:" }, { "code": null, "e": 994, "s": 945, "text": "AR language model: autoregressive language model" }, { "code": null, "e": 1040, "s": 994, "text": "AE language model: autoencoder language model" }, { "code": null, "e": 1159, "s": 1040, "text": "In order to make this post more independent, here I give a brief summary of What is XLNet and why it outperforms BERT." }, { "code": null, "e": 1373, "s": 1159, "text": "XLNet proposed that using Permutation Language Modeling to make the AR language model learn from bi-directional context. By this way, it can avoid the disadvantages brought by the MASK method in AE language model." }, { "code": null, "e": 1669, "s": 1373, "text": "The permutation method is to get permutations of a sequence, and using the previous t-1 tokens as the context to predict the t-th position token. For example, we have a sentence[x1, x2, x3, x4]and x3 is the t-th position token that we want to predict. First, we get permutations of the sentence." }, { "code": null, "e": 2294, "s": 1669, "text": "[('x1', 'x2', 'x3', 'x4'), ('x1', 'x2', 'x4', 'x3'), ('x1', 'x3', 'x2', 'x4'), ('x1', 'x3', 'x4', 'x2'), ('x1', 'x4', 'x2', 'x3'), ('x1', 'x4', 'x3', 'x2'), ('x2', 'x1', 'x3', 'x4'), ('x2', 'x1', 'x4', 'x3'), ('x2', 'x3', 'x1', 'x4'), ('x2', 'x3', 'x4', 'x1'), ('x2', 'x4', 'x1', 'x3'), ('x2', 'x4', 'x3', 'x1'), ('x3', 'x1', 'x2', 'x4'), ('x3', 'x1', 'x4', 'x2'), ('x3', 'x2', 'x1', 'x4'), ('x3', 'x2', 'x4', 'x1'), ('x3', 'x4', 'x1', 'x2'), ('x3', 'x4', 'x2', 'x1'), ('x4', 'x1', 'x2', 'x3'), ('x4', 'x1', 'x3', 'x2'), ('x4', 'x2', 'x1', 'x3'), ('x4', 'x2', 'x3', 'x1'), ('x4', 'x3', 'x1', 'x2'), ('x4', 'x3', 'x2', 'x1')]" }, { "code": null, "e": 2406, "s": 2294, "text": "Then we select some samples as the training data. (In the paper, it randomly selects samples from permutations)" }, { "code": null, "e": 2532, "s": 2406, "text": "('x1', 'x2', 'x4', 'x3'),('x1', 'x4', 'x3', 'x2'),('x2', 'x3', 'x4', 'x1'),('x4', 'x2', 'x3', 'x1'),('x3', 'x2', 'x4', 'x1')," }, { "code": null, "e": 2760, "s": 2532, "text": "We can see every token have the chance that appears before x3. So the AR model can learn the bi-directional information from these context tokens. If you are still not clear about permutations, you could read the previous post." }, { "code": null, "e": 2904, "s": 2760, "text": "The permutation can make AR model see the context from two directions, but it also brought problems that the original transformer cannot solve." }, { "code": null, "e": 2929, "s": 2904, "text": "Z: a factorization order" }, { "code": null, "e": 2954, "s": 2929, "text": "p_ΞΈ: likelihood function" }, { "code": null, "e": 3002, "s": 2954, "text": "x_zt: the t-th token in the factorization order" }, { "code": null, "e": 3038, "s": 3002, "text": "x_z<t: the tokens before t-th token" }, { "code": null, "e": 3179, "s": 3038, "text": "This is the objective function for permutation language modeling, which means takes t-1 tokens as the context and to predict the t-th token." }, { "code": null, "e": 3245, "s": 3179, "text": "There are two requirements that a standard Transformer cannot do:" }, { "code": null, "e": 3480, "s": 3245, "text": "to predict the token x_t, the model should only see the position of x_t, not the content of x_t (I will explain what is content in the next section)to predict the token x_t, the model should encode all tokens before x_t as the content" }, { "code": null, "e": 3629, "s": 3480, "text": "to predict the token x_t, the model should only see the position of x_t, not the content of x_t (I will explain what is content in the next section)" }, { "code": null, "e": 3716, "s": 3629, "text": "to predict the token x_t, the model should encode all tokens before x_t as the content" }, { "code": null, "e": 3892, "s": 3716, "text": "Especially the first requirements, transformer incorporate position encoding into the token embedding. So it cannot separate the position information from the token embedding." }, { "code": null, "e": 4379, "s": 3892, "text": "BERT is an AE language model, it does not need separate position information like the AR language model. Unlike the XLNet need position information to predict t-th token, BERT uses [MASK] to represent which token to predict (we can think [MASK] is just a placeholder). For example, if BERT use x2, x1 and x4 to predict x3, the embedding of x2, x1, x4 contains the position information and other information related to [MASK]. So the model has a high chance to predict that [MASK] is x3." }, { "code": null, "e": 4623, "s": 4379, "text": "Here I will give a more detail explanation about information. BERT embedding(information learned by BERT) contains two kinds of information, the position information, and the content information (I just split it into two parts for simplicity)." }, { "code": null, "e": 4891, "s": 4623, "text": "The position information is easy to understand that it tells the model the position of the current token. The content information (semantics and syntactic) contains the β€œmeaning” of the current token. An intuitive example you have seen is kind β€” man + woman = queen ." }, { "code": null, "e": 4954, "s": 4891, "text": "XLNet proposes Two-Stream Self-Attention to solve the problem." }, { "code": null, "e": 5204, "s": 4954, "text": "As the name indicates, it contains two kinds of self-attention. One is the content stream attention, which is the standard self-attention in Transformer. Another is the query stream attention. XLNet introduces it to replace the [MASK] token in BERT." }, { "code": null, "e": 5478, "s": 5204, "text": "For example, if BERT wants to predict x3 with knowledge of the context words x1 and x2, it can use [MASK] to represent the x3 token. The [MASK] is just a placeholder. And the embedding of x1 and x2 contains the position information to help the model to β€œknow” [MASK] is x3." }, { "code": null, "e": 5950, "s": 5478, "text": "Things are different come to XLNet. One token x3 will server two kinds of roles. When it is used as content to predict other tokens, we can use the content representation (learned by content stream attention) to represent x3. But if we want to predict x3, we should only know its position and not its content. That’s why XLNet uses query representation (learned by query stream attention) to preserve context information before x3 and only the position information of x3." }, { "code": null, "e": 6154, "s": 5950, "text": "In order to intuitively understand the Two-Stream Self-Attention, we can just think XLNet replace the [MASK] in BERT with query representation. They just choose different approaches to do the same thing." }, { "code": null, "e": 6333, "s": 6154, "text": "When I first read the paper, I can not stop wondering about the implementation details about permutation during training. So I will talk this a little in case you are interested." }, { "code": null, "e": 6491, "s": 6333, "text": "In the first part, β€œA quick review of Permutation Language Modeling”, I give an example that permutations of a sentence[x1, x2, x3, x4] will look like below." }, { "code": null, "e": 7116, "s": 6491, "text": "[('x1', 'x2', 'x3', 'x4'), ('x1', 'x2', 'x4', 'x3'), ('x1', 'x3', 'x2', 'x4'), ('x1', 'x3', 'x4', 'x2'), ('x1', 'x4', 'x2', 'x3'), ('x1', 'x4', 'x3', 'x2'), ('x2', 'x1', 'x3', 'x4'), ('x2', 'x1', 'x4', 'x3'), ('x2', 'x3', 'x1', 'x4'), ('x2', 'x3', 'x4', 'x1'), ('x2', 'x4', 'x1', 'x3'), ('x2', 'x4', 'x3', 'x1'), ('x3', 'x1', 'x2', 'x4'), ('x3', 'x1', 'x4', 'x2'), ('x3', 'x2', 'x1', 'x4'), ('x3', 'x2', 'x4', 'x1'), ('x3', 'x4', 'x1', 'x2'), ('x3', 'x4', 'x2', 'x1'), ('x4', 'x1', 'x2', 'x3'), ('x4', 'x1', 'x3', 'x2'), ('x4', 'x2', 'x1', 'x3'), ('x4', 'x2', 'x3', 'x1'), ('x4', 'x3', 'x1', 'x2'), ('x4', 'x3', 'x2', 'x1')]" }, { "code": null, "e": 7366, "s": 7116, "text": "It is very easy to misunderstand that we need to get the random order of a sentence and input it into the model. But this is not true. The order of input sentence is [x1, x2, x3, x4] , and XLNet use attention mask to permute the factorization order." }, { "code": null, "e": 7485, "s": 7366, "text": "The original order of the sentence is [x1, x2, x3, x4]. And we randomly get a factorization order as [x3, x2, x4, x1]." }, { "code": null, "e": 7692, "s": 7485, "text": "The upper left corner is the calculation of content representation. If we want to predict the content representation of x1, we should have all 4 tokens content information. KV = [h1, h2, h3, h4] and Q = h1." }, { "code": null, "e": 7897, "s": 7692, "text": "The lower-left corner is the calculation of query representation. If we want to predict the query representation of x1, we cannot see the content representation of x1 itself. KV = [h2, h3, h4] and Q = g1." }, { "code": null, "e": 8187, "s": 7897, "text": "The right corner is the whole calculation process. I explain it from bottom to top. First the h and g are initialized as e(xi) and w. And after the content mask and query mask, the two-stream attention will output the first layer output h^(1) and g^(1) and then calculate the second layer." }, { "code": null, "e": 8552, "s": 8187, "text": "Notice the right content mask and query mask. Both of them are matrices. In the content mask, the first row has 4 red points. It means that the first token (x1) can see (attend to) all other tokens including itself( x3->x2->x4->x1). The second row has 2 red points. It means that the second token (x2) can see (attend to) two tokens (x3->x2). And so on other rows." }, { "code": null, "e": 8710, "s": 8552, "text": "The only difference between the content mask and query mask is those diagonal elements in the query mask are 0, which means the tokens cannot see themselves." }, { "code": null, "e": 8850, "s": 8710, "text": "Let’s sum it up. The input sentence has only one order. But we can use different attention mask to implement different factorization order." }, { "code": null, "e": 9182, "s": 8850, "text": "In this post, I mainly explained what is the problem that XLNet face and how to use Two-Stream Self-Attention to solve it. I also mention some implement details about attention mask for the permutation. As for the result comparison, you can find the latest post from XLNet team, which do a more fair comparison than the paper does." }, { "code": null, "e": 9292, "s": 9182, "text": "Check out my other posts on Medium with a categorized view!GitHub: BrambleXuLinkedIn: Xu LiangBlog: BrambleXu" }, { "code": null, "e": 9332, "s": 9292, "text": "paper: https://arxiv.org/abs/1906.08237" }, { "code": null, "e": 9387, "s": 9332, "text": "implementation: pytorch_transformers/modeling_xlnet.py" }, { "code": null, "e": 9429, "s": 9387, "text": "What is XLNet and why it outperforms BERT" }, { "code": null, "e": 9573, "s": 9429, "text": "Paper Dissected: β€œXLNet: Generalized Autoregressive Pretraining for Language Understanding” Explained, this mainly talked about transformer-xl." } ]
Equilibrium Point | Practice | GeeksforGeeks
Given an array A of n positive numbers. The task is to find the first Equilibium Point in the array. Equilibrium Point in an array is a position such that the sum of elements before it is equal to the sum of elements after it. Note: Retun the index of Equilibrium point. (1-based index) Example 1: Input: n = 5 A[] = {1,3,5,2,2} Output: 3 Explanation: For second test case equilibrium point is at position 3 as elements before it (1+3) = elements after it (2+2). Example 2: Input: n = 1 A[] = {1} Output: 1 Explanation: Since its the only element hence its the only equilibrium point. Your Task: The task is to complete the function equilibriumPoint() which takes the array and n as input parameters and returns the point of equilibrium. Return -1 if no such point exists. Expected Time Complexity: O(n) Expected Auxiliary Space: O(1) Constraints: 1 <= n <= 106 1 <= A[i] <= 108 0 raushanrakesh0691 day ago int low = 0; int high = n-1; while(low<=high){ int mid = low+(high-low)/2; long sum = 0; long sum1 = 0; for(int i=0;i<mid;i++){ sum = sum+arr[i]; } for(int i=mid+1;i<n;i++){ sum1 = sum1+arr[i]; } if(sum==sum1){ return mid+1; }else if(sum<sum1){ low = mid+1; }else{ high = mid-1; } } return -1; 0.72 sec 0 somnathjha0720003 days ago java if(n==1) return 1; long leftsum = 0; long rightsum = 0; for(int i =1;i<n;i++) { rightsum +=arr[i]; } for(int i =1;i<n;i++) { if(rightsum-leftsum==0) return i; else{ leftsum +=arr[i-1]; rightsum -=arr[i]; } } return -1; } 0 dharpranoy22553 days ago java solution: if (n==1){ return 1; } long leftsum=arr[0]; long rightsum=0; for (int i=1;i<n;i++){ rightsum+=arr[i]; } for (int i=1;i<n;i++){ rightsum-=arr[i]; if (leftsum==rightsum){ return i+1; } leftsum+=arr[i]; } return -1; +1 bipulharsh1234 days ago int equilibriumPoint(long long a[], int n) { // Your code here if(n==1) return 1; if(n==2) return -1; int equipt = 1; int lsum = a[0]; int rsum = 0; for(int ind=2; ind<n; ind++) rsum += a[ind]; while(lsum < rsum){ lsum += a[equipt++]; rsum -= a[equipt]; } if(lsum == rsum) return equipt+1; return -1; } 0 mrnecto1 week ago C++ class Solution{ public: // Function to find equilibrium point in the array. // a: input array // n: size of array int equilibriumPoint(long long a[], int n) { // Your code here if(n == 1) return 1; int left = 0, right = 0, i, j; for(i = 0, j = n - 1; i <= j;) { if(i == j && left == right) return i + 1; if(left < right) left += a[i++]; else right += a[j--]; } return -1; } }; 0 shrivastavap6911 week ago cpp sol int equilibriumPoint(long long a[], int n) { long long sum=0; for(int i=0;i<n;i++){ sum+=a[i]; } int s=0; for(int i=n-1;i>=0;i--){ if(sum-a[i]-(2*s) == 0) return i+1; s+=a[i]; } return -1; } +1 bhardwajji1 week ago int equilibriumPoint(long long a[], int n) { long long sum=0; for(int i=0;i<n;i++){ sum+=a[i]; } int s=0; for(int i=n-1;i>=0;i--){ if(sum-a[i]-(2*s) == 0) return i+1; s+=a[i]; } return -1; } 0 neokaizer2 weeks ago Python Binary Search def equilibriumPoint(self,A, N): mid= N // 2 left = 0 right = 0 for i in range(mid): left += A[i] for i in range(N-1, mid, -1): right += A[i] if right > left: while right > left and mid < N-1: right -= A[mid+1] left += A[mid] mid += 1 else: while left > right and mid > 0: right += A[mid] left -= A[mid-1] mid -= 1 if right == left: return mid+1 else: return -1 +1 ashayjainrocks102 weeks ago C++ || O(1) space || O(n) time int equilibriumPoint(long long a[], int n) { long long sum=0,pre=0; for(int i=0;i<n;i++) sum+=a[i]; for(int i=n-1;i>=0;i--) { if(sum-a[i]-pre==pre) return i+1; pre+=a[i]; } return -1; } 0 ashayjainrocks102 weeks ago C++ || Naive approach int equilibriumPoint(long long a[], int n) { long long pre[n]={0}; long long post[n]={0}; for(int i=1;i<n;i++) { pre[i]=pre[i-1]+a[i-1]; post[n-i-1]=post[n-i]+a[n-i]; } for(int i=0;i<n;i++) { if(pre[i]==post[i]) return i+1; } return -1; } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 466, "s": 238, "text": "Given an array A of n positive numbers. The task is to find the first Equilibium Point in the array. \nEquilibrium Point in an array is a position such that the sum of elements before it is equal to the sum of elements after it." }, { "code": null, "e": 526, "s": 466, "text": "Note: Retun the index of Equilibrium point. (1-based index)" }, { "code": null, "e": 537, "s": 526, "text": "Example 1:" }, { "code": null, "e": 711, "s": 537, "text": "Input: \nn = 5 \nA[] = {1,3,5,2,2} \nOutput: 3 \nExplanation: For second test case \nequilibrium point is at position 3 \nas elements before it (1+3) = \nelements after it (2+2). \n" }, { "code": null, "e": 724, "s": 713, "text": "Example 2:" }, { "code": null, "e": 835, "s": 724, "text": "Input:\nn = 1\nA[] = {1}\nOutput: 1\nExplanation:\nSince its the only element hence\nits the only equilibrium point." }, { "code": null, "e": 1026, "s": 837, "text": "Your Task:\nThe task is to complete the function equilibriumPoint() which takes the array and n as input parameters and returns the point of equilibrium. Return -1 if no such point exists. " }, { "code": null, "e": 1088, "s": 1026, "text": "Expected Time Complexity: O(n)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1132, "s": 1088, "text": "Constraints:\n1 <= n <= 106\n1 <= A[i] <= 108" }, { "code": null, "e": 1134, "s": 1132, "text": "0" }, { "code": null, "e": 1160, "s": 1134, "text": "raushanrakesh0691 day ago" }, { "code": null, "e": 1679, "s": 1160, "text": "int low = 0; int high = n-1; while(low<=high){ int mid = low+(high-low)/2; long sum = 0; long sum1 = 0; for(int i=0;i<mid;i++){ sum = sum+arr[i]; } for(int i=mid+1;i<n;i++){ sum1 = sum1+arr[i]; } if(sum==sum1){ return mid+1; }else if(sum<sum1){ low = mid+1; }else{ high = mid-1; } } return -1;" }, { "code": null, "e": 1690, "s": 1681, "text": "0.72 sec" }, { "code": null, "e": 1692, "s": 1690, "text": "0" }, { "code": null, "e": 1719, "s": 1692, "text": "somnathjha0720003 days ago" }, { "code": null, "e": 1725, "s": 1719, "text": "java " }, { "code": null, "e": 2058, "s": 1725, "text": " if(n==1) return 1; long leftsum = 0; long rightsum = 0; for(int i =1;i<n;i++) { rightsum +=arr[i]; } for(int i =1;i<n;i++) { if(rightsum-leftsum==0) return i; else{ leftsum +=arr[i-1]; rightsum -=arr[i]; } } return -1;" }, { "code": null, "e": 2060, "s": 2058, "text": "}" }, { "code": null, "e": 2062, "s": 2060, "text": "0" }, { "code": null, "e": 2087, "s": 2062, "text": "dharpranoy22553 days ago" }, { "code": null, "e": 2102, "s": 2087, "text": "java solution:" }, { "code": null, "e": 2444, "s": 2102, "text": " if (n==1){ return 1; } long leftsum=arr[0]; long rightsum=0; for (int i=1;i<n;i++){ rightsum+=arr[i]; } for (int i=1;i<n;i++){ rightsum-=arr[i]; if (leftsum==rightsum){ return i+1; } leftsum+=arr[i]; } return -1;" }, { "code": null, "e": 2447, "s": 2444, "text": "+1" }, { "code": null, "e": 2471, "s": 2447, "text": "bipulharsh1234 days ago" }, { "code": null, "e": 2905, "s": 2471, "text": "int equilibriumPoint(long long a[], int n) { // Your code here if(n==1) return 1; if(n==2) return -1; int equipt = 1; int lsum = a[0]; int rsum = 0; for(int ind=2; ind<n; ind++) rsum += a[ind]; while(lsum < rsum){ lsum += a[equipt++]; rsum -= a[equipt]; } if(lsum == rsum) return equipt+1; return -1; }" }, { "code": null, "e": 2907, "s": 2905, "text": "0" }, { "code": null, "e": 2925, "s": 2907, "text": "mrnecto1 week ago" }, { "code": null, "e": 2929, "s": 2925, "text": "C++" }, { "code": null, "e": 3406, "s": 2929, "text": "class Solution{\n public:\n // Function to find equilibrium point in the array.\n // a: input array\n // n: size of array\n int equilibriumPoint(long long a[], int n) {\n // Your code here\n if(n == 1) return 1;\n int left = 0, right = 0, i, j;\n for(i = 0, j = n - 1; i <= j;)\n {\n if(i == j && left == right) return i + 1;\n if(left < right) left += a[i++];\n else right += a[j--];\n }\n return -1;\n }\n};" }, { "code": null, "e": 3408, "s": 3406, "text": "0" }, { "code": null, "e": 3434, "s": 3408, "text": "shrivastavap6911 week ago" }, { "code": null, "e": 3790, "s": 3434, "text": "cpp sol\nint equilibriumPoint(long long a[], int n) {\n \n long long sum=0;\n for(int i=0;i<n;i++){\n sum+=a[i];\n }\n \n int s=0;\n \n for(int i=n-1;i>=0;i--){\n if(sum-a[i]-(2*s) == 0)\n return i+1;\n s+=a[i];\n }\n \n return -1;\n \n }" }, { "code": null, "e": 3793, "s": 3790, "text": "+1" }, { "code": null, "e": 3814, "s": 3793, "text": "bhardwajji1 week ago" }, { "code": null, "e": 4162, "s": 3814, "text": "int equilibriumPoint(long long a[], int n) {\n \n long long sum=0;\n for(int i=0;i<n;i++){\n sum+=a[i];\n }\n \n int s=0;\n \n for(int i=n-1;i>=0;i--){\n if(sum-a[i]-(2*s) == 0)\n return i+1;\n s+=a[i];\n }\n \n return -1;\n \n }" }, { "code": null, "e": 4164, "s": 4162, "text": "0" }, { "code": null, "e": 4185, "s": 4164, "text": "neokaizer2 weeks ago" }, { "code": null, "e": 4206, "s": 4185, "text": "Python Binary Search" }, { "code": null, "e": 4817, "s": 4206, "text": "def equilibriumPoint(self,A, N):\n mid= N // 2\n left = 0\n right = 0\n for i in range(mid):\n left += A[i]\n for i in range(N-1, mid, -1):\n right += A[i]\n \n if right > left:\n while right > left and mid < N-1:\n right -= A[mid+1]\n left += A[mid]\n mid += 1\n else:\n while left > right and mid > 0:\n right += A[mid]\n left -= A[mid-1]\n mid -= 1\n if right == left:\n return mid+1\n else:\n return -1" }, { "code": null, "e": 4820, "s": 4817, "text": "+1" }, { "code": null, "e": 4848, "s": 4820, "text": "ashayjainrocks102 weeks ago" }, { "code": null, "e": 4879, "s": 4848, "text": "C++ || O(1) space || O(n) time" }, { "code": null, "e": 5142, "s": 4879, "text": "int equilibriumPoint(long long a[], int n) {\n long long sum=0,pre=0;\n for(int i=0;i<n;i++) sum+=a[i];\n for(int i=n-1;i>=0;i--)\n {\n if(sum-a[i]-pre==pre) return i+1;\n pre+=a[i];\n }\n return -1;\n }\n" }, { "code": null, "e": 5144, "s": 5142, "text": "0" }, { "code": null, "e": 5172, "s": 5144, "text": "ashayjainrocks102 weeks ago" }, { "code": null, "e": 5194, "s": 5172, "text": "C++ || Naive approach" }, { "code": null, "e": 5551, "s": 5194, "text": "int equilibriumPoint(long long a[], int n) {\n \n long long pre[n]={0};\n long long post[n]={0};\n for(int i=1;i<n;i++)\n {\n pre[i]=pre[i-1]+a[i-1];\n post[n-i-1]=post[n-i]+a[n-i];\n }\n for(int i=0;i<n;i++)\n {\n if(pre[i]==post[i]) return i+1;\n }\n return -1;\n }\n" }, { "code": null, "e": 5697, "s": 5551, "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": 5733, "s": 5697, "text": " Login to access your submissions. " }, { "code": null, "e": 5743, "s": 5733, "text": "\nProblem\n" }, { "code": null, "e": 5753, "s": 5743, "text": "\nContest\n" }, { "code": null, "e": 5816, "s": 5753, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5964, "s": 5816, "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": 6172, "s": 5964, "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": 6278, "s": 6172, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to modularize code in ReactJS ? - GeeksforGeeks
08 Oct, 2021 Modularized code is divided into segments or modules, where each file is responsible for a feature or specific functionality. React code can easily be modularized by using the component structure. The approach is to define each component into different files. With each component separated into different files, all we have to do is figure out how to access the code defined in one file within another file. To access one file into another file, React provide the functionality to import and export the files. Import and Export: It enables us to use code from one file into other locations across our projects, which becomes increasingly important as we build out larger applications. Export: Exporting a component, or module of code, allows us to call that export in other files, and use the embedded code within other modules. There are two ways to export code in react: Export Default: We can use the export default syntax. Named Exports: We can explicitly name our exports. Export Default: We can only use export default once per file. The syntax allows us to give any name when we want to import the given module. Syntax: export default COMPONENT_NAME Named Exports: With named exports, we can export multiple pieces of code from a single file, allowing us to call on them explicitly when we import. And for multiple such exports, we can use a comma to separate two-parameter names within the curly braces. Syntax: export {CODE1, CODE2} Import: The import keyword enables us to call the modules that we’ve exported and use them in other files throughout our applications. There are many ways to import the modules in React, and the method that we use depends on how we exported it. Importing default export: In order to import the default export from a file, we can use only the address and use the keyword import before it, or we can give any name to the import. Syntax: import ANY_NAME from ADDRESS Importing named exports: Named export code can be imported by giving the name of that module inside curly braces followed by the address of that file containing that module. For multiple modules, we can use a comma to separate two-parameter names within the curly braces. Syntax: import {Code1, Code2} from ADDRESS Example: Let us see it in the example below where we would use the import and export operations in several ways. Let there are three files, index.js, DefaultExport.js, and NamedExport.js. Let us see how to implement the import and export operations. Filename: index.js Javascript import React from "react";import ReactDOM from "react-dom"; // Importing CSSimport "./index.css"; // Importing default exportimport File from "./DefaultExport"; // Importing named exportsimport { NamedExport } from "./NamedExport";ReactDOM.render( <React.StrictMode> <File /> <NamedExport /> </React.StrictMode>, document.getElementById("root")); Filename: DefaultExport.js Javascript import React from "react"; const DefaultExport = () => { return ( <div> <h1>This is from default export</h1> <h2>Hello Coders</h2> </div> );}; // Default exportexport default DefaultExport; Filename: NamedExport.js Javascript import React from "react"; const NamedExport = () => { return ( <div> <h1>This is from named export</h1> <h2>Nice to see you</h2> </div> );}; // Named Exportexport { NamedExport }; Output: Picked React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to set background images in ReactJS ? How to create a table in ReactJS ? How to navigate on path by button click in react router ? How to create a multi-page website using React.js ? How to build a basic CRUD app with Node.js and ReactJS ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24397, "s": 24369, "text": "\n08 Oct, 2021" }, { "code": null, "e": 24907, "s": 24397, "text": "Modularized code is divided into segments or modules, where each file is responsible for a feature or specific functionality. React code can easily be modularized by using the component structure. The approach is to define each component into different files. With each component separated into different files, all we have to do is figure out how to access the code defined in one file within another file. To access one file into another file, React provide the functionality to import and export the files." }, { "code": null, "e": 25083, "s": 24907, "text": "Import and Export: It enables us to use code from one file into other locations across our projects, which becomes increasingly important as we build out larger applications. " }, { "code": null, "e": 25227, "s": 25083, "text": "Export: Exporting a component, or module of code, allows us to call that export in other files, and use the embedded code within other modules." }, { "code": null, "e": 25271, "s": 25227, "text": "There are two ways to export code in react:" }, { "code": null, "e": 25325, "s": 25271, "text": "Export Default: We can use the export default syntax." }, { "code": null, "e": 25376, "s": 25325, "text": "Named Exports: We can explicitly name our exports." }, { "code": null, "e": 25518, "s": 25376, "text": "Export Default: We can only use export default once per file. The syntax allows us to give any name when we want to import the given module. " }, { "code": null, "e": 25526, "s": 25518, "text": "Syntax:" }, { "code": null, "e": 25556, "s": 25526, "text": "export default COMPONENT_NAME" }, { "code": null, "e": 25812, "s": 25556, "text": "Named Exports: With named exports, we can export multiple pieces of code from a single file, allowing us to call on them explicitly when we import. And for multiple such exports, we can use a comma to separate two-parameter names within the curly braces. " }, { "code": null, "e": 25820, "s": 25812, "text": "Syntax:" }, { "code": null, "e": 25842, "s": 25820, "text": "export {CODE1, CODE2}" }, { "code": null, "e": 26087, "s": 25842, "text": "Import: The import keyword enables us to call the modules that we’ve exported and use them in other files throughout our applications. There are many ways to import the modules in React, and the method that we use depends on how we exported it." }, { "code": null, "e": 26270, "s": 26087, "text": "Importing default export: In order to import the default export from a file, we can use only the address and use the keyword import before it, or we can give any name to the import. " }, { "code": null, "e": 26278, "s": 26270, "text": "Syntax:" }, { "code": null, "e": 26307, "s": 26278, "text": "import ANY_NAME from ADDRESS" }, { "code": null, "e": 26580, "s": 26307, "text": "Importing named exports: Named export code can be imported by giving the name of that module inside curly braces followed by the address of that file containing that module. For multiple modules, we can use a comma to separate two-parameter names within the curly braces. " }, { "code": null, "e": 26590, "s": 26582, "text": "Syntax:" }, { "code": null, "e": 26625, "s": 26590, "text": "import {Code1, Code2} from ADDRESS" }, { "code": null, "e": 26877, "s": 26625, "text": "Example: Let us see it in the example below where we would use the import and export operations in several ways. Let there are three files, index.js, DefaultExport.js, and NamedExport.js. Let us see how to implement the import and export operations. " }, { "code": null, "e": 26897, "s": 26877, "text": "Filename: index.js " }, { "code": null, "e": 26908, "s": 26897, "text": "Javascript" }, { "code": "import React from \"react\";import ReactDOM from \"react-dom\"; // Importing CSSimport \"./index.css\"; // Importing default exportimport File from \"./DefaultExport\"; // Importing named exportsimport { NamedExport } from \"./NamedExport\";ReactDOM.render( <React.StrictMode> <File /> <NamedExport /> </React.StrictMode>, document.getElementById(\"root\"));", "e": 27267, "s": 26908, "text": null }, { "code": null, "e": 27294, "s": 27267, "text": "Filename: DefaultExport.js" }, { "code": null, "e": 27305, "s": 27294, "text": "Javascript" }, { "code": "import React from \"react\"; const DefaultExport = () => { return ( <div> <h1>This is from default export</h1> <h2>Hello Coders</h2> </div> );}; // Default exportexport default DefaultExport;", "e": 27515, "s": 27305, "text": null }, { "code": null, "e": 27540, "s": 27515, "text": "Filename: NamedExport.js" }, { "code": null, "e": 27551, "s": 27540, "text": "Javascript" }, { "code": "import React from \"react\"; const NamedExport = () => { return ( <div> <h1>This is from named export</h1> <h2>Nice to see you</h2> </div> );}; // Named Exportexport { NamedExport };", "e": 27752, "s": 27551, "text": null }, { "code": null, "e": 27760, "s": 27752, "text": "Output:" }, { "code": null, "e": 27767, "s": 27760, "text": "Picked" }, { "code": null, "e": 27783, "s": 27767, "text": "React-Questions" }, { "code": null, "e": 27791, "s": 27783, "text": "ReactJS" }, { "code": null, "e": 27808, "s": 27791, "text": "Web Technologies" }, { "code": null, "e": 27906, "s": 27808, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27915, "s": 27906, "text": "Comments" }, { "code": null, "e": 27928, "s": 27915, "text": "Old Comments" }, { "code": null, "e": 27970, "s": 27928, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 28005, "s": 27970, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 28063, "s": 28005, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 28115, "s": 28063, "text": "How to create a multi-page website using React.js ?" }, { "code": null, "e": 28172, "s": 28115, "text": "How to build a basic CRUD app with Node.js and ReactJS ?" }, { "code": null, "e": 28228, "s": 28172, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 28261, "s": 28228, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28323, "s": 28261, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28373, "s": 28323, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Querying age from DOB in MySQL?
Let us first create a table βˆ’ mysql> create table DemoTable611 (DOB date); Query OK, 0 rows affected (0.99 sec) Insert some records in the table using insert command βˆ’ mysql> insert into DemoTable611 values('1996-04-21'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable611 values('2001-01-31'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable611 values('2004-12-21'); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable611 values('2000-02-03'); Query OK, 1 row affected (0.14 sec) Display all records from the table using select statement βˆ’ mysql> select *from DemoTable611; This will produce the following output βˆ’ +------------+ | DOB | +------------+ | 1996-04-21 | | 2001-01-31 | | 2004-12-21 | | 2000-02-03 | +------------+ 4 rows in set (0.00 sec) Querying age from DOB βˆ’ mysql> select *from DemoTable611 where DOB >= (CURDATE() - INTERVAL 16 YEAR); This will produce the following output βˆ’ +------------+ | DOB | +------------+ | 2004-12-21 | +------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1092, "s": 1062, "text": "Let us first create a table βˆ’" }, { "code": null, "e": 1174, "s": 1092, "text": "mysql> create table DemoTable611 (DOB date);\nQuery OK, 0 rows affected (0.99 sec)" }, { "code": null, "e": 1230, "s": 1174, "text": "Insert some records in the table using insert command βˆ’" }, { "code": null, "e": 1590, "s": 1230, "text": "mysql> insert into DemoTable611 values('1996-04-21');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable611 values('2001-01-31');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable611 values('2004-12-21');\nQuery OK, 1 row affected (0.22 sec)\nmysql> insert into DemoTable611 values('2000-02-03');\nQuery OK, 1 row affected (0.14 sec)" }, { "code": null, "e": 1650, "s": 1590, "text": "Display all records from the table using select statement βˆ’" }, { "code": null, "e": 1684, "s": 1650, "text": "mysql> select *from DemoTable611;" }, { "code": null, "e": 1725, "s": 1684, "text": "This will produce the following output βˆ’" }, { "code": null, "e": 1870, "s": 1725, "text": "+------------+\n| DOB |\n+------------+\n| 1996-04-21 |\n| 2001-01-31 |\n| 2004-12-21 |\n| 2000-02-03 |\n+------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 1894, "s": 1870, "text": "Querying age from DOB βˆ’" }, { "code": null, "e": 1972, "s": 1894, "text": "mysql> select *from DemoTable611 where DOB >= (CURDATE() - INTERVAL 16 YEAR);" }, { "code": null, "e": 2013, "s": 1972, "text": "This will produce the following output βˆ’" }, { "code": null, "e": 2112, "s": 2013, "text": "+------------+\n| DOB |\n+------------+\n| 2004-12-21 |\n+------------+\n1 row in set (0.00 sec)" } ]
How can I source a Python file from another Python file?
In order to source a Python file from another python file, you have to use it like a module. import the file you want to run and run its functions. For example, say you want to import fileB.py into fileA.py, assuming the files are in the same directory, inside fileA you'd write import fileB Now in fileA, you can call any function inside fileB like: fileB.my_func() In file B you have to define a function called my_func before you can use it in any other file. def my_func(): print("Hello from B") Now when you run fileA.py, you will get the output: Hello from B
[ { "code": null, "e": 1341, "s": 1062, "text": "In order to source a Python file from another python file, you have to use it like a module. import the file you want to run and run its functions. For example, say you want to import fileB.py into fileA.py, assuming the files are in the same directory, inside fileA you'd write" }, { "code": null, "e": 1354, "s": 1341, "text": "import fileB" }, { "code": null, "e": 1413, "s": 1354, "text": "Now in fileA, you can call any function inside fileB like:" }, { "code": null, "e": 1429, "s": 1413, "text": "fileB.my_func()" }, { "code": null, "e": 1525, "s": 1429, "text": "In file B you have to define a function called my_func before you can use it in any other file." }, { "code": null, "e": 1566, "s": 1525, "text": "def my_func():\n print(\"Hello from B\")" }, { "code": null, "e": 1618, "s": 1566, "text": "Now when you run fileA.py, you will get the output:" }, { "code": null, "e": 1631, "s": 1618, "text": "Hello from B" } ]
Python - Convert String Truth values to Boolean - GeeksforGeeks
02 Sep, 2020 Given a String List, convert the String Truth values to Boolean values. Input : test_list = [β€œTrue”, β€œFalse”, β€œTrue”, β€œFalse”]Output : [True, False, True, False]Explanation : String booleans converted to actual Boolean. Input : test_list = [β€œTrue”]Output : [True]Explanation : String boolean converted to actual Boolean. Method #1 : Using list comprehension In this, we check for just the True value, rest values are automatically converted to False boolean. Python3 # Python3 code to demonstrate working of # Convert String Truth values to Boolean# Using list comprehension # initializing liststest_list = ["True", "False", "True", "True", "False"] # printing stringprint("The original list : " + str(test_list)) # using list comprehension to check "True" stringres = [ele == "True" for ele in test_list] # printing results print("The converted Boolean values : " + str(res)) The original list : ['True', 'False', 'True', 'True', 'False'] The converted Boolean values : [True, False, True, True, False] Method #2 : Using map() + lambda In this, we apply same approach, just the different way to solve the problem. The map() is used to extend logic of values computed by lambda function. Python3 # Python3 code to demonstrate working of # Convert String Truth values to Boolean# Using map() + lambda # initializing liststest_list = ["True", "False", "True", "True", "False"] # printing stringprint("The original list : " + str(test_list)) # using map() to extend and lambda to check "True" stringres = list(map(lambda ele: ele == "True", test_list)) # printing results print("The converted Boolean values : " + str(res)) The original list : ['True', 'False', 'True', 'True', 'False'] The converted Boolean values : [True, False, True, True, False] Python list-programs Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary Python program to check whether a number is Prime or not
[ { "code": null, "e": 24465, "s": 24437, "text": "\n02 Sep, 2020" }, { "code": null, "e": 24537, "s": 24465, "text": "Given a String List, convert the String Truth values to Boolean values." }, { "code": null, "e": 24685, "s": 24537, "text": "Input : test_list = [β€œTrue”, β€œFalse”, β€œTrue”, β€œFalse”]Output : [True, False, True, False]Explanation : String booleans converted to actual Boolean." }, { "code": null, "e": 24786, "s": 24685, "text": "Input : test_list = [β€œTrue”]Output : [True]Explanation : String boolean converted to actual Boolean." }, { "code": null, "e": 24823, "s": 24786, "text": "Method #1 : Using list comprehension" }, { "code": null, "e": 24924, "s": 24823, "text": "In this, we check for just the True value, rest values are automatically converted to False boolean." }, { "code": null, "e": 24932, "s": 24924, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Convert String Truth values to Boolean# Using list comprehension # initializing liststest_list = [\"True\", \"False\", \"True\", \"True\", \"False\"] # printing stringprint(\"The original list : \" + str(test_list)) # using list comprehension to check \"True\" stringres = [ele == \"True\" for ele in test_list] # printing results print(\"The converted Boolean values : \" + str(res))", "e": 25346, "s": 24932, "text": null }, { "code": null, "e": 25474, "s": 25346, "text": "The original list : ['True', 'False', 'True', 'True', 'False']\nThe converted Boolean values : [True, False, True, True, False]\n" }, { "code": null, "e": 25507, "s": 25474, "text": "Method #2 : Using map() + lambda" }, { "code": null, "e": 25658, "s": 25507, "text": "In this, we apply same approach, just the different way to solve the problem. The map() is used to extend logic of values computed by lambda function." }, { "code": null, "e": 25666, "s": 25658, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Convert String Truth values to Boolean# Using map() + lambda # initializing liststest_list = [\"True\", \"False\", \"True\", \"True\", \"False\"] # printing stringprint(\"The original list : \" + str(test_list)) # using map() to extend and lambda to check \"True\" stringres = list(map(lambda ele: ele == \"True\", test_list)) # printing results print(\"The converted Boolean values : \" + str(res))", "e": 26095, "s": 25666, "text": null }, { "code": null, "e": 26223, "s": 26095, "text": "The original list : ['True', 'False', 'True', 'True', 'False']\nThe converted Boolean values : [True, False, True, True, False]\n" }, { "code": null, "e": 26244, "s": 26223, "text": "Python list-programs" }, { "code": null, "e": 26267, "s": 26244, "text": "Python string-programs" }, { "code": null, "e": 26274, "s": 26267, "text": "Python" }, { "code": null, "e": 26290, "s": 26274, "text": "Python Programs" }, { "code": null, "e": 26388, "s": 26290, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26397, "s": 26388, "text": "Comments" }, { "code": null, "e": 26410, "s": 26397, "text": "Old Comments" }, { "code": null, "e": 26428, "s": 26410, "text": "Python Dictionary" }, { "code": null, "e": 26463, "s": 26428, "text": "Read a file line by line in Python" }, { "code": null, "e": 26485, "s": 26463, "text": "Enumerate() in Python" }, { "code": null, "e": 26517, "s": 26485, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26547, "s": 26517, "text": "Iterate over a list in Python" }, { "code": null, "e": 26569, "s": 26547, "text": "Defaultdict in Python" }, { "code": null, "e": 26608, "s": 26569, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26654, "s": 26608, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26692, "s": 26654, "text": "Python | Convert a list to dictionary" } ]
How to generate XML from Python dictionary?
To generate XML from a python dictionary, you need to install the dicttoxml package. You can install it using: $ pip install dicttoxml Once installed, you can use the dicttoxml method to create the xml. a = { 'foo': 45, 'bar': { 'baz': "Hello" } } xml = dicttoxml.dicttoxml(a) print(xml) This will give the output: b'<?xml version="1.0" encoding="UTF-8" ?><root><foo type="int">45</foo><bar type="dict"><baz type="str">Hello</baz></bar></root>' You can also prettyprint this output using the toprettyxml method. from xml.dom.minidom import parseString a = { 'foo': 45, 'bar': { 'baz': "Hello" } } xml = dicttoxml.dicttoxml(a) dom = parseString(xml) print(dom.toprettyxml()) This will give the output βˆ’ <?xml version = "1.0" ?> <root> <foo type = "int">45</foo> <bar type = "dict"> <baz type="str">Hello</baz> </bar> </root>
[ { "code": null, "e": 1173, "s": 1062, "text": "To generate XML from a python dictionary, you need to install the dicttoxml package. You can install it using:" }, { "code": null, "e": 1197, "s": 1173, "text": "$ pip install dicttoxml" }, { "code": null, "e": 1266, "s": 1197, "text": "Once installed, you can use the dicttoxml method to create the xml. " }, { "code": null, "e": 1366, "s": 1266, "text": "a = {\n 'foo': 45,\n 'bar': {\n 'baz': \"Hello\"\n }\n}\nxml = dicttoxml.dicttoxml(a)\nprint(xml)" }, { "code": null, "e": 1393, "s": 1366, "text": "This will give the output:" }, { "code": null, "e": 1523, "s": 1393, "text": "b'<?xml version=\"1.0\" encoding=\"UTF-8\" ?><root><foo type=\"int\">45</foo><bar type=\"dict\"><baz type=\"str\">Hello</baz></bar></root>'" }, { "code": null, "e": 1591, "s": 1523, "text": "You can also prettyprint this output using the toprettyxml method. " }, { "code": null, "e": 1631, "s": 1591, "text": "from xml.dom.minidom import parseString" }, { "code": null, "e": 1768, "s": 1631, "text": "a = {\n 'foo': 45,\n 'bar': {\n 'baz': \"Hello\"\n }\n}\nxml = dicttoxml.dicttoxml(a)\ndom = parseString(xml)\nprint(dom.toprettyxml())" }, { "code": null, "e": 1796, "s": 1768, "text": "This will give the output βˆ’" }, { "code": null, "e": 1933, "s": 1796, "text": "<?xml version = \"1.0\" ?>\n<root>\n <foo type = \"int\">45</foo>\n <bar type = \"dict\">\n <baz type=\"str\">Hello</baz>\n </bar>\n</root>" } ]
Streams in Java
Stream is a new abstract layer introduced in Java 8. Using stream, you can process data in a declarative way similar to SQL statements. For example, consider the following SQL statement. SELECT max(salary), employee_id, employee_name FROM Employee The above SQL expression automatically returns the maximum salaried employee's details, without doing any computation on the developer's end. Using collections framework in Java, a developer has to use loops and make repeated checks. Another concern is efficiency; as multi-core processors are available at ease, a Java developer has to write parallel code processing that can be pretty error-prone. To resolve such issues, Java 8 introduced the concept of stream that lets the developer to process data declaratively and leverage multicore architecture without the need to write any specific code for it. Stream represents a sequence of objects from a source, which supports aggregate operations. Following are the characteristics of a Stream. Sequence of elements βˆ’ A stream provides a set of elements of specific type in a sequential manner. A stream gets/computes elements on demand. It never stores the elements. Sequence of elements βˆ’ A stream provides a set of elements of specific type in a sequential manner. A stream gets/computes elements on demand. It never stores the elements. Source βˆ’ Stream takes Collections, Arrays, or I/O resources as input source. Source βˆ’ Stream takes Collections, Arrays, or I/O resources as input source. Aggregate operations βˆ’ Stream supports aggregate operations like filter, map, limit, reduce, find, match, and so on. Aggregate operations βˆ’ Stream supports aggregate operations like filter, map, limit, reduce, find, match, and so on. Pipelining βˆ’ Most of the stream operations return stream itself so that their result can be pipelined. These operations are called intermediate operations and their function is to take input, process them, and return output to the target. collect() method is a terminal operation which is normally present at the end of the pipelining operation to mark the end of the stream. Pipelining βˆ’ Most of the stream operations return stream itself so that their result can be pipelined. These operations are called intermediate operations and their function is to take input, process them, and return output to the target. collect() method is a terminal operation which is normally present at the end of the pipelining operation to mark the end of the stream. Automatic iterations βˆ’ Stream operations do the iterations internally over the source elements provided, in contrast to Collections where explicit iteration is required. Automatic iterations βˆ’ Stream operations do the iterations internally over the source elements provided, in contrast to Collections where explicit iteration is required. With Java 8, Collection interface has two methods to generate a Stream. stream() βˆ’ Returns a sequential stream considering collection as its source. stream() βˆ’ Returns a sequential stream considering collection as its source. parallelStream() βˆ’ Returns a parallel Stream considering collection as its source. parallelStream() βˆ’ Returns a parallel Stream considering collection as its source. List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl"); List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList()); Stream has provided a new method 'forEach' to iterate each element of the stream. The following code segment shows how to print 10 random numbers using forEach. Random random = new Random(); random.ints().limit(10).forEach(System.out::println); The 'map' method is used to map each element to its corresponding result. The following code segment prints unique squares of numbers using map. List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5); //get list of unique squares List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList()); The 'filter' method is used to eliminate elements based on a criteria. The following code segment prints a count of empty strings using filter. List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl"); //get count of empty string int count = strings.stream().filter(string -> string.isEmpty()).count(); The 'limit' method is used to reduce the size of the stream. The following code segment shows how to print 10 random numbers using limit. Random random = new Random(); random.ints().limit(10).forEach(System.out::println); The 'sorted' method is used to sort the stream. The following code segment shows how to print 10 random numbers in a sorted order. Random random = new Random(); random.ints().limit(10).sorted().forEach(System.out::println); parallelStream is the alternative of stream for parallel processing. Take a look at the following code segment that prints a count of empty strings using parallelStream. List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl"); //get count of empty string int count = strings.parallelStream().filter(string -> string.isEmpty()).count(); It is very easy to switch between sequential and parallel streams. Collectors are used to combine the result of processing on the elements of a stream. Collectors can be used to return a list or a string. List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl"); List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList()); System.out.println("Filtered List: " + filtered); String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", ")); System.out.println("Merged String: " + mergedString); With Java 8, statistics collectors are introduced to calculate all statistics when stream processing is being done. List numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5); IntSummaryStatistics stats = integers.stream().mapToInt((x) -> x).summaryStatistics(); System.out.println("Highest number in List : " + stats.getMax()); System.out.println("Lowest number in List : " + stats.getMin()); System.out.println("Sum of all numbers : " + stats.getSum()); System.out.println("Average of all numbers : " + stats.getAverage()); Create the following Java program using any editor of your choice in, say, C:\> JAVA. Live Demo import java.util.ArrayList; import java.util.Arrays; import java.util.IntSummaryStatistics; import java.util.List; import java.util.Random; import java.util.stream.Collectors; import java.util.Map; public class Java8Tester { public static void main(String args[]) { System.out.println("Using Java 7: "); // Count empty strings List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl"); System.out.println("List: " +strings); long count = getCountEmptyStringUsingJava7(strings); System.out.println("Empty Strings: " + count); count = getCountLength3UsingJava7(strings); System.out.println("Strings of length 3: " + count); //Eliminate empty string List<String> filtered = deleteEmptyStringsUsingJava7(strings); System.out.println("Filtered List: " + filtered); //Eliminate empty string and join using comma. String mergedString = getMergedStringUsingJava7(strings,", "); System.out.println("Merged String: " + mergedString); List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5); //get list of square of distinct numbers List<Integer> squaresList = getSquares(numbers); System.out.println("Squares List: " + squaresList); List<Integer> integers = Arrays.asList(1,2,13,4,15,6,17,8,19); System.out.println("List: " +integers); System.out.println("Highest number in List : " + getMax(integers)); System.out.println("Lowest number in List : " + getMin(integers)); System.out.println("Sum of all numbers : " + getSum(integers)); System.out.println("Average of all numbers : " + getAverage(integers)); System.out.println("Random Numbers: "); //print ten random numbers Random random = new Random(); for(int i = 0; i < 10; i++) { System.out.println(random.nextInt()); } System.out.println("Using Java 8: "); System.out.println("List: " +strings); count = strings.stream().filter(string->string.isEmpty()).count(); System.out.println("Empty Strings: " + count); count = strings.stream().filter(string -> string.length() == 3).count(); System.out.println("Strings of length 3: " + count); filtered = strings.stream().filter(string ->!string.isEmpty()).collect(Collectors.toList()); System.out.println("Filtered List: " + filtered); mergedString = strings.stream().filter(string ->!string.isEmpty()).collect(Collectors.joining(", ")); System.out.println("Merged String: " + mergedString); squaresList = numbers.stream().map( i ->i*i).distinct().collect(Collectors.toList()); System.out.println("Squares List: " + squaresList); System.out.println("List: " +integers); IntSummaryStatistics stats = integers.stream().mapToInt((x) ->x).summaryStatistics(); System.out.println("Highest number in List : " + stats.getMax()); System.out.println("Lowest number in List : " + stats.getMin()); System.out.println("Sum of all numbers : " + stats.getSum()); System.out.println("Average of all numbers : " + stats.getAverage()); System.out.println("Random Numbers: "); random.ints().limit(10).sorted().forEach(System.out::println); //parallel processing count = strings.parallelStream().filter(string -> string.isEmpty()).count(); System.out.println("Empty Strings: " + count); } private static int getCountEmptyStringUsingJava7(List<String> strings) { int count = 0; for(String string: strings) { if(string.isEmpty()) { count++; } } return count; } private static int getCountLength3UsingJava7(List<String> strings) { int count = 0; for(String string: strings) { if(string.length() == 3) { count++; } } return count; } private static List<String> deleteEmptyStringsUsingJava7(List<String> strings) { List<String> filteredList = new ArrayList<String>(); for(String string: strings) { if(!string.isEmpty()) { filteredList.add(string); } } return filteredList; } private static String getMergedStringUsingJava7(List<String> strings, String separator) { StringBuilder stringBuilder = new StringBuilder(); for(String string: strings) { if(!string.isEmpty()) { stringBuilder.append(string); stringBuilder.append(separator); } } String mergedString = stringBuilder.toString(); return mergedString.substring(0, mergedString.length()-2); } private static List<Integer> getSquares(List<Integer> numbers) { List<Integer> squaresList = new ArrayList<Integer>(); for(Integer number: numbers) { Integer square = new Integer(number.intValue() * number.intValue()); if(!squaresList.contains(square)) { squaresList.add(square); } } return squaresList; } private static int getMax(List<Integer> numbers) { int max = numbers.get(0); for(int i = 1;i < numbers.size();i++) { Integer number = numbers.get(i); if(number.intValue() > max) { max = number.intValue(); } } return max; } private static int getMin(List<Integer> numbers) { int min = numbers.get(0); for(int i= 1;i < numbers.size();i++) { Integer number = numbers.get(i); if(number.intValue() < min) { min = number.intValue(); } } return min; } private static int getSum(List numbers) { int sum = (int)(numbers.get(0)); for(int i = 1;i < numbers.size();i++) { sum += (int)numbers.get(i); } return sum; } private static int getAverage(List<Integer> numbers) { return getSum(numbers) / numbers.size(); } } Compile the class using javac compiler as follows βˆ’ C:\JAVA>javac Java8Tester.java Now run the Java8Tester as follows βˆ’ C:\JAVA>java Java8Tester It should produce the following result. Using Java 7: List: [abc, , bc, efg, abcd, , jkl] Empty Strings: 2 Strings of length 3: 3 Filtered List: [abc, bc, efg, abcd, jkl] Merged String: abc, bc, efg, abcd, jkl Squares List: [9, 4, 49, 25] List: [1, 2, 13, 4, 15, 6, 17, 8, 19] Highest number in List : 19 Lowest number in List : 1 Sum of all numbers : 85 Average of all numbers : 9 Random Numbers: -1279735475 903418352 -1133928044 -1571118911 628530462 18407523 -881538250 -718932165 270259229 421676854 Using Java 8: List: [abc, , bc, efg, abcd, , jkl] Empty Strings: 2 Strings of length 3: 3 Filtered List: [abc, bc, efg, abcd, jkl] Merged String: abc, bc, efg, abcd, jkl Squares List: [9, 4, 49, 25] List: [1, 2, 13, 4, 15, 6, 17, 8, 19] Highest number in List : 19 Lowest number in List : 1 Sum of all numbers : 85 Average of all numbers : 9.444444444444445 Random Numbers: -1009474951 -551240647 -2484714 181614550 933444268 1227850416 1579250773 1627454872 1683033687 1798939493 Empty Strings: 2
[ { "code": null, "e": 1249, "s": 1062, "text": "Stream is a new abstract layer introduced in Java 8. Using stream, you can process data in a declarative way similar to SQL statements. For example, consider the following SQL statement." }, { "code": null, "e": 1310, "s": 1249, "text": "SELECT max(salary), employee_id, employee_name FROM Employee" }, { "code": null, "e": 1710, "s": 1310, "text": "The above SQL expression automatically returns the maximum salaried employee's details, without doing any computation on the developer's end. Using collections framework in Java, a developer has to use loops and make repeated checks. Another concern is efficiency; as multi-core processors are available at ease, a Java developer has to write parallel code processing that can be pretty error-prone." }, { "code": null, "e": 1916, "s": 1710, "text": "To resolve such issues, Java 8 introduced the concept of stream that lets the developer to process data declaratively and leverage multicore architecture without the need to write any specific code for it." }, { "code": null, "e": 2055, "s": 1916, "text": "Stream represents a sequence of objects from a source, which supports aggregate operations. Following are the characteristics of a Stream." }, { "code": null, "e": 2228, "s": 2055, "text": "Sequence of elements βˆ’ A stream provides a set of elements of specific type in a sequential manner. A stream gets/computes elements on demand. It never stores the elements." }, { "code": null, "e": 2401, "s": 2228, "text": "Sequence of elements βˆ’ A stream provides a set of elements of specific type in a sequential manner. A stream gets/computes elements on demand. It never stores the elements." }, { "code": null, "e": 2478, "s": 2401, "text": "Source βˆ’ Stream takes Collections, Arrays, or I/O resources as input source." }, { "code": null, "e": 2555, "s": 2478, "text": "Source βˆ’ Stream takes Collections, Arrays, or I/O resources as input source." }, { "code": null, "e": 2672, "s": 2555, "text": "Aggregate operations βˆ’ Stream supports aggregate operations like filter, map, limit, reduce, find, match, and so on." }, { "code": null, "e": 2789, "s": 2672, "text": "Aggregate operations βˆ’ Stream supports aggregate operations like filter, map, limit, reduce, find, match, and so on." }, { "code": null, "e": 3165, "s": 2789, "text": "Pipelining βˆ’ Most of the stream operations return stream itself so that their result can be pipelined. These operations are called intermediate operations and their function is to take input, process them, and return output to the target. collect() method is a terminal operation which is normally present at the end of the pipelining operation to mark the end of the stream." }, { "code": null, "e": 3541, "s": 3165, "text": "Pipelining βˆ’ Most of the stream operations return stream itself so that their result can be pipelined. These operations are called intermediate operations and their function is to take input, process them, and return output to the target. collect() method is a terminal operation which is normally present at the end of the pipelining operation to mark the end of the stream." }, { "code": null, "e": 3711, "s": 3541, "text": "Automatic iterations βˆ’ Stream operations do the iterations internally over the source elements provided, in contrast to Collections where explicit iteration is required." }, { "code": null, "e": 3881, "s": 3711, "text": "Automatic iterations βˆ’ Stream operations do the iterations internally over the source elements provided, in contrast to Collections where explicit iteration is required." }, { "code": null, "e": 3953, "s": 3881, "text": "With Java 8, Collection interface has two methods to generate a Stream." }, { "code": null, "e": 4030, "s": 3953, "text": "stream() βˆ’ Returns a sequential stream considering collection as its source." }, { "code": null, "e": 4107, "s": 4030, "text": "stream() βˆ’ Returns a sequential stream considering collection as its source." }, { "code": null, "e": 4190, "s": 4107, "text": "parallelStream() βˆ’ Returns a parallel Stream considering collection as its source." }, { "code": null, "e": 4273, "s": 4190, "text": "parallelStream() βˆ’ Returns a parallel Stream considering collection as its source." }, { "code": null, "e": 4460, "s": 4273, "text": "List<String> strings = Arrays.asList(\"abc\", \"\", \"bc\", \"efg\", \"abcd\",\"\", \"jkl\");\nList<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());" }, { "code": null, "e": 4621, "s": 4460, "text": "Stream has provided a new method 'forEach' to iterate each element of the stream. The following code segment shows how to print 10 random numbers using forEach." }, { "code": null, "e": 4705, "s": 4621, "text": "Random random = new Random();\nrandom.ints().limit(10).forEach(System.out::println);" }, { "code": null, "e": 4850, "s": 4705, "text": "The 'map' method is used to map each element to its corresponding result. The following code segment prints unique squares of numbers using map." }, { "code": null, "e": 5041, "s": 4850, "text": "List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);\n\n//get list of unique squares\nList<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());" }, { "code": null, "e": 5185, "s": 5041, "text": "The 'filter' method is used to eliminate elements based on a criteria. The following code segment prints a count of empty strings using filter." }, { "code": null, "e": 5366, "s": 5185, "text": "List<String>strings = Arrays.asList(\"abc\", \"\", \"bc\", \"efg\", \"abcd\",\"\", \"jkl\");\n\n//get count of empty string\nint count = strings.stream().filter(string -> string.isEmpty()).count();" }, { "code": null, "e": 5504, "s": 5366, "text": "The 'limit' method is used to reduce the size of the stream. The following code segment shows how to print 10 random numbers using limit." }, { "code": null, "e": 5588, "s": 5504, "text": "Random random = new Random();\nrandom.ints().limit(10).forEach(System.out::println);" }, { "code": null, "e": 5719, "s": 5588, "text": "The 'sorted' method is used to sort the stream. The following code segment shows how to print 10 random numbers in a sorted order." }, { "code": null, "e": 5812, "s": 5719, "text": "Random random = new Random();\nrandom.ints().limit(10).sorted().forEach(System.out::println);" }, { "code": null, "e": 5982, "s": 5812, "text": "parallelStream is the alternative of stream for parallel processing. Take a look at the following code segment that prints a count of empty strings using parallelStream." }, { "code": null, "e": 6172, "s": 5982, "text": "List<String> strings = Arrays.asList(\"abc\", \"\", \"bc\", \"efg\", \"abcd\",\"\", \"jkl\");\n\n//get count of empty string\nint count = strings.parallelStream().filter(string -> string.isEmpty()).count();" }, { "code": null, "e": 6239, "s": 6172, "text": "It is very easy to switch between sequential and parallel streams." }, { "code": null, "e": 6377, "s": 6239, "text": "Collectors are used to combine the result of processing on the elements of a stream. Collectors can be used to return a list or a string." }, { "code": null, "e": 6777, "s": 6377, "text": "List<String>strings = Arrays.asList(\"abc\", \"\", \"bc\", \"efg\", \"abcd\",\"\", \"jkl\");\nList<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());\nSystem.out.println(\"Filtered List: \" + filtered);\nString mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(\", \"));\nSystem.out.println(\"Merged String: \" + mergedString);" }, { "code": null, "e": 6893, "s": 6777, "text": "With Java 8, statistics collectors are introduced to calculate all statistics when stream processing is being done." }, { "code": null, "e": 7294, "s": 6893, "text": "List numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);\nIntSummaryStatistics stats = integers.stream().mapToInt((x) -> x).summaryStatistics();\nSystem.out.println(\"Highest number in List : \" + stats.getMax());\nSystem.out.println(\"Lowest number in List : \" + stats.getMin());\nSystem.out.println(\"Sum of all numbers : \" + stats.getSum());\nSystem.out.println(\"Average of all numbers : \" + stats.getAverage());" }, { "code": null, "e": 7380, "s": 7294, "text": "Create the following Java program using any editor of your choice in, say, C:\\> JAVA." }, { "code": null, "e": 7391, "s": 7380, "text": " Live Demo" }, { "code": null, "e": 13278, "s": 7391, "text": "import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.IntSummaryStatistics;\nimport java.util.List;\nimport java.util.Random;\nimport java.util.stream.Collectors;\nimport java.util.Map;\npublic class Java8Tester {\n public static void main(String args[]) {\n System.out.println(\"Using Java 7: \");\n // Count empty strings\n List<String> strings = Arrays.asList(\"abc\", \"\", \"bc\", \"efg\", \"abcd\",\"\", \"jkl\");\n System.out.println(\"List: \" +strings);\n long count = getCountEmptyStringUsingJava7(strings);\n System.out.println(\"Empty Strings: \" + count);\n count = getCountLength3UsingJava7(strings);\n System.out.println(\"Strings of length 3: \" + count);\n //Eliminate empty string\n List<String> filtered = deleteEmptyStringsUsingJava7(strings);\n System.out.println(\"Filtered List: \" + filtered);\n //Eliminate empty string and join using comma.\n String mergedString = getMergedStringUsingJava7(strings,\", \");\n System.out.println(\"Merged String: \" + mergedString);\n List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);\n //get list of square of distinct numbers\n List<Integer> squaresList = getSquares(numbers);\n System.out.println(\"Squares List: \" + squaresList);\n List<Integer> integers = Arrays.asList(1,2,13,4,15,6,17,8,19);\n System.out.println(\"List: \" +integers);\n System.out.println(\"Highest number in List : \" + getMax(integers));\n System.out.println(\"Lowest number in List : \" + getMin(integers));\n System.out.println(\"Sum of all numbers : \" + getSum(integers));\n System.out.println(\"Average of all numbers : \" + getAverage(integers));\n System.out.println(\"Random Numbers: \");\n //print ten random numbers\n Random random = new Random();\n for(int i = 0; i < 10; i++) {\n System.out.println(random.nextInt());\n }\n System.out.println(\"Using Java 8: \");\n System.out.println(\"List: \" +strings);\n count = strings.stream().filter(string->string.isEmpty()).count();\n System.out.println(\"Empty Strings: \" + count);\n count = strings.stream().filter(string -> string.length() == 3).count();\n System.out.println(\"Strings of length 3: \" + count);\n filtered = strings.stream().filter(string ->!string.isEmpty()).collect(Collectors.toList());\n System.out.println(\"Filtered List: \" + filtered);\n mergedString = strings.stream().filter(string ->!string.isEmpty()).collect(Collectors.joining(\", \"));\n System.out.println(\"Merged String: \" + mergedString);\n squaresList = numbers.stream().map( i ->i*i).distinct().collect(Collectors.toList());\n System.out.println(\"Squares List: \" + squaresList);\n System.out.println(\"List: \" +integers);\n IntSummaryStatistics stats = integers.stream().mapToInt((x) ->x).summaryStatistics();\n System.out.println(\"Highest number in List : \" + stats.getMax());\n System.out.println(\"Lowest number in List : \" + stats.getMin());\n System.out.println(\"Sum of all numbers : \" + stats.getSum());\n System.out.println(\"Average of all numbers : \" + stats.getAverage());\n System.out.println(\"Random Numbers: \");\n random.ints().limit(10).sorted().forEach(System.out::println);\n //parallel processing\n count = strings.parallelStream().filter(string -> string.isEmpty()).count();\n System.out.println(\"Empty Strings: \" + count);\n }\n private static int getCountEmptyStringUsingJava7(List<String> strings) {\n int count = 0;\n for(String string: strings) {\n if(string.isEmpty()) {\n count++;\n }\n }\n return count;\n }\n private static int getCountLength3UsingJava7(List<String> strings) {\n int count = 0;\n for(String string: strings) {\n if(string.length() == 3) {\n count++;\n }\n }\n return count;\n }\n private static List<String> deleteEmptyStringsUsingJava7(List<String> strings) {\n List<String> filteredList = new ArrayList<String>();\n for(String string: strings) {\n if(!string.isEmpty()) {\n filteredList.add(string);\n }\n }\n return filteredList;\n }\n private static String getMergedStringUsingJava7(List<String> strings, String separator) {\n StringBuilder stringBuilder = new StringBuilder();\n for(String string: strings) {\n if(!string.isEmpty()) {\n stringBuilder.append(string);\n stringBuilder.append(separator);\n }\n }\n String mergedString = stringBuilder.toString();\n return mergedString.substring(0, mergedString.length()-2);\n }\n private static List<Integer> getSquares(List<Integer> numbers) {\n List<Integer> squaresList = new ArrayList<Integer>();\n for(Integer number: numbers) {\n Integer square = new Integer(number.intValue() * number.intValue());\n if(!squaresList.contains(square)) {\n squaresList.add(square);\n }\n }\n return squaresList;\n }\n private static int getMax(List<Integer> numbers) {\n int max = numbers.get(0);\n for(int i = 1;i < numbers.size();i++) {\n Integer number = numbers.get(i);\n if(number.intValue() > max) {\n max = number.intValue();\n }\n }\n return max;\n }\n private static int getMin(List<Integer> numbers) {\n int min = numbers.get(0);\n for(int i= 1;i < numbers.size();i++) {\n Integer number = numbers.get(i);\n if(number.intValue() < min) {\n min = number.intValue();\n }\n }\n return min;\n }\n private static int getSum(List numbers) {\n int sum = (int)(numbers.get(0));\n for(int i = 1;i < numbers.size();i++) {\n sum += (int)numbers.get(i);\n }\n return sum;\n }\n private static int getAverage(List<Integer> numbers) {\n return getSum(numbers) / numbers.size();\n }\n}" }, { "code": null, "e": 13330, "s": 13278, "text": "Compile the class using javac compiler as follows βˆ’" }, { "code": null, "e": 13362, "s": 13330, "text": "C:\\JAVA>javac Java8Tester.java\n" }, { "code": null, "e": 13399, "s": 13362, "text": "Now run the Java8Tester as follows βˆ’" }, { "code": null, "e": 13425, "s": 13399, "text": "C:\\JAVA>java Java8Tester\n" }, { "code": null, "e": 13465, "s": 13425, "text": "It should produce the following result." }, { "code": null, "e": 14429, "s": 13465, "text": "Using Java 7:\nList: [abc, , bc, efg, abcd, , jkl]\nEmpty Strings: 2\nStrings of length 3: 3\nFiltered List: [abc, bc, efg, abcd, jkl]\nMerged String: abc, bc, efg, abcd, jkl\nSquares List: [9, 4, 49, 25]\nList: [1, 2, 13, 4, 15, 6, 17, 8, 19]\nHighest number in List : 19\nLowest number in List : 1\nSum of all numbers : 85\nAverage of all numbers : 9\nRandom Numbers:\n-1279735475\n903418352\n-1133928044\n-1571118911\n628530462\n18407523\n-881538250\n-718932165\n270259229\n421676854\nUsing Java 8:\nList: [abc, , bc, efg, abcd, , jkl]\nEmpty Strings: 2\nStrings of length 3: 3\nFiltered List: [abc, bc, efg, abcd, jkl]\nMerged String: abc, bc, efg, abcd, jkl\nSquares List: [9, 4, 49, 25]\nList: [1, 2, 13, 4, 15, 6, 17, 8, 19]\nHighest number in List : 19\nLowest number in List : 1\nSum of all numbers : 85\nAverage of all numbers : 9.444444444444445\nRandom Numbers:\n-1009474951\n-551240647\n-2484714\n181614550\n933444268\n1227850416\n1579250773\n1627454872\n1683033687\n1798939493\nEmpty Strings: 2\n" } ]
Universal Selector in CSS
The CSS * selector is a universal selector which is used to select all elements of the HTML DOM. The syntax for CSS universal selector is as follows βˆ’ * { /*declarations*/ } The following examples illustrate CSS universal selector βˆ’ Live Demo <!DOCTYPE html> <html> <head> <style> * { margin: 15px; padding: 5px; border: 2px solid black; box-shadow: inset 30px 0 8px lightblue; } </style> </head> <body> <table> <tr> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> </tr> </table> </body> </html> Live Demo <!DOCTYPE html> <html> <head> <style> * { margin: 15px; padding: 5px; width: 200px; border: 2px solid black; } html::before { content: "one"; } </style> </head> <body> two <div>three <div>four <div>five</div> </div> </div> </body> </html>
[ { "code": null, "e": 1159, "s": 1062, "text": "The CSS * selector is a universal selector which is used to select all elements of the HTML DOM." }, { "code": null, "e": 1213, "s": 1159, "text": "The syntax for CSS universal selector is as follows βˆ’" }, { "code": null, "e": 1239, "s": 1213, "text": "* {\n /*declarations*/\n}" }, { "code": null, "e": 1298, "s": 1239, "text": "The following examples illustrate CSS universal selector βˆ’" }, { "code": null, "e": 1309, "s": 1298, "text": " Live Demo" }, { "code": null, "e": 1597, "s": 1309, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n* {\n margin: 15px;\n padding: 5px;\n border: 2px solid black;\n box-shadow: inset 30px 0 8px lightblue;\n}\n</style>\n</head>\n<body>\n<table>\n<tr>\n<td></td>\n<td></td>\n</tr>\n<tr>\n<td></td>\n<td></td>\n<td></td>\n<td></td>\n</tr>\n</table>\n</body>\n</html>" }, { "code": null, "e": 1608, "s": 1597, "text": " Live Demo" }, { "code": null, "e": 1862, "s": 1608, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n* {\n margin: 15px;\n padding: 5px;\n width: 200px;\n border: 2px solid black;\n}\nhtml::before {\n content: \"one\";\n}\n</style>\n</head>\n<body>\ntwo\n<div>three\n<div>four\n<div>five</div>\n</div>\n</div>\n</body>\n</html>" } ]