title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
HTML - <frameset> Tag
The HTML <frameset> tag is used to divide the window into frames. This tag is not supported in HTML5. <!DOCTYPE html> <html> <head> <title>HTML frameset Tag</title> </head> <frameset cols = "200, *"> <frame src = "/html/menu.htm" name = "menu_page" /> <frame src = "/html/main.htm" name = "main_page" /> <noframes> <body> Your browser does not support frames. </body> </noframes> </frameset> </html> This will produce the following result, refer the image given below. The left frame is menu.htm and the right one is main.htm − Academic Tutorials Big Data & Analytics Computer Programming Computer Science Databases DevOps Digital Marketing Engineering Tutorials Exams Syllabus Famous Monuments GATE Exams Tutorials Latest Technologies Machine Learning Mainframe Development Management Tutorials Mathematics Tutorials Microsoft Technologies Misc tutorials Mobile Development Java Technologies Python Technologies SAP Tutorials Programming Scripts Selected Reading Software Quality Soft Skills Telecom Tutorials UPSC IAS Exams Web Development Sports Tutorials XML Technologies Multi-Language Interview Questions Academic Tutorials Big Data & Analytics Computer Programming Computer Science Databases DevOps Digital Marketing Engineering Tutorials Exams Syllabus Famous Monuments GATE Exams Tutorials Latest Technologies Machine Learning Mainframe Development Management Tutorials Mathematics Tutorials Microsoft Technologies Misc tutorials Mobile Development Java Technologies Python Technologies SAP Tutorials Programming Scripts Selected Reading Software Quality Soft Skills Telecom Tutorials UPSC IAS Exams Web Development Sports Tutorials XML Technologies Multi-Language Interview Questions HTML Tutorial HTML - Home HTML - Overview HTML - Basic Tags HTML - Elements HTML - Attributes HTML - Formatting HTML - Phrase Tags HTML - Meta Tags HTML - Comments HTML - Images HTML - Tables HTML - Lists HTML - Text Links HTML - Image Links HTML - Email Links HTML - Frames HTML - Iframes HTML - Blocks HTML - Backgrounds HTML - Colors HTML - Fonts HTML - Forms HTML - Embed Multimedia HTML - Marquees HTML - Header HTML - Style Sheet HTML - Javascript HTML - Layouts HTML References HTML - Tags Reference HTML - Attributes Reference HTML - Events Reference HTML - Fonts Reference HTML - ASCII Codes ASCII Table Lookup HTML - Color Names HTML - Entities HTML - Fonts Ref HTML - Events Ref MIME Media Types HTML - URL Encoding Language ISO Codes HTML - Character Encodings HTML - Deprecated Tags HTML Resources HTML - Quick Guide HTML - Useful Resources HTML - Color Code Builder HTML - Discussion HTML - Online Editor Selected Reading UPSC IAS Exams Notes Developer's Best Practices Questions and Answers Effective Resume Writing HR Interview Questions Computer Glossary Who is Who 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2476, "s": 2374, "text": "The HTML <frameset> tag is used to divide the window into frames. This tag is not supported in HTML5." }, { "code": null, "e": 2873, "s": 2476, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML frameset Tag</title>\n </head>\n \n <frameset cols = \"200, *\">\n <frame src = \"/html/menu.htm\" name = \"menu_page\" />\n <frame src = \"/html/main.htm\" name = \"main_page\" />\n \n <noframes>\n <body>\n Your browser does not support frames.\n </body>\n </noframes>\n \n </frameset> \n</html>" }, { "code": null, "e": 3001, "s": 2873, "text": "This will produce the following result, refer the image given below. The left frame is menu.htm and the right one is main.htm −" }, { "code": null, "e": 3648, "s": 3001, "text": "\n\n Academic Tutorials\n Big Data & Analytics \n Computer Programming \n Computer Science \n Databases \n DevOps \n Digital Marketing \n Engineering Tutorials \n Exams Syllabus \n Famous Monuments \n GATE Exams Tutorials\n Latest Technologies \n Machine Learning \n Mainframe Development \n Management Tutorials \n Mathematics Tutorials\n Microsoft Technologies \n Misc tutorials \n Mobile Development \n Java Technologies \n Python Technologies \n SAP Tutorials \nProgramming Scripts \n Selected Reading \n Software Quality \n Soft Skills \n Telecom Tutorials \n UPSC IAS Exams \n Web Development \n Sports Tutorials \n XML Technologies \n Multi-Language\n Interview Questions\n\n" }, { "code": null, "e": 3668, "s": 3648, "text": " Academic Tutorials" }, { "code": null, "e": 3691, "s": 3668, "text": " Big Data & Analytics " }, { "code": null, "e": 3714, "s": 3691, "text": " Computer Programming " }, { "code": null, "e": 3733, "s": 3714, "text": " Computer Science " }, { "code": null, "e": 3745, "s": 3733, "text": " Databases " }, { "code": null, "e": 3754, "s": 3745, "text": " DevOps " }, { "code": null, "e": 3774, "s": 3754, "text": " Digital Marketing " }, { "code": null, "e": 3798, "s": 3774, "text": " Engineering Tutorials " }, { "code": null, "e": 3815, "s": 3798, "text": " Exams Syllabus " }, { "code": null, "e": 3834, "s": 3815, "text": " Famous Monuments " }, { "code": null, "e": 3856, "s": 3834, "text": " GATE Exams Tutorials" }, { "code": null, "e": 3878, "s": 3856, "text": " Latest Technologies " }, { "code": null, "e": 3897, "s": 3878, "text": " Machine Learning " }, { "code": null, "e": 3921, "s": 3897, "text": " Mainframe Development " }, { "code": null, "e": 3944, "s": 3921, "text": " Management Tutorials " }, { "code": null, "e": 3967, "s": 3944, "text": " Mathematics Tutorials" }, { "code": null, "e": 3992, "s": 3967, "text": " Microsoft Technologies " }, { "code": null, "e": 4009, "s": 3992, "text": " Misc tutorials " }, { "code": null, "e": 4030, "s": 4009, "text": " Mobile Development " }, { "code": null, "e": 4050, "s": 4030, "text": " Java Technologies " }, { "code": null, "e": 4072, "s": 4050, "text": " Python Technologies " }, { "code": null, "e": 4088, "s": 4072, "text": " SAP Tutorials " }, { "code": null, "e": 4109, "s": 4088, "text": "Programming Scripts " }, { "code": null, "e": 4128, "s": 4109, "text": " Selected Reading " }, { "code": null, "e": 4147, "s": 4128, "text": " Software Quality " }, { "code": null, "e": 4161, "s": 4147, "text": " Soft Skills " }, { "code": null, "e": 4181, "s": 4161, "text": " Telecom Tutorials " }, { "code": null, "e": 4198, "s": 4181, "text": " UPSC IAS Exams " }, { "code": null, "e": 4216, "s": 4198, "text": " Web Development " }, { "code": null, "e": 4235, "s": 4216, "text": " Sports Tutorials " }, { "code": null, "e": 4254, "s": 4235, "text": " XML Technologies " }, { "code": null, "e": 4270, "s": 4254, "text": " Multi-Language" }, { "code": null, "e": 4291, "s": 4270, "text": " Interview Questions" }, { "code": null, "e": 4305, "s": 4291, "text": "HTML Tutorial" }, { "code": null, "e": 4317, "s": 4305, "text": "HTML - Home" }, { "code": null, "e": 4333, "s": 4317, "text": "HTML - Overview" }, { "code": null, "e": 4351, "s": 4333, "text": "HTML - Basic Tags" }, { "code": null, "e": 4367, "s": 4351, "text": "HTML - Elements" }, { "code": null, "e": 4385, "s": 4367, "text": "HTML - Attributes" }, { "code": null, "e": 4403, "s": 4385, "text": "HTML - Formatting" }, { "code": null, "e": 4422, "s": 4403, "text": "HTML - Phrase Tags" }, { "code": null, "e": 4439, "s": 4422, "text": "HTML - Meta Tags" }, { "code": null, "e": 4455, "s": 4439, "text": "HTML - Comments" }, { "code": null, "e": 4469, "s": 4455, "text": "HTML - Images" }, { "code": null, "e": 4483, "s": 4469, "text": "HTML - Tables" }, { "code": null, "e": 4496, "s": 4483, "text": "HTML - Lists" }, { "code": null, "e": 4514, "s": 4496, "text": "HTML - Text Links" }, { "code": null, "e": 4533, "s": 4514, "text": "HTML - Image Links" }, { "code": null, "e": 4552, "s": 4533, "text": "HTML - Email Links" }, { "code": null, "e": 4566, "s": 4552, "text": "HTML - Frames" }, { "code": null, "e": 4581, "s": 4566, "text": "HTML - Iframes" }, { "code": null, "e": 4595, "s": 4581, "text": "HTML - Blocks" }, { "code": null, "e": 4614, "s": 4595, "text": "HTML - Backgrounds" }, { "code": null, "e": 4628, "s": 4614, "text": "HTML - Colors" }, { "code": null, "e": 4641, "s": 4628, "text": "HTML - Fonts" }, { "code": null, "e": 4654, "s": 4641, "text": "HTML - Forms" }, { "code": null, "e": 4678, "s": 4654, "text": "HTML - Embed Multimedia" }, { "code": null, "e": 4694, "s": 4678, "text": "HTML - Marquees" }, { "code": null, "e": 4708, "s": 4694, "text": "HTML - Header" }, { "code": null, "e": 4727, "s": 4708, "text": "HTML - Style Sheet" }, { "code": null, "e": 4745, "s": 4727, "text": "HTML - Javascript" }, { "code": null, "e": 4760, "s": 4745, "text": "HTML - Layouts" }, { "code": null, "e": 4776, "s": 4760, "text": "HTML References" }, { "code": null, "e": 4798, "s": 4776, "text": "HTML - Tags Reference" }, { "code": null, "e": 4826, "s": 4798, "text": "HTML - Attributes Reference" }, { "code": null, "e": 4851, "s": 4826, "text": "HTML - Events Reference " }, { "code": null, "e": 4874, "s": 4851, "text": "HTML - Fonts Reference" }, { "code": null, "e": 4893, "s": 4874, "text": "HTML - ASCII Codes" }, { "code": null, "e": 4912, "s": 4893, "text": "ASCII Table Lookup" }, { "code": null, "e": 4931, "s": 4912, "text": "HTML - Color Names" }, { "code": null, "e": 4947, "s": 4931, "text": "HTML - Entities" }, { "code": null, "e": 4964, "s": 4947, "text": "HTML - Fonts Ref" }, { "code": null, "e": 4982, "s": 4964, "text": "HTML - Events Ref" }, { "code": null, "e": 4999, "s": 4982, "text": "MIME Media Types" }, { "code": null, "e": 5019, "s": 4999, "text": "HTML - URL Encoding" }, { "code": null, "e": 5038, "s": 5019, "text": "Language ISO Codes" }, { "code": null, "e": 5065, "s": 5038, "text": "HTML - Character Encodings" }, { "code": null, "e": 5088, "s": 5065, "text": "HTML - Deprecated Tags" }, { "code": null, "e": 5103, "s": 5088, "text": "HTML Resources" }, { "code": null, "e": 5122, "s": 5103, "text": "HTML - Quick Guide" }, { "code": null, "e": 5146, "s": 5122, "text": "HTML - Useful Resources" }, { "code": null, "e": 5172, "s": 5146, "text": "HTML - Color Code Builder" }, { "code": null, "e": 5190, "s": 5172, "text": "HTML - Discussion" }, { "code": null, "e": 5211, "s": 5190, "text": "HTML - Online Editor" }, { "code": null, "e": 5228, "s": 5211, "text": "Selected Reading" }, { "code": null, "e": 5249, "s": 5228, "text": "UPSC IAS Exams Notes" }, { "code": null, "e": 5276, "s": 5249, "text": "Developer's Best Practices" }, { "code": null, "e": 5298, "s": 5276, "text": "Questions and Answers" }, { "code": null, "e": 5323, "s": 5298, "text": "Effective Resume Writing" }, { "code": null, "e": 5346, "s": 5323, "text": "HR Interview Questions" }, { "code": null, "e": 5364, "s": 5346, "text": "Computer Glossary" }, { "code": null, "e": 5375, "s": 5364, "text": "Who is Who" }, { "code": null, "e": 5408, "s": 5375, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 5422, "s": 5408, "text": " Anadi Sharma" }, { "code": null, "e": 5457, "s": 5422, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5471, "s": 5457, "text": " Anadi Sharma" }, { "code": null, "e": 5506, "s": 5471, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5523, "s": 5506, "text": " Frahaan Hussain" }, { "code": null, "e": 5558, "s": 5523, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5589, "s": 5558, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 5622, "s": 5589, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 5653, "s": 5622, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 5688, "s": 5653, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5719, "s": 5688, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 5726, "s": 5719, "text": " Print" }, { "code": null, "e": 5737, "s": 5726, "text": " Add Notes" } ]
How to Create and Deploy a Machine Learning App to Heroku | by Chanin Nantasenamat | Towards Data Science
Deployment of a machine learning model is an important phase in the data life cycle. Such a model could be a minimum viable product (MVP) that would allow relevant stakeholders access to the model from which to test and experiment with, which could lead to valuable feedback for further model improvement. Model deployment may seem like a difficult and daunting task but it does not have to be. In this article, you will learn how to easily deploy a machine learning app to the cloud using Heroku. The advantage of deploying to Heroku is that we don’t have to worry about anything related to the underlying operating system (i.e. no more installing updates, dependencies or maintenance) on which the app is running on. It should be noted that this article has an accompanying video (How to Deploy Data Science Web App to Heroku) that can serve as a supplement or visual aid from which to refer to. Heroku is a platform as a service that deploy apps onto the cloud. The platform officially supports apps created by any of several programming languages such as Node.js, Ruby, Java, PHP, Python, Go, Scala and Clojure. It also supports other languages (such as R Shiny) through the use of third-party buildpacks. The advantage of using Heroku as opposed to creating your own virtual private server (VPS) running on Linux or Windows operating system is the time and overhead that comes along with maintain the server. Imagine the headache of dealing with software upgrades, dependencies and compatibility issues. For example, I have a Ubuntu server running several of my R Shiny apps, which is running perfectly fine but it is running on Ubuntu 14 and an older version of R, which means that it would not support newer R packages. Migrating all the apps to a new server seems to be an overwhelming task that I still procrastinate about to this very day. All of these concerns would no longer matter if using Heroku. The great thing is that you can get started for free with Heroku as they provide a free tier of about 550–1000 dyno hours per month. Dynos are isolated Linux containers and serves as the building blocks of Heroku’s offerings (more information on Heroku’s dynos here). They range in size from a small and economical dyno (offering fewer CPU processors and small RAM capacity) to larger and costlier dyno (unlimited CPU processors and up to 14 GB of RAM). The machine learning model that we are going to be deploying today is the Penguins Species classification model. In essence, the model will use innate physical characteristics of penguins (e.g. bill length, bill depth, flipper length and body mass) along with their gender and geographical location as input parameters (i.e. the X variables) in order to classify penguins as belonging to one of three species (e.g. Adelie, Gentoo and Chinstrap) which is the Y variable. A cartoon illustration of the modeling workflow is summarized in the image on the left. Now, that we have seen the schematic workflow of how the model is built, let’s now take a look at the code. In this simple example, we’re going to use the random forest algorithm for classifying penguins as belonging to one of three species (Adelie, Gentoo and Chinstrap) as also mentioned above. Line 1 — Import the pandas library which will subsequently be used to store values of the penguins dataset. Line 2 — Read in the penguins dataset from a CSV file using the pd.read_csv() function and store the contents to the penguins variable. Lines 4 and 5 — Commented text to describe that the code block underneath will be performing ordinal feature encoding Line 6 — Copy the contents from the penguins variable to the newly created df variable. Line 7 — Assign the column name 'species' found in the df dataframe that we will use as the Y variable. Line 8 — Create a list of ordinal features to be encoded and assign it to the encode variable. Lines 10–13 — Here, the ordinal features will be encoded. The for loop is used to iterate through the 2 features to be encoded as follows: — Perform one hot encoding via the pd.get_dummies() function and concatenate the newly generated one hot encoded values as new columns into the df dataframe. — Finally, delete the original column from the df dataframe. Lines 15–19 — The species column which will be used as the Y variable will now be converted to numerical form via numerical mapping whereby the class label (Adelie, Chinstrap and Gentoo) are mapped to numerical values (0, 1 and 2) as shown in line 15. A simple custom function is created to perform this numerical mapping (lines 16 and 17), which will be applied on line 19. The mapped values are then assigned to the 'species' column of the df dataframe. Lines 21–23 — The df dataframe will now be separated into the X and Y variables as performed on lines 22 and 23, respectively. Lines 25–28 — This block of code will now build the random forest model as commented on Line 25. This starts by importing the RandomForestClassifier function from the sklearn.ensemble sub-module. The model is instantiated on Line 27 whereby the RandomForestClassifier() function is assigned to the clf variable. The model is finally trained on Line 28 via clf.fit() function using X and Y variables as the input data. Line 30–32 — Finally, we’re going to save the model by serializing it with the pickle library where the pickle.dump() function will save the trained model stored in the clf variable into a file called penguins_clf.pkl. We now have the trained model saved from scikit-learn, which we will now use for model deployment. Full details and line-by-line explanation on building the Penguins web app in Python using the Streamlit library is provided in the prior article (below). towardsdatascience.com Let’s now build the Penguins app using the Streamlit library. The code for building the app is provided in the penguins-app.py file shown below. This app will make use of the trained model (penguins_clf.pkl) for predicting the class label (the Penguin’s species as being Adelie, Chinstrap or Gentoo) by using input parameters from the sidebar panel of the web app’s front-end. We are going to launch the app locally on our own computer. Firstly, make sure you have streamlit installed and if you haven’t already you can do so using the following commands: pip install streamlit In the terminal, we can now launch the app (the penguins-app.py file) using the commands shown below: streamlit run penguins-app.py In a short moment we should see the following output in the terminal. > streamlit run penguins-app.pyYou can now view your Streamlit app in your browser.Local URL: http://localhost:8501Network URL: http://10.0.0.11:8501 Then a browser should pop up, giving us the Penguins app. Now that the web app works locally, we will now proceed to deploying it onto the cloud. Firstly, we will create a new repository on GitHub and we will name the repository to be penguins_heroku, which can be entered into the text box for Repository name. Then tick on Add a README file and click on Create repository. Secondly, we will upload the trained model (penguins_clf.pkl) and the web app (penguins-app.py) to this new GitHub repository. This can be done by clicking on Add file > Upload files. Then choose and upload the above 2 files (penguins_clf.pkl and penguins-app.py). From the above screenshot, you will see that in addition to the 2 uploaded file we have 5 additional files (Procfile, penguins_example.csv, requirements.txt, setup.sh and runtime.txt) that we will have to create and place inside this repository as well. To create a new file directly on GitHub, we can click on Add file > Create new file. In the example below we will create one of the four files mentioned above, which we will start with creating the Procfile file: Then, scroll to the bottom of the page and click on the Commit new file button. Afterwards, you should notice the addition of the Procfile to the repository. Repeat this for the 4 remaining files consisting of penguins_example.csv, requirements.txt, setup.sh and runtime.txt. Let’s now proceed to deploying the model by heading over to the Heroku website to sign up (if you haven’t already) and log in. To sign up for a free Heroku account find the “Sign up” button at the top right hand corner of the Heroku website as shown below. After sign up, log into your Heroku account. To create a new app, click on New > Create new app button as shown in the screenshot below. Now, we’re going to give the app a name, here we will use penguins-model which is still available. It should be noted that if an App name is already taken you will see an error message, if so then you can choose a new name. To proceed, click on the Create app button at the bottom. We’re now going to connect our App to the GitHub repository. To do this click on GitHub (Connect to GitHub) as shown in the screenshot below. If this is your first time deploying to Heroku, you will have to authenticate your GitHub account and give Heroku permission to access it. This is done once per Heroku account. Now, type in the name of the GitHub repository that you have just created into the text box and click on Connect. If this was successful, you’ll see the Connected to dataprofessor/penguins-heroku message. It should be noted that we can activate Automatic deploys but this is recommended after Manual deploy is successful. Thus, we can come back and activate this later. Now, scroll down and click on the Deploy Branch button. The build log will update as the container is provisioned and prerequisite libraries are being installed. After the container have been provisioned and libraries have been installed successfully, you should see the message Your app was successfully deployed. Now, click on the View button to launch the deployed web app. If you see the web app with no error message, congratulations! You have now successfully deployed the Penguins App. Click on the following link if you would like to see a Demo of the Penguins App. I work full-time as an Associate Professor of Bioinformatics and Head of Data Mining and Biomedical Informatics at a Research University in Thailand. In my after work hours, I’m a YouTuber (AKA the Data Professor) making online videos about data science. In all tutorial videos that I make, I also share Jupyter notebooks on GitHub (Data Professor GitHub page). www.youtube.com ✅ YouTube: http://youtube.com/dataprofessor/✅ Website: http://dataprofessor.org/ (Under construction)✅ LinkedIn: https://www.linkedin.com/company/dataprofessor/✅ Twitter: https://twitter.com/thedataprof/✅ FaceBook: http://facebook.com/dataprofessor/✅ GitHub: https://github.com/dataprofessor/✅ Instagram: https://www.instagram.com/data.professor/
[ { "code": null, "e": 477, "s": 171, "text": "Deployment of a machine learning model is an important phase in the data life cycle. Such a model could be a minimum viable product (MVP) that would allow relevant stakeholders access to the model from which to test and experiment with, which could lead to valuable feedback for further model improvement." }, { "code": null, "e": 890, "s": 477, "text": "Model deployment may seem like a difficult and daunting task but it does not have to be. In this article, you will learn how to easily deploy a machine learning app to the cloud using Heroku. The advantage of deploying to Heroku is that we don’t have to worry about anything related to the underlying operating system (i.e. no more installing updates, dependencies or maintenance) on which the app is running on." }, { "code": null, "e": 1069, "s": 890, "text": "It should be noted that this article has an accompanying video (How to Deploy Data Science Web App to Heroku) that can serve as a supplement or visual aid from which to refer to." }, { "code": null, "e": 1381, "s": 1069, "text": "Heroku is a platform as a service that deploy apps onto the cloud. The platform officially supports apps created by any of several programming languages such as Node.js, Ruby, Java, PHP, Python, Go, Scala and Clojure. It also supports other languages (such as R Shiny) through the use of third-party buildpacks." }, { "code": null, "e": 1680, "s": 1381, "text": "The advantage of using Heroku as opposed to creating your own virtual private server (VPS) running on Linux or Windows operating system is the time and overhead that comes along with maintain the server. Imagine the headache of dealing with software upgrades, dependencies and compatibility issues." }, { "code": null, "e": 2216, "s": 1680, "text": "For example, I have a Ubuntu server running several of my R Shiny apps, which is running perfectly fine but it is running on Ubuntu 14 and an older version of R, which means that it would not support newer R packages. Migrating all the apps to a new server seems to be an overwhelming task that I still procrastinate about to this very day. All of these concerns would no longer matter if using Heroku. The great thing is that you can get started for free with Heroku as they provide a free tier of about 550–1000 dyno hours per month." }, { "code": null, "e": 2537, "s": 2216, "text": "Dynos are isolated Linux containers and serves as the building blocks of Heroku’s offerings (more information on Heroku’s dynos here). They range in size from a small and economical dyno (offering fewer CPU processors and small RAM capacity) to larger and costlier dyno (unlimited CPU processors and up to 14 GB of RAM)." }, { "code": null, "e": 2650, "s": 2537, "text": "The machine learning model that we are going to be deploying today is the Penguins Species classification model." }, { "code": null, "e": 3007, "s": 2650, "text": "In essence, the model will use innate physical characteristics of penguins (e.g. bill length, bill depth, flipper length and body mass) along with their gender and geographical location as input parameters (i.e. the X variables) in order to classify penguins as belonging to one of three species (e.g. Adelie, Gentoo and Chinstrap) which is the Y variable." }, { "code": null, "e": 3095, "s": 3007, "text": "A cartoon illustration of the modeling workflow is summarized in the image on the left." }, { "code": null, "e": 3203, "s": 3095, "text": "Now, that we have seen the schematic workflow of how the model is built, let’s now take a look at the code." }, { "code": null, "e": 3392, "s": 3203, "text": "In this simple example, we’re going to use the random forest algorithm for classifying penguins as belonging to one of three species (Adelie, Gentoo and Chinstrap) as also mentioned above." }, { "code": null, "e": 3500, "s": 3392, "text": "Line 1 — Import the pandas library which will subsequently be used to store values of the penguins dataset." }, { "code": null, "e": 3636, "s": 3500, "text": "Line 2 — Read in the penguins dataset from a CSV file using the pd.read_csv() function and store the contents to the penguins variable." }, { "code": null, "e": 3754, "s": 3636, "text": "Lines 4 and 5 — Commented text to describe that the code block underneath will be performing ordinal feature encoding" }, { "code": null, "e": 3842, "s": 3754, "text": "Line 6 — Copy the contents from the penguins variable to the newly created df variable." }, { "code": null, "e": 3946, "s": 3842, "text": "Line 7 — Assign the column name 'species' found in the df dataframe that we will use as the Y variable." }, { "code": null, "e": 4041, "s": 3946, "text": "Line 8 — Create a list of ordinal features to be encoded and assign it to the encode variable." }, { "code": null, "e": 4399, "s": 4041, "text": "Lines 10–13 — Here, the ordinal features will be encoded. The for loop is used to iterate through the 2 features to be encoded as follows: — Perform one hot encoding via the pd.get_dummies() function and concatenate the newly generated one hot encoded values as new columns into the df dataframe. — Finally, delete the original column from the df dataframe." }, { "code": null, "e": 4855, "s": 4399, "text": "Lines 15–19 — The species column which will be used as the Y variable will now be converted to numerical form via numerical mapping whereby the class label (Adelie, Chinstrap and Gentoo) are mapped to numerical values (0, 1 and 2) as shown in line 15. A simple custom function is created to perform this numerical mapping (lines 16 and 17), which will be applied on line 19. The mapped values are then assigned to the 'species' column of the df dataframe." }, { "code": null, "e": 4982, "s": 4855, "text": "Lines 21–23 — The df dataframe will now be separated into the X and Y variables as performed on lines 22 and 23, respectively." }, { "code": null, "e": 5400, "s": 4982, "text": "Lines 25–28 — This block of code will now build the random forest model as commented on Line 25. This starts by importing the RandomForestClassifier function from the sklearn.ensemble sub-module. The model is instantiated on Line 27 whereby the RandomForestClassifier() function is assigned to the clf variable. The model is finally trained on Line 28 via clf.fit() function using X and Y variables as the input data." }, { "code": null, "e": 5619, "s": 5400, "text": "Line 30–32 — Finally, we’re going to save the model by serializing it with the pickle library where the pickle.dump() function will save the trained model stored in the clf variable into a file called penguins_clf.pkl." }, { "code": null, "e": 5718, "s": 5619, "text": "We now have the trained model saved from scikit-learn, which we will now use for model deployment." }, { "code": null, "e": 5873, "s": 5718, "text": "Full details and line-by-line explanation on building the Penguins web app in Python using the Streamlit library is provided in the prior article (below)." }, { "code": null, "e": 5896, "s": 5873, "text": "towardsdatascience.com" }, { "code": null, "e": 6273, "s": 5896, "text": "Let’s now build the Penguins app using the Streamlit library. The code for building the app is provided in the penguins-app.py file shown below. This app will make use of the trained model (penguins_clf.pkl) for predicting the class label (the Penguin’s species as being Adelie, Chinstrap or Gentoo) by using input parameters from the sidebar panel of the web app’s front-end." }, { "code": null, "e": 6452, "s": 6273, "text": "We are going to launch the app locally on our own computer. Firstly, make sure you have streamlit installed and if you haven’t already you can do so using the following commands:" }, { "code": null, "e": 6474, "s": 6452, "text": "pip install streamlit" }, { "code": null, "e": 6576, "s": 6474, "text": "In the terminal, we can now launch the app (the penguins-app.py file) using the commands shown below:" }, { "code": null, "e": 6606, "s": 6576, "text": "streamlit run penguins-app.py" }, { "code": null, "e": 6676, "s": 6606, "text": "In a short moment we should see the following output in the terminal." }, { "code": null, "e": 6826, "s": 6676, "text": "> streamlit run penguins-app.pyYou can now view your Streamlit app in your browser.Local URL: http://localhost:8501Network URL: http://10.0.0.11:8501" }, { "code": null, "e": 6884, "s": 6826, "text": "Then a browser should pop up, giving us the Penguins app." }, { "code": null, "e": 6972, "s": 6884, "text": "Now that the web app works locally, we will now proceed to deploying it onto the cloud." }, { "code": null, "e": 7201, "s": 6972, "text": "Firstly, we will create a new repository on GitHub and we will name the repository to be penguins_heroku, which can be entered into the text box for Repository name. Then tick on Add a README file and click on Create repository." }, { "code": null, "e": 7466, "s": 7201, "text": "Secondly, we will upload the trained model (penguins_clf.pkl) and the web app (penguins-app.py) to this new GitHub repository. This can be done by clicking on Add file > Upload files. Then choose and upload the above 2 files (penguins_clf.pkl and penguins-app.py)." }, { "code": null, "e": 7720, "s": 7466, "text": "From the above screenshot, you will see that in addition to the 2 uploaded file we have 5 additional files (Procfile, penguins_example.csv, requirements.txt, setup.sh and runtime.txt) that we will have to create and place inside this repository as well." }, { "code": null, "e": 7805, "s": 7720, "text": "To create a new file directly on GitHub, we can click on Add file > Create new file." }, { "code": null, "e": 7933, "s": 7805, "text": "In the example below we will create one of the four files mentioned above, which we will start with creating the Procfile file:" }, { "code": null, "e": 8091, "s": 7933, "text": "Then, scroll to the bottom of the page and click on the Commit new file button. Afterwards, you should notice the addition of the Procfile to the repository." }, { "code": null, "e": 8209, "s": 8091, "text": "Repeat this for the 4 remaining files consisting of penguins_example.csv, requirements.txt, setup.sh and runtime.txt." }, { "code": null, "e": 8336, "s": 8209, "text": "Let’s now proceed to deploying the model by heading over to the Heroku website to sign up (if you haven’t already) and log in." }, { "code": null, "e": 8466, "s": 8336, "text": "To sign up for a free Heroku account find the “Sign up” button at the top right hand corner of the Heroku website as shown below." }, { "code": null, "e": 8511, "s": 8466, "text": "After sign up, log into your Heroku account." }, { "code": null, "e": 8603, "s": 8511, "text": "To create a new app, click on New > Create new app button as shown in the screenshot below." }, { "code": null, "e": 8827, "s": 8603, "text": "Now, we’re going to give the app a name, here we will use penguins-model which is still available. It should be noted that if an App name is already taken you will see an error message, if so then you can choose a new name." }, { "code": null, "e": 8885, "s": 8827, "text": "To proceed, click on the Create app button at the bottom." }, { "code": null, "e": 9027, "s": 8885, "text": "We’re now going to connect our App to the GitHub repository. To do this click on GitHub (Connect to GitHub) as shown in the screenshot below." }, { "code": null, "e": 9204, "s": 9027, "text": "If this is your first time deploying to Heroku, you will have to authenticate your GitHub account and give Heroku permission to access it. This is done once per Heroku account." }, { "code": null, "e": 9318, "s": 9204, "text": "Now, type in the name of the GitHub repository that you have just created into the text box and click on Connect." }, { "code": null, "e": 9574, "s": 9318, "text": "If this was successful, you’ll see the Connected to dataprofessor/penguins-heroku message. It should be noted that we can activate Automatic deploys but this is recommended after Manual deploy is successful. Thus, we can come back and activate this later." }, { "code": null, "e": 9630, "s": 9574, "text": "Now, scroll down and click on the Deploy Branch button." }, { "code": null, "e": 9736, "s": 9630, "text": "The build log will update as the container is provisioned and prerequisite libraries are being installed." }, { "code": null, "e": 9889, "s": 9736, "text": "After the container have been provisioned and libraries have been installed successfully, you should see the message Your app was successfully deployed." }, { "code": null, "e": 9951, "s": 9889, "text": "Now, click on the View button to launch the deployed web app." }, { "code": null, "e": 10148, "s": 9951, "text": "If you see the web app with no error message, congratulations! You have now successfully deployed the Penguins App. Click on the following link if you would like to see a Demo of the Penguins App." }, { "code": null, "e": 10510, "s": 10148, "text": "I work full-time as an Associate Professor of Bioinformatics and Head of Data Mining and Biomedical Informatics at a Research University in Thailand. In my after work hours, I’m a YouTuber (AKA the Data Professor) making online videos about data science. In all tutorial videos that I make, I also share Jupyter notebooks on GitHub (Data Professor GitHub page)." }, { "code": null, "e": 10526, "s": 10510, "text": "www.youtube.com" } ]
How to pass values between Fragments in Android?
This example demonstrates how do I pass values between fragments in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#574706" tools:context=".MainActivity"> <fragment android:layout_width="wrap_content" android:layout_height="wrap_content" android:name="app.com.sample.FragmentOne" android:id="@+id/fragment" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" tools:layout="@layout/fragment_fragment_one" /> <fragment android:layout_width="wrap_content" android:layout_height="wrap_content" android:name="app.com.sample.FragmentTwo" android:id="@+id/fragment2" android:layout_below="@+id/fragment" android:layout_centerHorizontal="true" android:layout_marginTop="41dp" tools:layout="@layout/fragment_fragment_two" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends AppCompatActivity implements FragmentOne.OnFragmentInteractionListener{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.textUpdate) { return true; } return super.onOptionsItemSelected(item); } @Override public void onFragmentInteraction(String userContent) { FragmentTwo fragmentTwo = (FragmentTwo) getSupportFragmentManager().findFragmentById(R.id.fragment2); fragmentTwo.updateTextField(userContent); } } Step 4 − Create two fragments (FragmentOne and FragmentTwo) and add the following code − a) FragmentOne.java import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class FragmentOne extends Fragment { private OnFragmentInteractionListener mListener; private EditText userInput; private String userData; public FragmentOne() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_fragment_one, container, false); userInput = view.findViewById(R.id.userInput); Button update = view.findViewById(R.id.button); update.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(userInput.getText().toString().equals("")){ Toast.makeText(getActivity(), "User input value must be filled", Toast.LENGTH_LONG).show(); return; } userData = userInput.getText().toString(); onButtonPressed(userData); } }); return view; } public void onButtonPressed(String userContent) { if (mListener != null) { mListener.onFragmentInteraction(userContent); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnFragmentInteractionListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } public interface OnFragmentInteractionListener { void onFragmentInteraction(String userContent); } } fragment_fragment_one.xml − <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="4dp" android:paddingBottom="32dp"> <EditText android:id="@+id/userInput" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="16dp" android:ems="10" android:inputType="text"> <requestFocus /> </EditText> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_below="@id/userInput" android:layout_marginTop="20dp" android:padding="16dp" android:elevation="4dp" android:text="Update" /> </RelativeLayout> b) FragmentTwo.java import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class FragmentTwo extends Fragment { private TextView updateText; public FragmentTwo() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_fragment_two, container, false); updateText = view.findViewById(R.id.textUpdate); return view; } public void updateTextField(String newText){ updateText.setText(newText); } } fragment_fragment_two − <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/textUpdate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="" android:textSize="24sp" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:textStyle="bold" android:layout_marginTop="32dp" /> </RelativeLayout> Step 5 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
[ { "code": null, "e": 1139, "s": 1062, "text": "This example demonstrates how do I pass values between fragments in android." }, { "code": null, "e": 1268, "s": 1139, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1333, "s": 1268, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2305, "s": 1333, "text": "<RelativeLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:background=\"#574706\"\n tools:context=\".MainActivity\">\n <fragment\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:name=\"app.com.sample.FragmentOne\"\n android:id=\"@+id/fragment\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\"\n tools:layout=\"@layout/fragment_fragment_one\" />\n <fragment\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:name=\"app.com.sample.FragmentTwo\"\n android:id=\"@+id/fragment2\"\n android:layout_below=\"@+id/fragment\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"41dp\"\n tools:layout=\"@layout/fragment_fragment_two\" />\n</RelativeLayout>" }, { "code": null, "e": 2362, "s": 2305, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3380, "s": 2362, "text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.Menu;\nimport android.view.MenuItem;\npublic class MainActivity extends AppCompatActivity implements FragmentOne.OnFragmentInteractionListener{\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n getMenuInflater().inflate(R.menu.menu_main, menu);\n return true;\n }\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n int id = item.getItemId();\n if (id == R.id.textUpdate) {\n return true;\n }\n return super.onOptionsItemSelected(item);\n }\n @Override\n public void onFragmentInteraction(String userContent) {\n FragmentTwo fragmentTwo =\n (FragmentTwo)\n getSupportFragmentManager().findFragmentById(R.id.fragment2);\n fragmentTwo.updateTextField(userContent);\n }\n}" }, { "code": null, "e": 3469, "s": 3380, "text": "Step 4 − Create two fragments (FragmentOne and FragmentTwo) and add the following code −" }, { "code": null, "e": 3489, "s": 3469, "text": "a) FragmentOne.java" }, { "code": null, "e": 5434, "s": 3489, "text": "import android.app.Activity;\nimport android.os.Bundle;\nimport android.support.v4.app.Fragment;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.Toast;\npublic class FragmentOne extends Fragment {\n private OnFragmentInteractionListener mListener;\n private EditText userInput;\n private String userData;\n public FragmentOne() {\n }\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n View view = inflater.inflate(R.layout.fragment_fragment_one, container, false);\n userInput = view.findViewById(R.id.userInput);\n Button update = view.findViewById(R.id.button);\n update.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if(userInput.getText().toString().equals(\"\")){\n Toast.makeText(getActivity(), \"User input value must be filled\",\n Toast.LENGTH_LONG).show();\n return;\n }\n userData = userInput.getText().toString();\n onButtonPressed(userData);\n }\n });\n return view;\n }\n public void onButtonPressed(String userContent) {\n if (mListener != null) {\n mListener.onFragmentInteraction(userContent);\n }\n }\n @Override\n public void onAttach(Activity activity) {\n super.onAttach(activity);\n try {\n mListener = (OnFragmentInteractionListener) activity;\n } catch (ClassCastException e) {\n throw new ClassCastException(activity.toString() + \" must implement\n OnFragmentInteractionListener\");\n }\n }\n @Override\n public void onDetach() {\n super.onDetach();\n mListener = null;\n }\n public interface OnFragmentInteractionListener {\n void onFragmentInteraction(String userContent);\n }\n}" }, { "code": null, "e": 5462, "s": 5434, "text": "fragment_fragment_one.xml −" }, { "code": null, "e": 6428, "s": 5462, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"4dp\"\n android:paddingBottom=\"32dp\">\n <EditText\n android:id=\"@+id/userInput\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"16dp\"\n android:ems=\"10\"\n android:inputType=\"text\">\n <requestFocus />\n </EditText>\n <Button\n android:id=\"@+id/button\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_below=\"@id/userInput\"\n android:layout_marginTop=\"20dp\"\n android:padding=\"16dp\"\n android:elevation=\"4dp\"\n android:text=\"Update\" />\n</RelativeLayout>" }, { "code": null, "e": 6448, "s": 6428, "text": "b) FragmentTwo.java" }, { "code": null, "e": 7123, "s": 6448, "text": "import android.os.Bundle;\nimport android.support.v4.app.Fragment;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.TextView;\npublic class FragmentTwo extends Fragment {\n private TextView updateText;\n public FragmentTwo() {\n }\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n View view =\n inflater.inflate(R.layout.fragment_fragment_two, container, false);\n updateText = view.findViewById(R.id.textUpdate);\n return view;\n }\n public void updateTextField(String newText){\n updateText.setText(newText);\n }\n}" }, { "code": null, "e": 7147, "s": 7123, "text": "fragment_fragment_two −" }, { "code": null, "e": 7707, "s": 7147, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\">\n <TextView\n android:id=\"@+id/textUpdate\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"\"\n android:textSize=\"24sp\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\"\n android:textStyle=\"bold\"\n android:layout_marginTop=\"32dp\" />\n</RelativeLayout>" }, { "code": null, "e": 7762, "s": 7707, "text": "Step 5 − Add the following code to androidManifest.xml" }, { "code": null, "e": 8468, "s": 7762, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action\n android:name=\"android.intent.action.MAIN\" />\n <category\n android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 8814, "s": 8468, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" } ]
C++ Program to Check if it is a Sparse Matrix
A sparse matrix is a matrix in which majority of the elements are 0. In other words, if more than half of the elements in the matrix are 0, it is known as a sparse matrix. For example − The matrix given below contains 5 zeroes. Since the number of zeroes is more than half the elements of the matrix, it is a sparse matrix. 1 0 2 5 0 0 0 0 9 A program to check if it is a sparse matrix or not is as follows. Live Demo #include<iostream> using namespace std; int main () { int a[10][10] = { {2, 0, 0} , {0, 3, 8} , {0, 9, 0} }; int i, j, count = 0; int r = 3, c = 3; for (i = 0; i < r; ++i) { for (j = 0; j < c; ++j) { if (a[i][j] == 0) count++; } } cout<<"The matrix is:"<<endl; for (i = 0; i < r; ++i) { for (j = 0; j < c; ++j) { cout<<a[i][j]<<" "; } cout<<endl; } cout<<"There are "<<count<<" zeros in the matrix"<<endl; if (count > ((r * c)/ 2)) cout<<"This is a sparse matrix"<<endl; else cout<<"This is not a sparse matrix"<<endl; return 0; } The matrix is: 2 0 0 0 3 8 0 9 0 There are 5 zeros in the matrix This is a sparse matrix In the above program, a nested for loop is used to count the number of zeros in the matrix. This is demonstrated using the following code snippet. for (i = 0; i < r; ++i) { for (j = 0; j < c; ++j) { if (a[i][j] == 0) count++; } } After finding the number of zeros, the matrix is displayed using a nested for loop. This is shown below − cout<<"The matrix is:"<<endl; for (i = 0; i < r; ++i) { for (j = 0; j < c; ++j) { cout<<a[i][j]<<" "; } cout<<endl; } Finally, the number of zeroes are displayed. If the count of zeros is more than half the elements in the matrix, then it is displayed that the matrix is a sparse matrix otherwise the matrix is not a sparse matrix. cout<<"There are "<<count<<" zeros in the matrix"<<endl; if (count > ((r * c)/ 2)) cout<<"This is a sparse matrix"<<endl; else cout<<"This is not a sparse matrix"<<endl;
[ { "code": null, "e": 1248, "s": 1062, "text": "A sparse matrix is a matrix in which majority of the elements are 0. In other words, if more than half of the elements in the matrix are 0, it is known as a sparse matrix. For example −" }, { "code": null, "e": 1386, "s": 1248, "text": "The matrix given below contains 5 zeroes. Since the number of zeroes is more than half the elements of the matrix, it is a sparse matrix." }, { "code": null, "e": 1404, "s": 1386, "text": "1 0 2\n5 0 0\n0 0 9" }, { "code": null, "e": 1470, "s": 1404, "text": "A program to check if it is a sparse matrix or not is as follows." }, { "code": null, "e": 1481, "s": 1470, "text": " Live Demo" }, { "code": null, "e": 2111, "s": 1481, "text": "#include<iostream>\nusing namespace std;\nint main () {\n int a[10][10] = { {2, 0, 0} , {0, 3, 8} , {0, 9, 0} };\n int i, j, count = 0;\n int r = 3, c = 3;\n for (i = 0; i < r; ++i) {\n for (j = 0; j < c; ++j) {\n if (a[i][j] == 0)\n count++;\n }\n }\n cout<<\"The matrix is:\"<<endl;\n for (i = 0; i < r; ++i) {\n for (j = 0; j < c; ++j) {\n cout<<a[i][j]<<\" \";\n }\n cout<<endl;\n }\n cout<<\"There are \"<<count<<\" zeros in the matrix\"<<endl;\n if (count > ((r * c)/ 2))\n cout<<\"This is a sparse matrix\"<<endl;\n else\n cout<<\"This is not a sparse matrix\"<<endl;\n return 0;\n}" }, { "code": null, "e": 2200, "s": 2111, "text": "The matrix is:\n2 0 0\n0 3 8\n0 9 0\nThere are 5 zeros in the matrix\nThis is a sparse matrix" }, { "code": null, "e": 2347, "s": 2200, "text": "In the above program, a nested for loop is used to count the number of zeros in the matrix. This is demonstrated using the following code snippet." }, { "code": null, "e": 2448, "s": 2347, "text": "for (i = 0; i < r; ++i) {\n for (j = 0; j < c; ++j) {\n if (a[i][j] == 0)\n count++;\n }\n}" }, { "code": null, "e": 2554, "s": 2448, "text": "After finding the number of zeros, the matrix is displayed using a nested for loop. This is shown below −" }, { "code": null, "e": 2687, "s": 2554, "text": "cout<<\"The matrix is:\"<<endl;\nfor (i = 0; i < r; ++i) {\n for (j = 0; j < c; ++j) {\n cout<<a[i][j]<<\" \";\n }\n cout<<endl;\n}" }, { "code": null, "e": 2901, "s": 2687, "text": "Finally, the number of zeroes are displayed. If the count of zeros is more than half the elements in the matrix, then it is displayed that the matrix is a sparse matrix otherwise the matrix is not a sparse matrix." }, { "code": null, "e": 3071, "s": 2901, "text": "cout<<\"There are \"<<count<<\" zeros in the matrix\"<<endl;\nif (count > ((r * c)/ 2))\ncout<<\"This is a sparse matrix\"<<endl;\nelse\ncout<<\"This is not a sparse matrix\"<<endl;" } ]
7 Tips To Maximize PyTorch Performance | by William Falcon | Towards Data Science
Throughout the last 10 months, while working on PyTorch Lightning, the team and I have been exposed to many styles of structuring PyTorch code and we have identified a few key places where we see people inadvertently introducing bottlenecks. We’ve taken great care to make sure that PyTorch Lightning does not make any of these mistakes for the code we automate for you, and we even try to correct it for users when we detect them. However, since Lightning is just structured PyTorch and you still control all of the scientific PyTorch, there’s not much we can do in many cases for the user. In addition, if you’re not using Lightning, you might inadvertently introduce these issues into your code. To help you train the faster, here are 8 tips you should be aware of that might be slowing down your code. This first mistake is an easy one to correct. PyTorch allows loading data on multiple processes simultaneously (documentation). In this case, PyTorch can bypass the GIL lock by processing 8 batches, each on a separate process. How many workers should you use? A good rule of thumb is: num_worker = 4 * num_GPU This answer has a good discussion about this. Warning: The downside is that your memory usage will also increase (source). You know how sometimes your GPU memory shows that it’s full but you’re pretty sure that your model isn’t using that much? That overhead is called pinned memory. ie: this memory has been reserved as a type of “working allocation.” When you enable pinned_memory in a DataLoader it “automatically puts the fetched data Tensors in pinned memory, and enables faster data transfer to CUDA-enabled GPUs” (source). This also means you should not unnecessarily call: torch.cuda.empty_cache() # bad.cpu().item().numpy() I see heavy usage of the .item() or .cpu() or .numpy() calls. This is really bad for performance because every one of these calls transfers data from GPU to CPU and dramatically slows your performance. If you’re trying to clear up the attached computational graph, use .detach() instead. # good.detach() This won’t transfer memory to GPU and it will remove any computational graphs attached to that variable. Most people create tensors on GPUs like this t = tensor.rand(2,2).cuda() However, this first creates CPU tensor, and THEN transfers it to GPU... this is really slow. Instead, create the tensor directly on the device you want. t = tensor.rand(2,2, device=torch.device('cuda:0')) If you’re using Lightning, we automatically put your model and the batch on the correct GPU for you. But, if you create a new tensor inside your code somewhere (ie: sample random noise for a VAE, or something like that), then you must put the tensor yourself. t = tensor.rand(2,2, device=self.device) Every LightningModule has a convenient self.device call which works whether you are on CPU, multiple GPUs, or TPUs (ie: lightning will choose the right device for that tensor. PyTorch has two main models for training on multiple GPUs. The first, DataParallel (DP), splits a batch across multiple GPUs. But this also means that the model has to be copied to each GPU and once gradients are calculated on GPU 0, they must be synced to the other GPUs. That’s a lot of GPU transfers which are expensive! Instead, DistributedDataParallel (DDP)creates a siloed copy of the model on each GPU (in its own process), and makes only a portion of the data available to that GPU. Then its like having N independent models training, except that once each one calculates the gradients, they all sync gradients across models... this means we only transfer data across GPUs once during each batch. In Lightning, you can trivially switch between both Trainer(distributed_backend='ddp', gpus=8)Trainer(distributed_backend='dp', gpus=8) Note that both PyTorch and Lightning, discourage DP use. This is another way to speed up training which we don’t see many people using. In 16-bit training parts of your model and your data go from 32-bit numbers to 16-bit numbers. This has a few advantages: You use half the memory (which means you can double batch size and cut training time in half).Certain GPUs (V100, 2080Ti) give you automatic speed-ups (3x-8x faster) because they are optimized for 16-bit computations. You use half the memory (which means you can double batch size and cut training time in half). Certain GPUs (V100, 2080Ti) give you automatic speed-ups (3x-8x faster) because they are optimized for 16-bit computations. In Lightning this is trivial to enable: Trainer(precision=16) Note: Before PyTorch 1.6 you ALSO had to install Nvidia Apex... now 16-bit is native to PyTorch. But if you’re using Lightning, it supports both and automatically switches depending on the detected PyTorch version. This last tip may be hard to do without Lightning, but you can use things like the cprofiler to do. However, in Lightning you can get a summary of all the calls made during training in two ways: First, the built-in basic profiler Trainer(profile=True) Which gives an output like this: or the advanced profiler: profiler = AdvancedProfiler()trainer = Trainer(profiler=profiler) which gets very granular The full documentation for the Lightning profiler can be found here. PyTorch Lightning is nothing more than structured PyTorch. If you’re ready to have most of these tips automated for you (and well tested), then check out this video on refactoring your PyTorch code into the Lightning format!
[ { "code": null, "e": 414, "s": 172, "text": "Throughout the last 10 months, while working on PyTorch Lightning, the team and I have been exposed to many styles of structuring PyTorch code and we have identified a few key places where we see people inadvertently introducing bottlenecks." }, { "code": null, "e": 764, "s": 414, "text": "We’ve taken great care to make sure that PyTorch Lightning does not make any of these mistakes for the code we automate for you, and we even try to correct it for users when we detect them. However, since Lightning is just structured PyTorch and you still control all of the scientific PyTorch, there’s not much we can do in many cases for the user." }, { "code": null, "e": 871, "s": 764, "text": "In addition, if you’re not using Lightning, you might inadvertently introduce these issues into your code." }, { "code": null, "e": 978, "s": 871, "text": "To help you train the faster, here are 8 tips you should be aware of that might be slowing down your code." }, { "code": null, "e": 1106, "s": 978, "text": "This first mistake is an easy one to correct. PyTorch allows loading data on multiple processes simultaneously (documentation)." }, { "code": null, "e": 1263, "s": 1106, "text": "In this case, PyTorch can bypass the GIL lock by processing 8 batches, each on a separate process. How many workers should you use? A good rule of thumb is:" }, { "code": null, "e": 1288, "s": 1263, "text": "num_worker = 4 * num_GPU" }, { "code": null, "e": 1334, "s": 1288, "text": "This answer has a good discussion about this." }, { "code": null, "e": 1411, "s": 1334, "text": "Warning: The downside is that your memory usage will also increase (source)." }, { "code": null, "e": 1641, "s": 1411, "text": "You know how sometimes your GPU memory shows that it’s full but you’re pretty sure that your model isn’t using that much? That overhead is called pinned memory. ie: this memory has been reserved as a type of “working allocation.”" }, { "code": null, "e": 1818, "s": 1641, "text": "When you enable pinned_memory in a DataLoader it “automatically puts the fetched data Tensors in pinned memory, and enables faster data transfer to CUDA-enabled GPUs” (source)." }, { "code": null, "e": 1869, "s": 1818, "text": "This also means you should not unnecessarily call:" }, { "code": null, "e": 1894, "s": 1869, "text": "torch.cuda.empty_cache()" }, { "code": null, "e": 1921, "s": 1894, "text": "# bad.cpu().item().numpy()" }, { "code": null, "e": 2123, "s": 1921, "text": "I see heavy usage of the .item() or .cpu() or .numpy() calls. This is really bad for performance because every one of these calls transfers data from GPU to CPU and dramatically slows your performance." }, { "code": null, "e": 2209, "s": 2123, "text": "If you’re trying to clear up the attached computational graph, use .detach() instead." }, { "code": null, "e": 2225, "s": 2209, "text": "# good.detach()" }, { "code": null, "e": 2330, "s": 2225, "text": "This won’t transfer memory to GPU and it will remove any computational graphs attached to that variable." }, { "code": null, "e": 2375, "s": 2330, "text": "Most people create tensors on GPUs like this" }, { "code": null, "e": 2403, "s": 2375, "text": "t = tensor.rand(2,2).cuda()" }, { "code": null, "e": 2556, "s": 2403, "text": "However, this first creates CPU tensor, and THEN transfers it to GPU... this is really slow. Instead, create the tensor directly on the device you want." }, { "code": null, "e": 2608, "s": 2556, "text": "t = tensor.rand(2,2, device=torch.device('cuda:0'))" }, { "code": null, "e": 2868, "s": 2608, "text": "If you’re using Lightning, we automatically put your model and the batch on the correct GPU for you. But, if you create a new tensor inside your code somewhere (ie: sample random noise for a VAE, or something like that), then you must put the tensor yourself." }, { "code": null, "e": 2909, "s": 2868, "text": "t = tensor.rand(2,2, device=self.device)" }, { "code": null, "e": 3085, "s": 2909, "text": "Every LightningModule has a convenient self.device call which works whether you are on CPU, multiple GPUs, or TPUs (ie: lightning will choose the right device for that tensor." }, { "code": null, "e": 3358, "s": 3085, "text": "PyTorch has two main models for training on multiple GPUs. The first, DataParallel (DP), splits a batch across multiple GPUs. But this also means that the model has to be copied to each GPU and once gradients are calculated on GPU 0, they must be synced to the other GPUs." }, { "code": null, "e": 3790, "s": 3358, "text": "That’s a lot of GPU transfers which are expensive! Instead, DistributedDataParallel (DDP)creates a siloed copy of the model on each GPU (in its own process), and makes only a portion of the data available to that GPU. Then its like having N independent models training, except that once each one calculates the gradients, they all sync gradients across models... this means we only transfer data across GPUs once during each batch." }, { "code": null, "e": 3842, "s": 3790, "text": "In Lightning, you can trivially switch between both" }, { "code": null, "e": 3926, "s": 3842, "text": "Trainer(distributed_backend='ddp', gpus=8)Trainer(distributed_backend='dp', gpus=8)" }, { "code": null, "e": 3983, "s": 3926, "text": "Note that both PyTorch and Lightning, discourage DP use." }, { "code": null, "e": 4184, "s": 3983, "text": "This is another way to speed up training which we don’t see many people using. In 16-bit training parts of your model and your data go from 32-bit numbers to 16-bit numbers. This has a few advantages:" }, { "code": null, "e": 4402, "s": 4184, "text": "You use half the memory (which means you can double batch size and cut training time in half).Certain GPUs (V100, 2080Ti) give you automatic speed-ups (3x-8x faster) because they are optimized for 16-bit computations." }, { "code": null, "e": 4497, "s": 4402, "text": "You use half the memory (which means you can double batch size and cut training time in half)." }, { "code": null, "e": 4621, "s": 4497, "text": "Certain GPUs (V100, 2080Ti) give you automatic speed-ups (3x-8x faster) because they are optimized for 16-bit computations." }, { "code": null, "e": 4661, "s": 4621, "text": "In Lightning this is trivial to enable:" }, { "code": null, "e": 4683, "s": 4661, "text": "Trainer(precision=16)" }, { "code": null, "e": 4898, "s": 4683, "text": "Note: Before PyTorch 1.6 you ALSO had to install Nvidia Apex... now 16-bit is native to PyTorch. But if you’re using Lightning, it supports both and automatically switches depending on the detected PyTorch version." }, { "code": null, "e": 5093, "s": 4898, "text": "This last tip may be hard to do without Lightning, but you can use things like the cprofiler to do. However, in Lightning you can get a summary of all the calls made during training in two ways:" }, { "code": null, "e": 5128, "s": 5093, "text": "First, the built-in basic profiler" }, { "code": null, "e": 5150, "s": 5128, "text": "Trainer(profile=True)" }, { "code": null, "e": 5183, "s": 5150, "text": "Which gives an output like this:" }, { "code": null, "e": 5209, "s": 5183, "text": "or the advanced profiler:" }, { "code": null, "e": 5275, "s": 5209, "text": "profiler = AdvancedProfiler()trainer = Trainer(profiler=profiler)" }, { "code": null, "e": 5300, "s": 5275, "text": "which gets very granular" }, { "code": null, "e": 5369, "s": 5300, "text": "The full documentation for the Lightning profiler can be found here." }, { "code": null, "e": 5428, "s": 5369, "text": "PyTorch Lightning is nothing more than structured PyTorch." } ]
SWING - SpringLayout Class
The class SpringLayout positions the children of its associated container according to a set of constraints. Following is the declaration for javax.swing.SpringLayout class − public class SpringLayout extends Object implements LayoutManager2 Following are the fields for javax.swing.SpringLayout class − static String BASELINE − Specifies the baseline of a component. static String BASELINE − Specifies the baseline of a component. static String EAST − Specifies the right edge of a component's bounding rectangle. static String EAST − Specifies the right edge of a component's bounding rectangle. static String HEIGHT − Specifies the height of a component's bounding rectangle. static String HEIGHT − Specifies the height of a component's bounding rectangle. static String HORIZONTAL_CENTER − Specifies the horizontal center of a component's bounding rectangle. static String HORIZONTAL_CENTER − Specifies the horizontal center of a component's bounding rectangle. static String NORTH − Specifies the top edge of a component's bounding rectangle. static String NORTH − Specifies the top edge of a component's bounding rectangle. static String SOUTH − Specifies the bottom edge of a component's bounding rectangle. static String SOUTH − Specifies the bottom edge of a component's bounding rectangle. static String VERTICAL_CENTER − Specifies the vertical center of a component's bounding rectangle. static String VERTICAL_CENTER − Specifies the vertical center of a component's bounding rectangle. static String WEST − Specifies the left edge of a component's bounding rectangle. static String WEST − Specifies the left edge of a component's bounding rectangle. static String WIDTH − Specifies the width of a component's bounding rectangle. static String WIDTH − Specifies the width of a component's bounding rectangle. SpringLayout() Creates a new SpringLayout. void addLayoutComponent(Component component, Object constraints) If constraints is an instance of SpringLayout.Constraints, associates the constraints with the specified component. void addLayoutComponent(String name, Component c) Has no effect, since this layout manager does not use a per-component string. Spring getConstraint(String edgeName, Component c) Returns the spring controlling the distance between the specified edge of the component and the top or left edge of its parent. SpringLayout.Constraints getConstraints(Component c) Returns the constraints for the specified component. float getLayoutAlignmentX(Container p) Returns 0.5f (centered). float getLayoutAlignmentY(Container p) Returns 0.5f (centered). void invalidateLayout(Container p) Invalidates the layout, indicating that if the layout manager has cached information it should be discarded. void layoutContainer(Container parent) Lays out the specified container. Dimension maximumLayoutSize(Container parent) Calculates the maximum size dimensions for the specified container, given the components it contains. Dimension minimumLayoutSize(Container parent) Calculates the minimum size dimensions for the specified container, given the components it contains. Dimension preferredLayoutSize(Container parent) Calculates the preferred size dimensions for the specified container, given the components it contains. void putConstraint(String e1, Component c1, int pad, String e2, Component c2) Links edge e1 of component c1 to edge e2 of component c2, with a fixed distance between the edges. void putConstraint(String e1, Component c1, Spring s, String e2, Component c2) Links edge e1 of component c1 to edge e2 of component c2. void removeLayoutComponent(Component c) Removes the constraints associated with the specified component. This class inherits methods from the following class − java.lang.Object Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui > SwingLayoutDemo.java import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SwingSpringLayout { private JFrame mainFrame; private JLabel headerLabel; private JLabel statusLabel; private JPanel controlPanel; public SwingSpringLayout(){ prepareGUI(); } public static void main(String[] args){ SwingSpringLayout swingLayoutDemo = new SwingSpringLayout(); swingLayoutDemo.showSpringLayoutDemo(); } private void prepareGUI(){ mainFrame = new JFrame("Java SWING Examples"); mainFrame.setSize(400,400); mainFrame.setLayout(new GridLayout(3, 1)); headerLabel = new JLabel("",JLabel.CENTER ); statusLabel = new JLabel("",JLabel.CENTER); statusLabel.setSize(350,100); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); controlPanel = new JPanel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); } private void showSpringLayoutDemo(){ headerLabel.setText("Layout in action: SpringLayout"); SpringLayout layout = new SpringLayout(); JPanel panel = new JPanel(); panel.setLayout(layout); JLabel label = new JLabel("Enter Name: "); JTextField textField = new JTextField("", 15); panel.add(label); panel.add(textField); layout.putConstraint(SpringLayout.WEST, label,5, SpringLayout.WEST, controlPanel); layout.putConstraint(SpringLayout.NORTH, label,5, SpringLayout.NORTH, controlPanel); layout.putConstraint(SpringLayout.WEST, textField,5, SpringLayout.EAST, label); layout.putConstraint(SpringLayout.NORTH, textField,5, SpringLayout.NORTH, controlPanel); layout.putConstraint(SpringLayout.EAST, panel,5, SpringLayout.EAST, textField); layout.putConstraint(SpringLayout.SOUTH, panel,5, SpringLayout.SOUTH, textField); controlPanel.add(panel); mainFrame.setVisible(true); } } Compile the program using the command prompt. Go to D:/ > SWING and type the following command. D:\SWING>javac com\tutorialspoint\gui\SwingLayoutDemo.java If no error occurs, it means the compilation is successful. Run the program using the following command. D:\SWING>java com.tutorialspoint.gui.SwingLayoutDemo Verify the following output. 30 Lectures 3.5 hours Pranjal Srivastava 13 Lectures 1 hours Pranjal Srivastava 25 Lectures 4.5 hours Emenwa Global, Ejike IfeanyiChukwu 14 Lectures 1.5 hours Travis Rose 14 Lectures 1 hours Travis Rose Print Add Notes Bookmark this page
[ { "code": null, "e": 1872, "s": 1763, "text": "The class SpringLayout positions the children of its associated container according to a set of constraints." }, { "code": null, "e": 1938, "s": 1872, "text": "Following is the declaration for javax.swing.SpringLayout class −" }, { "code": null, "e": 2015, "s": 1938, "text": "public class SpringLayout\n extends Object\n implements LayoutManager2\n" }, { "code": null, "e": 2077, "s": 2015, "text": "Following are the fields for javax.swing.SpringLayout class −" }, { "code": null, "e": 2141, "s": 2077, "text": "static String BASELINE − Specifies the baseline of a component." }, { "code": null, "e": 2205, "s": 2141, "text": "static String BASELINE − Specifies the baseline of a component." }, { "code": null, "e": 2288, "s": 2205, "text": "static String EAST − Specifies the right edge of a component's bounding rectangle." }, { "code": null, "e": 2371, "s": 2288, "text": "static String EAST − Specifies the right edge of a component's bounding rectangle." }, { "code": null, "e": 2452, "s": 2371, "text": "static String HEIGHT − Specifies the height of a component's bounding rectangle." }, { "code": null, "e": 2533, "s": 2452, "text": "static String HEIGHT − Specifies the height of a component's bounding rectangle." }, { "code": null, "e": 2636, "s": 2533, "text": "static String HORIZONTAL_CENTER − Specifies the horizontal center of a component's bounding rectangle." }, { "code": null, "e": 2739, "s": 2636, "text": "static String HORIZONTAL_CENTER − Specifies the horizontal center of a component's bounding rectangle." }, { "code": null, "e": 2821, "s": 2739, "text": "static String NORTH − Specifies the top edge of a component's bounding rectangle." }, { "code": null, "e": 2903, "s": 2821, "text": "static String NORTH − Specifies the top edge of a component's bounding rectangle." }, { "code": null, "e": 2988, "s": 2903, "text": "static String SOUTH − Specifies the bottom edge of a component's bounding rectangle." }, { "code": null, "e": 3073, "s": 2988, "text": "static String SOUTH − Specifies the bottom edge of a component's bounding rectangle." }, { "code": null, "e": 3172, "s": 3073, "text": "static String VERTICAL_CENTER − Specifies the vertical center of a component's bounding rectangle." }, { "code": null, "e": 3271, "s": 3172, "text": "static String VERTICAL_CENTER − Specifies the vertical center of a component's bounding rectangle." }, { "code": null, "e": 3353, "s": 3271, "text": "static String WEST − Specifies the left edge of a component's bounding rectangle." }, { "code": null, "e": 3435, "s": 3353, "text": "static String WEST − Specifies the left edge of a component's bounding rectangle." }, { "code": null, "e": 3514, "s": 3435, "text": "static String WIDTH − Specifies the width of a component's bounding rectangle." }, { "code": null, "e": 3593, "s": 3514, "text": "static String WIDTH − Specifies the width of a component's bounding rectangle." }, { "code": null, "e": 3608, "s": 3593, "text": "SpringLayout()" }, { "code": null, "e": 3636, "s": 3608, "text": "Creates a new SpringLayout." }, { "code": null, "e": 3701, "s": 3636, "text": "void addLayoutComponent(Component component, Object constraints)" }, { "code": null, "e": 3817, "s": 3701, "text": "If constraints is an instance of SpringLayout.Constraints, associates the constraints with the specified component." }, { "code": null, "e": 3867, "s": 3817, "text": "void addLayoutComponent(String name, Component c)" }, { "code": null, "e": 3945, "s": 3867, "text": "Has no effect, since this layout manager does not use a per-component string." }, { "code": null, "e": 3996, "s": 3945, "text": "Spring getConstraint(String edgeName, Component c)" }, { "code": null, "e": 4124, "s": 3996, "text": "Returns the spring controlling the distance between the specified edge of the component and the top or left edge of its parent." }, { "code": null, "e": 4177, "s": 4124, "text": "SpringLayout.Constraints getConstraints(Component c)" }, { "code": null, "e": 4230, "s": 4177, "text": "Returns the constraints for the specified component." }, { "code": null, "e": 4269, "s": 4230, "text": "float getLayoutAlignmentX(Container p)" }, { "code": null, "e": 4294, "s": 4269, "text": "Returns 0.5f (centered)." }, { "code": null, "e": 4333, "s": 4294, "text": "float getLayoutAlignmentY(Container p)" }, { "code": null, "e": 4358, "s": 4333, "text": "Returns 0.5f (centered)." }, { "code": null, "e": 4393, "s": 4358, "text": "void invalidateLayout(Container p)" }, { "code": null, "e": 4502, "s": 4393, "text": "Invalidates the layout, indicating that if the layout manager has cached information it should be discarded." }, { "code": null, "e": 4541, "s": 4502, "text": "void layoutContainer(Container parent)" }, { "code": null, "e": 4575, "s": 4541, "text": "Lays out the specified container." }, { "code": null, "e": 4621, "s": 4575, "text": "Dimension maximumLayoutSize(Container parent)" }, { "code": null, "e": 4723, "s": 4621, "text": "Calculates the maximum size dimensions for the specified container, given the components it contains." }, { "code": null, "e": 4769, "s": 4723, "text": "Dimension minimumLayoutSize(Container parent)" }, { "code": null, "e": 4871, "s": 4769, "text": "Calculates the minimum size dimensions for the specified container, given the components it contains." }, { "code": null, "e": 4919, "s": 4871, "text": "Dimension preferredLayoutSize(Container parent)" }, { "code": null, "e": 5023, "s": 4919, "text": "Calculates the preferred size dimensions for the specified container, given the components it contains." }, { "code": null, "e": 5101, "s": 5023, "text": "void putConstraint(String e1, Component c1, int pad, String e2, Component c2)" }, { "code": null, "e": 5200, "s": 5101, "text": "Links edge e1 of component c1 to edge e2 of component c2, with a fixed distance between the edges." }, { "code": null, "e": 5279, "s": 5200, "text": "void putConstraint(String e1, Component c1, Spring s, String e2, Component c2)" }, { "code": null, "e": 5337, "s": 5279, "text": "Links edge e1 of component c1 to edge e2 of component c2." }, { "code": null, "e": 5377, "s": 5337, "text": "void removeLayoutComponent(Component c)" }, { "code": null, "e": 5442, "s": 5377, "text": "Removes the constraints associated with the specified component." }, { "code": null, "e": 5497, "s": 5442, "text": "This class inherits methods from the following class −" }, { "code": null, "e": 5514, "s": 5497, "text": "java.lang.Object" }, { "code": null, "e": 5630, "s": 5514, "text": "Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >" }, { "code": null, "e": 5651, "s": 5630, "text": "SwingLayoutDemo.java" }, { "code": null, "e": 7819, "s": 5651, "text": "import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\n\npublic class SwingSpringLayout {\n private JFrame mainFrame;\n private JLabel headerLabel;\n private JLabel statusLabel;\n private JPanel controlPanel;\n\n public SwingSpringLayout(){\n prepareGUI();\n }\n public static void main(String[] args){\n SwingSpringLayout swingLayoutDemo = new SwingSpringLayout(); \n swingLayoutDemo.showSpringLayoutDemo(); \n }\n private void prepareGUI(){\n mainFrame = new JFrame(\"Java SWING Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n\n headerLabel = new JLabel(\"\",JLabel.CENTER );\n statusLabel = new JLabel(\"\",JLabel.CENTER); \n statusLabel.setSize(350,100);\n \n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n });\n\t\tcontrolPanel = new JPanel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n private void showSpringLayoutDemo(){\n headerLabel.setText(\"Layout in action: SpringLayout\"); \n SpringLayout layout = new SpringLayout();\n\n JPanel panel = new JPanel();\n panel.setLayout(layout);\n JLabel label = new JLabel(\"Enter Name: \");\n JTextField textField = new JTextField(\"\", 15);\n panel.add(label);\n panel.add(textField);\n\n layout.putConstraint(SpringLayout.WEST, label,5, SpringLayout.WEST, controlPanel);\n layout.putConstraint(SpringLayout.NORTH, label,5, SpringLayout.NORTH, controlPanel);\n layout.putConstraint(SpringLayout.WEST, textField,5, SpringLayout.EAST, label);\n layout.putConstraint(SpringLayout.NORTH, textField,5, SpringLayout.NORTH, \n controlPanel);\n \n layout.putConstraint(SpringLayout.EAST, panel,5, SpringLayout.EAST, textField);\n layout.putConstraint(SpringLayout.SOUTH, panel,5, SpringLayout.SOUTH, textField);\n controlPanel.add(panel);\n mainFrame.setVisible(true); \n } \n}" }, { "code": null, "e": 7915, "s": 7819, "text": "Compile the program using the command prompt. Go to D:/ > SWING and type the following command." }, { "code": null, "e": 7975, "s": 7915, "text": "D:\\SWING>javac com\\tutorialspoint\\gui\\SwingLayoutDemo.java\n" }, { "code": null, "e": 8080, "s": 7975, "text": "If no error occurs, it means the compilation is successful. Run the program using the following command." }, { "code": null, "e": 8134, "s": 8080, "text": "D:\\SWING>java com.tutorialspoint.gui.SwingLayoutDemo\n" }, { "code": null, "e": 8163, "s": 8134, "text": "Verify the following output." }, { "code": null, "e": 8198, "s": 8163, "text": "\n 30 Lectures \n 3.5 hours \n" }, { "code": null, "e": 8218, "s": 8198, "text": " Pranjal Srivastava" }, { "code": null, "e": 8251, "s": 8218, "text": "\n 13 Lectures \n 1 hours \n" }, { "code": null, "e": 8271, "s": 8251, "text": " Pranjal Srivastava" }, { "code": null, "e": 8306, "s": 8271, "text": "\n 25 Lectures \n 4.5 hours \n" }, { "code": null, "e": 8342, "s": 8306, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 8377, "s": 8342, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8390, "s": 8377, "text": " Travis Rose" }, { "code": null, "e": 8423, "s": 8390, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 8436, "s": 8423, "text": " Travis Rose" }, { "code": null, "e": 8443, "s": 8436, "text": " Print" }, { "code": null, "e": 8454, "s": 8443, "text": " Add Notes" } ]
How to search Python dictionary for matching key?
If you have the exact key you want to find, then you can simply use the [] operator or get the function to get the value associated with this key. For example, a = { 'foo': 45, 'bar': 22 } print(a['foo']) print(a.get('foo')) This will give the output: 45 45 If you have a substring that you want to search in the dict, you can use substring search on the keys list and if you find it, use the value. For example, a = { 'foo': 45, 'bar': 22 } for key in a.keys(): if key.find('oo') > -1: print(a[key]) This will give the output 45
[ { "code": null, "e": 1222, "s": 1062, "text": "If you have the exact key you want to find, then you can simply use the [] operator or get the function to get the value associated with this key. For example," }, { "code": null, "e": 1293, "s": 1222, "text": "a = {\n 'foo': 45,\n 'bar': 22\n}\nprint(a['foo'])\nprint(a.get('foo'))" }, { "code": null, "e": 1320, "s": 1293, "text": "This will give the output:" }, { "code": null, "e": 1326, "s": 1320, "text": "45\n45" }, { "code": null, "e": 1481, "s": 1326, "text": "If you have a substring that you want to search in the dict, you can use substring search on the keys list and if you find it, use the value. For example," }, { "code": null, "e": 1584, "s": 1481, "text": "a = {\n 'foo': 45,\n 'bar': 22\n}\nfor key in a.keys():\n if key.find('oo') > -1:\n print(a[key])" }, { "code": null, "e": 1610, "s": 1584, "text": "This will give the output" }, { "code": null, "e": 1613, "s": 1610, "text": "45" } ]
Text and File processing using sed Linux Commands
Sed is a stream editor. A stream editor is used to participate in normal textual content transformations on an enter a file. At the same time in some approaches much like an editor which allows scripted edits (comparable to ed). sed works by means of making only one cross over on the input(s) and is more efficient. Now, let us explore more about – “Text and File processing using sed Linux Commands”. Firstly, to verify the sed version, use the following command – $ sed --v The sample output should be like this – sed (GNU sed) 4.2.2 Copyright (C) 2012 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later . This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. ......................................................................................... In the below example, abc.txt is the file name. In this article, we have learnt about – Learn Text and File processing using sed Linux Commands. In our next articles, we will come up with more Linux based tricks and tips. Keep reading!
[ { "code": null, "e": 1465, "s": 1062, "text": "Sed is a stream editor. A stream editor is used to participate in normal textual content transformations on an enter a file. At the same time in some approaches much like an editor which allows scripted edits (comparable to ed). sed works by means of making only one cross over on the input(s) and is more efficient. Now, let us explore more about – “Text and File processing using sed Linux Commands”." }, { "code": null, "e": 1529, "s": 1465, "text": "Firstly, to verify the sed version, use the following command –" }, { "code": null, "e": 1539, "s": 1529, "text": "$ sed --v" }, { "code": null, "e": 1579, "s": 1539, "text": "The sample output should be like this –" }, { "code": null, "e": 1954, "s": 1579, "text": "sed (GNU sed) 4.2.2\nCopyright (C) 2012 Free Software Foundation, Inc.\nLicense GPLv3+: GNU GPL version 3 or later .\nThis is free software: you are free to change and redistribute it.\nThere is NO WARRANTY, to the extent permitted by law.\n.........................................................................................\n\nIn the below example, abc.txt is the file name." }, { "code": null, "e": 2142, "s": 1954, "text": "In this article, we have learnt about – Learn Text and File processing using sed Linux Commands. In our next articles, we will come up with more Linux based tricks and tips. Keep reading!" } ]
Object Slicing in C++
Object slicing is used to describe the situation when you assign an object of a derived class to an instance of a base class. This causes a loss of methods and member variables for the derived class object. This is termed as information being sliced away. For example, class Foo { int a; }; class Bar : public Foo { int b; } Since Bar extends Foo, it now has 2 member variables, a and b. So if you create a variable bar of type Bar and then create a variable of type Foo and assign bar, you'll lose the member variable b in the process. For example, Bar bar; Foo foo = bar; In this case, the information in for about b is lost in a bar. This is known as member slicing.
[ { "code": null, "e": 1331, "s": 1062, "text": "Object slicing is used to describe the situation when you assign an object of a derived class to an instance of a base class. This causes a loss of methods and member variables for the derived class object. This is termed as information being sliced away. For example," }, { "code": null, "e": 1393, "s": 1331, "text": "class Foo {\n int a;\n};\nclass Bar : public Foo {\n int b;\n}" }, { "code": null, "e": 1618, "s": 1393, "text": "Since Bar extends Foo, it now has 2 member variables, a and b. So if you create a variable bar of type Bar and then create a variable of type Foo and assign bar, you'll lose the member variable b in the process. For example," }, { "code": null, "e": 1642, "s": 1618, "text": "Bar bar;\nFoo foo = bar;" }, { "code": null, "e": 1738, "s": 1642, "text": "In this case, the information in for about b is lost in a bar. This is known as member slicing." } ]
HTML - Colors
Colors are very important to give a good look and feel to your website. You can specify colors on page level using <body> tag or you can set colors for individual tags using bgcolor attribute. The <body> tag has following attributes which can be used to set different colors − bgcolor − sets a color for the background of the page. bgcolor − sets a color for the background of the page. text − sets a color for the body text. text − sets a color for the body text. alink − sets a color for active links or selected links. alink − sets a color for active links or selected links. link − sets a color for linked text. link − sets a color for linked text. vlink − sets a color for visited links − that is, for linked text that you have already clicked on. vlink − sets a color for visited links − that is, for linked text that you have already clicked on. There are following three different methods to set colors in your web page − Color names − You can specify color names directly like green, blue or red. Color names − You can specify color names directly like green, blue or red. Hex codes − A six-digit code representing the amount of red, green, and blue that makes up the color. Hex codes − A six-digit code representing the amount of red, green, and blue that makes up the color. Color decimal or percentage values − This value is specified using the rgb( ) property. Color decimal or percentage values − This value is specified using the rgb( ) property. Now we will see these coloring schemes one by one. You can specify direct a color name to set text or background color. W3C has listed 16 basic color names that will validate with an HTML validator but there are over 200 different color names supported by major browsers. Note − Check a complete list of HTML Color Name. Here is the list of W3C Standard 16 Colors names and it is recommended to use them. Here are the examples to set background of an HTML tag by color name − <!DOCTYPE html> <html> <head> <title>HTML Colors by Name</title> </head> <body text = "blue" bgcolor = "green"> <p>Use different color names for for body and table and see the result.</p> <table bgcolor = "black"> <tr> <td> <font color = "white">This text will appear white on black background.</font> </td> </tr> </table> </body> </html> A hexadecimal is a 6 digit representation of a color. The first two digits(RR) represent a red value, the next two are a green value(GG), and the last are the blue value(BB). A hexadecimal value can be taken from any graphics software like Adobe Photoshop, Paintshop Pro or MS Paint. Each hexadecimal code will be preceded by a pound or hash sign #. Following is a list of few colors using hexadecimal notation. Here are the examples to set background of an HTML tag by color code in hexadecimal − <!DOCTYPE html> <html> <head> <title>HTML Colors by Hex</title> </head> <body text = "#0000FF" bgcolor = "#00FF00"> <p>Use different color hexa for for body and table and see the result.</p> <table bgcolor = "#000000"> <tr> <td> <font color = "#FFFFFF">This text will appear white on black background.</font> </td> </tr> </table> </body> </html> This color value is specified using the rgb( ) property. This property takes three values, one each for red, green, and blue. The value can be an integer between 0 and 255 or a percentage. Note − All the browsers does not support rgb() property of color so it is recommended not to use it. Following is a list to show few colors using RGB values. Here are the examples to set background of an HTML tag by color code using rgb() values − <!DOCTYPE html> <html> <head> <title>HTML Colors by RGB code</title> </head> <body text = "rgb(0,0,255)" bgcolor = "rgb(0,255,0)"> <p>Use different color code for for body and table and see the result.</p> <table bgcolor = "rgb(0,0,0)"> <tr> <td> <font color = "rgb(255,255,255)">This text will appear white on black background.</font> </td> </tr> </table> </body> </html> Here is the list of 216 colors which are supposed to be safest and computer independent colors. These colors very from hexa code 000000 to FFFFFF and they will be supported by all the computers having 256 color palette. 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2567, "s": 2374, "text": "Colors are very important to give a good look and feel to your website. You can specify colors on page level using <body> tag or you can set colors for individual tags using bgcolor attribute." }, { "code": null, "e": 2651, "s": 2567, "text": "The <body> tag has following attributes which can be used to set different colors −" }, { "code": null, "e": 2706, "s": 2651, "text": "bgcolor − sets a color for the background of the page." }, { "code": null, "e": 2761, "s": 2706, "text": "bgcolor − sets a color for the background of the page." }, { "code": null, "e": 2800, "s": 2761, "text": "text − sets a color for the body text." }, { "code": null, "e": 2839, "s": 2800, "text": "text − sets a color for the body text." }, { "code": null, "e": 2896, "s": 2839, "text": "alink − sets a color for active links or selected links." }, { "code": null, "e": 2953, "s": 2896, "text": "alink − sets a color for active links or selected links." }, { "code": null, "e": 2990, "s": 2953, "text": "link − sets a color for linked text." }, { "code": null, "e": 3027, "s": 2990, "text": "link − sets a color for linked text." }, { "code": null, "e": 3127, "s": 3027, "text": "vlink − sets a color for visited links − that is, for linked text that you have already clicked on." }, { "code": null, "e": 3227, "s": 3127, "text": "vlink − sets a color for visited links − that is, for linked text that you have already clicked on." }, { "code": null, "e": 3304, "s": 3227, "text": "There are following three different methods to set colors in your web page −" }, { "code": null, "e": 3380, "s": 3304, "text": "Color names − You can specify color names directly like green, blue or red." }, { "code": null, "e": 3456, "s": 3380, "text": "Color names − You can specify color names directly like green, blue or red." }, { "code": null, "e": 3558, "s": 3456, "text": "Hex codes − A six-digit code representing the amount of red, green, and blue that makes up the color." }, { "code": null, "e": 3660, "s": 3558, "text": "Hex codes − A six-digit code representing the amount of red, green, and blue that makes up the color." }, { "code": null, "e": 3748, "s": 3660, "text": "Color decimal or percentage values − This value is specified using the rgb( ) property." }, { "code": null, "e": 3836, "s": 3748, "text": "Color decimal or percentage values − This value is specified using the rgb( ) property." }, { "code": null, "e": 3887, "s": 3836, "text": "Now we will see these coloring schemes one by one." }, { "code": null, "e": 4108, "s": 3887, "text": "You can specify direct a color name to set text or background color. W3C has listed 16 basic color names that will validate with an HTML validator but there are over 200 different color names supported by major browsers." }, { "code": null, "e": 4157, "s": 4108, "text": "Note − Check a complete list of HTML Color Name." }, { "code": null, "e": 4241, "s": 4157, "text": "Here is the list of W3C Standard 16 Colors names and it is recommended to use them." }, { "code": null, "e": 4312, "s": 4241, "text": "Here are the examples to set background of an HTML tag by color name −" }, { "code": null, "e": 4758, "s": 4312, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML Colors by Name</title>\n </head>\n\t\n <body text = \"blue\" bgcolor = \"green\">\n <p>Use different color names for for body and table and see the result.</p>\n \n <table bgcolor = \"black\">\n <tr>\n <td>\n <font color = \"white\">This text will appear white on black background.</font>\n </td>\n </tr>\n </table>\n </body>\n \n</html>" }, { "code": null, "e": 4933, "s": 4758, "text": "A hexadecimal is a 6 digit representation of a color. The first two digits(RR) represent a red value, the next two are a green value(GG), and the last are the blue value(BB)." }, { "code": null, "e": 5042, "s": 4933, "text": "A hexadecimal value can be taken from any graphics software like Adobe Photoshop, Paintshop Pro or MS Paint." }, { "code": null, "e": 5170, "s": 5042, "text": "Each hexadecimal code will be preceded by a pound or hash sign #. Following is a list of few colors using hexadecimal notation." }, { "code": null, "e": 5256, "s": 5170, "text": "Here are the examples to set background of an HTML tag by color code in hexadecimal −" }, { "code": null, "e": 5709, "s": 5256, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML Colors by Hex</title>\n </head>\n\t\n <body text = \"#0000FF\" bgcolor = \"#00FF00\">\n <p>Use different color hexa for for body and table and see the result.</p>\n \n <table bgcolor = \"#000000\">\n <tr>\n <td>\n <font color = \"#FFFFFF\">This text will appear white on black background.</font>\n </td>\n </tr>\n </table>\n </body>\n \n</html>" }, { "code": null, "e": 5898, "s": 5709, "text": "This color value is specified using the rgb( ) property. This property takes three values, one each for red, green, and blue. The value can be an integer between 0 and 255 or a percentage." }, { "code": null, "e": 6000, "s": 5898, "text": "Note − All the browsers does not support rgb() property of color so it is recommended not to use it." }, { "code": null, "e": 6057, "s": 6000, "text": "Following is a list to show few colors using RGB values." }, { "code": null, "e": 6147, "s": 6057, "text": "Here are the examples to set background of an HTML tag by color code using rgb() values −" }, { "code": null, "e": 6627, "s": 6147, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML Colors by RGB code</title>\n </head>\n\t\n <body text = \"rgb(0,0,255)\" bgcolor = \"rgb(0,255,0)\">\n <p>Use different color code for for body and table and see the result.</p>\n \n <table bgcolor = \"rgb(0,0,0)\">\n <tr>\n <td>\n <font color = \"rgb(255,255,255)\">This text will appear white on black background.</font>\n </td>\n </tr>\n </table>\n </body>\n \n</html>" }, { "code": null, "e": 6847, "s": 6627, "text": "Here is the list of 216 colors which are supposed to be safest and computer independent colors. These colors very from hexa code 000000 to FFFFFF and they will be supported by all the computers having 256 color palette." }, { "code": null, "e": 6880, "s": 6847, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 6894, "s": 6880, "text": " Anadi Sharma" }, { "code": null, "e": 6929, "s": 6894, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6943, "s": 6929, "text": " Anadi Sharma" }, { "code": null, "e": 6978, "s": 6943, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6995, "s": 6978, "text": " Frahaan Hussain" }, { "code": null, "e": 7030, "s": 6995, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7061, "s": 7030, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 7094, "s": 7061, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 7125, "s": 7094, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 7160, "s": 7125, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7191, "s": 7160, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 7198, "s": 7191, "text": " Print" }, { "code": null, "e": 7209, "s": 7198, "text": " Add Notes" } ]
What is operator binding in Python?
For expressions like − a == b first the python interpreter looks up the __eq__() method on the object a. If it finds that, then executes that with b as argument, ie, a.__eq__(b). If this method returns a NotImplemented, then it tries doind just the reverse, ie, it tries to call, b.__eq__(a)
[ { "code": null, "e": 1085, "s": 1062, "text": "For expressions like −" }, { "code": null, "e": 1093, "s": 1085, "text": "a == b\n" }, { "code": null, "e": 1343, "s": 1093, "text": "first the python interpreter looks up the __eq__() method on the object a. If it finds that, then executes that with b as argument, ie, a.__eq__(b). If this method returns a NotImplemented, then it tries doind just the reverse, ie, it tries to call," }, { "code": null, "e": 1356, "s": 1343, "text": "b.__eq__(a)\n" } ]
Handling Child Windows with Cypress
Sometimes on clicking a link or button, it opens to another window often known as the child window. Cypress has a unique way of handling child windows unlike other automation tools like Selenium and Protractor. It basically keeps no information on the child window by shifting its focus from the parent to the child window. Now let us understand why a link or a button opens a new webpage on a different tab considered as a child. This is due to the attribute target set in the html for that element. If omitted, it shall open in the same window. Cypress cannot directly handle a child window and it provides the workaround to continue our tasks on the parent window itself. At first the href attribute from the html code is grabbed. This is done with the help JQuery method prop() [ this shall give the value of the property passed as an argument to the method]. Now after the value of the href property is obtained, we can launch the url with the help of visit() command in Cypress. However the test gets successful only if the other application should have the same domain as the original application [a different sub domain of the two applications is accepted]. Cypress takes it as a security threat if we are to access another application in the same window with the help of visit() command. Thus we cannot work with more than one domain at a time. Code Implementation to handle child windows. describe('Tutorialspoint Test', function () { // test case it('Test Case6', function (){ // launch the application cy.visit("https://accounts.google.com/signup"); // grab the href prop with prop() JQuery method cy.get(':nth-child(1) > a').then(function(l){ const txt = l.prop('href'); // get the url in logs cy.log(txt); // launch the url again cy.visit(txt); }) }); }); Test runner logs is as shown below −
[ { "code": null, "e": 1386, "s": 1062, "text": "Sometimes on clicking a link or button, it opens to another window often known as\nthe child window. Cypress has a unique way of handling child windows unlike other\nautomation tools like Selenium and Protractor. It basically keeps no information on\nthe child window by shifting its focus from the parent to the child window." }, { "code": null, "e": 1609, "s": 1386, "text": "Now let us understand why a link or a button opens a new webpage on a different tab considered as a child. This is due to the attribute target set in the html for that element. If omitted, it shall open in the same window." }, { "code": null, "e": 1926, "s": 1609, "text": "Cypress cannot directly handle a child window and it provides the workaround to continue our tasks on the parent window itself. At first the href attribute from the html code is grabbed. This is done with the help JQuery method prop() [ this shall give the value of the property passed as an argument to the method]." }, { "code": null, "e": 2228, "s": 1926, "text": "Now after the value of the href property is obtained, we can launch the url with the help of visit() command in Cypress. However the test gets successful only if the other application should have the same domain as the original application [a different sub domain of the two applications is accepted]." }, { "code": null, "e": 2416, "s": 2228, "text": "Cypress takes it as a security threat if we are to access another application in the\nsame window with the help of visit() command. Thus we cannot work with more than one domain at a time." }, { "code": null, "e": 2461, "s": 2416, "text": "Code Implementation to handle child windows." }, { "code": null, "e": 2916, "s": 2461, "text": "describe('Tutorialspoint Test', function () {\n // test case\n it('Test Case6', function (){\n // launch the application\n cy.visit(\"https://accounts.google.com/signup\");\n // grab the href prop with prop() JQuery method\n cy.get(':nth-child(1) > a').then(function(l){\n const txt = l.prop('href');\n // get the url in logs\n cy.log(txt);\n // launch the url again\n cy.visit(txt);\n })\n });\n});" }, { "code": null, "e": 2953, "s": 2916, "text": "Test runner logs is as shown below −" } ]
Microsoft Dynamics CRM - Quick Guide
Customer Relationship Management (CRM) is a system for managing a company’s interactions with current and future customers. It often involves using technology to organize, automate, and synchronize sales, marketing, customer service, and technical support. CRM can help reduce costs and increase profitability by organizing and automating business processes that nurture customer satisfaction and loyalty. Microsoft Dynamics CRM is a customer relationship management software package developed by Microsoft focused on enhancing the customer relationship for any organization. Out of the box, the product focuses mainly on Sales, Marketing, and Customer Service sectors, though Microsoft has been marketing Dynamics CRM as an XRM platform and has been encouraging partners to use its proprietary (.NET based) framework to customize it. In recent years, it has also grown as an Analytics platform driven by CRM. The CRM Solution can be used to drive the sales productivity and marketing effectiveness for an organization, handle the complete customer support chain, and provide social insights, business intelligence, and a lot of other out-of-the-box functionalities and features. As a product, Microsoft Dynamics CRM also offers full mobile support for using CRM apps on mobiles and tablets. As of writing this tutorial, the latest version of CRM is CRM 2016. However, in this tutorial we will be using CRM 2015 Online version as it is the latest stable version as well as frequently used in many organizations. Nevertheless, even if you are using any other versions of CRM, all the concepts in the tutorial will still hold true. Microsoft Dynamics CRM is offered in two categories − CRM Online is a cloud-based offering of Microsoft Dynamics CRM where all the backend processes (such as application servers, setups, deployments, databases, licensing, etc.) are managed on Microsoft servers. CRM Online is a subscription-based offering which is preferred for organizations who may not want to manage all the technicalities involved in a CRM implementation. You can get started with setting up your system in a few days (not weeks, months or years) and access it on web via your browser. CRM on-premise is a more customized and robust offering of Microsoft Dynamics CRM, where the CRM application and databases will be deployed on your servers. This offering allows you to control all your databases, customizations, deployments, backups, licensing and other network and hardware setups. Generally, organizations who want to go for a customized CRM solution prefer on-premise deployment as it offers better integration and customization capabilities. From the functional standpoint, both the offerings offer similar functionalities; however, they differ significantly in terms of implementation. The differences are summarized in the following table. Microsoft Dynamics CRM can be accessed via any of the following options − Browser Mobile and Tablets Outlook Microsoft Dynamics CRM is undoubtedly one of the top products in the CRM space. However, following are the other products that compete with Microsoft Dynamics CRM. Salesforce.com Oracle SAP Sage CRM Sugar CRM NetSuite Microsoft Dynamics CRM has grown over the years starting from its 1.0 version in 2003. The latest version (as of writing this article) is 2015. Following is the chronological list of release versions − Microsoft CRM 1.0 Microsoft CRM 1.2 Microsoft Dynamics CRM 3.0 Microsoft Dynamics CRM 4.0 Microsoft Dynamics CRM 2011 Microsoft Dynamics CRM 2013 Microsoft Dynamics CRM 2015 Microsoft Dynamics CRM 2016 Let's start by setting up our CRM environment. We will be using the online version of CRM 2015, since the online version provides one-month free trial access. By doing this, you will not need to purchase any license to learn CRM. Note − Since Microsoft Dynamics CRM is a growing product, it is possible that by the time you are learning this, you will have a newer version of the product. In that case, the application may not look exactly as you would see in the screenshots of this tutorial. However, the core concepts of the product remain the same. The look-and-feel and the navigation of the product may change, however, in most of the cases you will be able to easily navigate and locate the required options. Step 1 − Navigate to the following URL − https://www.microsoft.com/en-us/dynamics365/home In case you do not see the options of Trial version via this link in future, just try searching "Microsoft Dynamics CRM Free Trial" on Google. Step 2 − Click the Try it free button. This will start a 3-step registration process as shown in the following screenshot. In Step 1 of 3-step registration, fill in the mandatory details such as name, email, and language. Step 3 − Click the Try it free button. This will start a 3-step registration process as shown in the following screenshot. In Step 1 of 3-step registration, fill in the mandatory details such as name, email, and language. Step 4 − In Step 3 of 3-step registration, Microsoft will validate the mobile number that you have specified. For this, you can provide your mobile number and click Text me. It will then send an OTP to your mobile using which you will be able to proceed further with the setup. Step 5 − Your Office 365 user ID will be created. You can save this user ID information for later access. After setting up the account, it will now open your CRM Dashboard which will look something like the following. Just to emphasize again, the screenshots above may change with a future version, however setting up the environment will be a pretty simple process. The Software Development Kit (SDK) of Microsoft Dynamics CRM contains important code samples including server side code, client side code, extensions, plugins, web services, workflows, security model, etc. Basically, the SDK contains every development resource that you would need to get started with CRM. Whether you are planning to set up a new plugin project or setting up a web services project for CRM, the SDK provides the basic architecture and examples ranging from simple to advanced level to help you kick-off. We will now look at the steps to download and install the SDK. Step 1 − Every version of Microsoft Dynamics CRM comes with its own SDK version. The best way to get the correct SDK version would be to search on Google for your respective CRM version. For example, if your CRM version is 2015, then try searching for "Microsoft Dynamics CRM 2015 SDK". Step 2 − Once downloaded, run the exe setup. Click Continue. Step 3 − It will ask you to choose the location where the SDK should be extracted. Select any appropriate location where you would like to keep the reference SDK. Step 4 − Open the folder where you had extracted. You can access all the SDK content from here. In this chapter, we have set up our environment by creating a CRM Online account. We then downloaded the CRM SDK, which will be used in the subsequent chapters of this tutorial. Make sure to note down the credentials with which you have set up the account, since you will need these credentials the next time you login. The entire Microsoft Dynamics CRM is designed around the following functional modules. Sales Marketing Service Management These functional modules are often called as Work Areas. The entire CRM application is divided functionally for different types of users and teams. Hence, if an organization is using CRM to manage its processes, the users from the Sales team would use the functionalities that come under the Sales module, while the users from the Marketing team would use functionalities that fall under the Marketing module. All these three functional modules come together to drive the entire lifecycle of gaining a new customer (Marketing), selling them the services (Sales) and maintaining the existing customers (Service Management). To understand this flow in a better way, consider a bank which sells credit cards to its customers. The typical lifecycle of selling a credit card to a customer would be as follows. In each step of this lifecycle, you will see how the Sales, Marketing and Service modules perform their role. Sales & Marketing − The bank’s call center office executive receives data of potential customers; often called as Leads in CRM. These Leads are captured in the CRM system via marketing campaigns, sales drives, referrals, etc. Sales − The call center executive communicates with these Leads either through phone calls/emails/etc. If the customer is interested in the credit card offering, the Lead record will be converted to an Opportunity record (won Lead). Service − Once a customer becomes a part of the system, the company would assist him/her with payments, billing, refunds, etc. Whenever the customer has any queries or concerns, they will make a call to the call center and raise incidents. The executive will followup to resolve the case with the aim to provide quality service to the customer. These tasks fall under CRM Service Management. Step 1 − Open CRM Home Page. Step 2 − By default, you will see the Sales work area as selected. Step 3 − To change the work area, click the Show work areas option. You will see the options for selecting Sales, Service, and Marketing. Step 4 − Click Sales. This will show you all the entities which fall under Sales such as Accounts, Contacts, Leads, Opportunities, Competitors, etc. Each of these entities are categorized by their business process such as My Work, Customers, Sales, Collateral, etc. Step 5 − Similarly, if you click the Marketing work area, you will see all the entities related to Marketing business functionalities. The Sales module of CRM is designed to drive the entire sales lifecycle of a new customer. The Sales module consists of the following sub-modules − Leads − Represents a person or an organization that can be a potential customer to the company in future. This is the first step towards getting a potential customer in the system. Opportunities − Represents a potential sale to the customer. Once a Lead shows interest in the offering, it gets converted to an Opportunity. An Opportunity will either be won or lost. Accounts − Represents a company with which the organization has relations. Once an Opportunity wins, it gets converted to either an Account or Contacts. Contacts − Represents a person, or any individual with whom the organization has relations. Mostly these Contacts are the customers of the organizations (e.g. all credit card customers of a bank). Once an Opportunity wins, it gets converted to either an Account or Contacts. Competitors − Manages all the market competitors of the organization. Products − Manages all the products offered by the organization to its customers (Example, all the credit card plans). Quotes − A formal offer for products or services proposed at specific prices sent to a prospective customer (Example, yearly pricing of a certain credit card plan sent to the customer). Orders − A quote that gets accepted by the customer turns into an Order (Example, out of all the plans that the organization offers you, you may go for a 6-month subscription). Invoices − A billed order generates an invoice. The Marketing module of CRM is designed to drive the entire marketing process of an organization for its existing and potential customers. The Marketing module consists of the following sub-modules − Marketing Lists − Provides a way to group your Contacts, Accounts, and Leads and interact with them via sending promotional emails, event details, newsletters and other updates relevant to the target customers. You can define the criteria to create your marketing lists (Example, contacts aged between 25 and 35). Campaigns − Campaigns are designed to measure the effectiveness and accomplish a specific result, such as introducing a new product or increasing the market share and may include various communication channels such as email, newspaper ads, YouTube ads, etc. Quick Campaigns − A Quick Campaign is similar to Campaign however it can be related to only one type of activity. All the above Marketing modules work in close co-ordination with the Sales module. The Service Management module of CRM is designed to focus, manage, and track the customer service operations of an organization such as supporting the incident-based services, supporting the customers using service scheduling, etc. The Service Management module covers the following sub-modules − Cases (Incidents) − Supports any customer requests, issues, or complaints to be tracked via incidents/cases. A case follows various stages of an issue resolution process and then finally gets resolved and is closed. Cases (Incidents) − Supports any customer requests, issues, or complaints to be tracked via incidents/cases. A case follows various stages of an issue resolution process and then finally gets resolved and is closed. Knowledge Base − Maintains a master repository for all the common questions and answers that the customer frequently asks. Knowledge Base − Maintains a master repository for all the common questions and answers that the customer frequently asks. Contracts − Contracts work with Cases indicating all the active contracts that the customer has. Contracts − Contracts work with Cases indicating all the active contracts that the customer has. Resources/Resource Groups − Represents the people, tools, rooms, or pieces of equipment that are used to deliver a service. These resources can be used to solve a specific customer issue. Resources/Resource Groups − Represents the people, tools, rooms, or pieces of equipment that are used to deliver a service. These resources can be used to solve a specific customer issue. Services − Represents all the services that the organization offers to the customers. Services − Represents all the services that the organization offers to the customers. Service Calendar − Used to schedule work timings and schedules of the users who work in the organization. Service Calendar − Used to schedule work timings and schedules of the users who work in the organization. All the modules explained above use the Activity Management module of CRM. An Activity represents any kind of interaction with the customer such as a Phone Call, Email, Letter, etc. These activities can be related to any of the entities explained earlier such as Account, Contact, Lead, Case, etc. By default, CRM provides following types of activities out-of-the-box − Phone Call Email Task Appointment Recurring Appointment Letter Fax Campaign Response Campaign Activities Service Activity Custom Activities In this chapter, we have learnt about the three major modules of CRM – Sales, Marketing, and Service Management. We understood how the work areas are organized in CRM and how the entire lifecycle of a CRM organization works. We also looked at the Activity Management module of CRM which allows to create Phone, Email, Fax and other types of customer interaction activities. Now that we have a functional overview of all the CRM modules, let us learn and understand about the entities and forms in CRM. An entity is used to model and manage business data in CRM. Contacts, Cases, Accounts, Leads, Opportunities, Activities, etc. are all entities which hold data records. Conceptually, a CRM entity is equivalent to a database table. For example, Contacts entity would hold Contact records, Cases entity would hold Cases records, and so on. You can have both: out-of-the-box entities (which comes by default with the CRM) and custom entities (which you can create with customization). For instance, suppose that you are maintaining the data of the books your customers have read. For this, you will be storing the customer data using out-of-the-box Contacts entity but where would you store the books data? You do not have any entity that can store data for books. In such scenarios, you will create a new custom entity named Books and relate this with the existing Contacts entity. For this tutorial, let us take an example of storing employers and employees in CRM. Taking this example into consideration, out-of-the-box, CRM provides Contact entity in which you can ideally store all your employees. It also provides an Account entity in which you can store all your employers. But for the sake of learning entities, we will create a new custom entity called Employer (and not use the existing Account entity). Step 1 − Click the top ribbon button followed by Settings option. Click Customizations option from the Customization section (Refer the following screenshot). Step 2 − Now click Customize the System option. This will open up the Default Solution window. You will learn more about CRM Solutions in the next chapters but for now you will be using the default CRM Solution. Step 3 − Expand the Entities option from the left panel. Step 4 − Now click New → Entity. Step 5 − In the Entity Form, enter the Display Name as Employer and PluralName as Employers. In the section ‘Areas that display this entity’, check Sales, Service and Marketing. Checking these options will display the newly created entity in Sales, Service, and Marketing tabs of CRM. Step 6 − Click on the Save and Close icon. This will create a new entity in CRM database behind the scenes. Step 7 − In the Default Solution parent window, you will see the newly created Employer entity. Step 8 − Click Publish All Customizations option from the top ribbon bar. This will publish (aka commit) all the changes we did till now. You can close this window by clicking Save and Close. CRM is all about managing valuable data in your system. In this section, we will learn how to create, open, read, and delete records in CRM. We will continue with the employer entity that we created in the last chapter. Step 1 − Navigate to Employer entity records grid via Show work areas → Sales → Extensions → Employers. Step 2 − Click the New icon. This will open the default new employer form. You can see that there is only one editable field Name in this default form. Enter Employer 1 in the Name field. Click Save and Close. Step 3 − In the Active Employers view, you can see the newly created employer record. To access the already created records in CRM, go to that entity page. In our case, navigate to Show work areas → Sales → Extensions → Employers. You will see list of records present there in the grid. Click any Employer record to access it. Once you have a record open, you can just edit any details on the form. By default, CRM 2015 comes with auto-save option which saves any changes made to the form 30 seconds after the change. Alternatively, you can click Ctrl+S. In case you want to disable the auto-save feature, go to Settings → Administration → System Settings → Enable auto-save for all forms and select No. Step 1 − Select one or multiple records which you want to delete and click the Delete button. Step 2 − Confirm the deletion of records by clicking Delete. As seen in the above example, the default Employer form had only one field. However, in real life scenarios, you will have many custom fields on a form. For example, if you look at a sample Contact record (which is an out-of-the-box CRM entity), it will have many fields to store contact information such as Full Name, Email, Phone, Address, Cases, etc. In the next chapters, you will learn how to edit this default form and add different types of fields on it. Before you learn how to add custom fields to CRM forms, let us take a look at what type of data fields are supported by CRM. Out-of-the-box, CRM provides 11 types of data fields that can be placed on forms − Single Line of Text Option Set (Dropdown) Two Options (Radio Button) Image Whole Number Floating Point Number Decimal Number Currency Multiple Lines of Text Date and Time Lookup The following table lists each with a brief description. Single Line of Text This field stores up to 4000 characters of text. You can also specify the format as one of these: Email, Text, Text Area, URL, Ticker Symbol, and Phone. You can set the maximum length and IME mode for each of these. Option Set (Dropdown) This field stores a set of options each having a number value and label. In other words, it is a dropdown field in CRM. You can also define Global Option Sets which can be used across multiple forms. Two Options (Radio Button) This field provides two options for the user to select (0 or 1). In other words, it is a radio button field. Image When an entity has an image field, it can be configured to display the image for the record in the application. Whole Number This field stores integer values between -2,147,483,648 and 2,147,483,647. It supports the specifying formats as None, Duration, Time Zone, and Language. You can set the minimum and maximum values too. Floating Point Number This field stores the floating point numbers up to 5 decimal points of precision between 0.00 and 1,000,000,000.00. You can set the minimum and maximum values too. Decimal Number This field stores up to 10 decimal points with values ranging from -100,000,000,000.00 and 100,000,000,000.00. Currency This field is used to store any currency values in the range of 922,337,203,685,477.0000 to 922,337,203,685,477.0000. You can also specify the Precision as Pricing Decimal, Currency Precision or any value between 0 to 4. Multiple Lines of Text This is a scrolling text box. You can set the maximum number of characters for this field. Date and Time This field is used to store date-related data in CRM with two supported formats: Date Only, and Date and Time. You can also specify the behavior as User Local, Date Only and Time-Zone Independent. Lookup You can create a lookup field using an entity relationship that has already been created, but not yet used with another lookup field. If you create a lookup field in an entity form, the relationship is automatically generated. A lookup field is created as a relationship field. In the last two chapters, you studied about creating new entities, creating new records and types of fields available in CRM. In this chapter, you will be learning to add new fields on CRM forms. Out of the 11 types of data fields studied in the previous chapter, you will be using three types of fields on your employer - Option Set (Dropdown), Multiple Lines of Text and DateTime. The Option Set field would be used to store the employer type, Multiple Lines of Text will be used to store brief description of employer and the DateTime field would be used to store date when the company was started. Note:You already had a Name field on your form which was a Single Line of Text type. Step 1 − Click the top ribbon button followed by Settings option. Click Customizations option from the Customization section (Refer screenshot below). Step 2 − Now click the Customize the System option. This will open the DefaultSolution window. You will learn more about CRM Solutions in the next chapters but for now you will be using the default CRM Solution. Step 3 − Expand the Entities option from the left panel. Step 4 − From the expanded entities, select Employer. This will open the details of the entity on the right window. Expand Employer option from the left panel and you will be able to see Forms, Views, Charts, Fields, and other several options. Step 5 − Click Fields. It will open a grid showing all the fields that came by default when you created this entity. Step 6 − Click the New button. In the new window that opens, enter the following details − Display Name − Employer Type Name − This field will be populated automatically based on the display name you select. However, if you would like to change it, you can do so. Data Type − Option Set. As soon as you select the Data Type as Option Set, it will show you the Options panel. Clicking the plus(+) icon creates a new option set item with default Label as Item and default Value as 100,000,000. You can change the label of this item to add four options representing employer types: Private, Government, Multinational and Public. Step 7 − Click Save and Close from the top ribbon. You have successfully created Employer Type field. Step 8 − Similar to what you just did for adding Employer Type field, add three other fields as described and shown in the following screenshots − Number of Employees − This will be a Whole Number field. Founded On − This will be a DateTime field. Employer Description − This will be a Multiple Lines of Text field. Step 9 − Now add these new fields on the employer form. For this, click Forms from the left navigation under Employer entity. This will show you two forms with name Information. By default, CRM creates two forms – Main and Mobile-Express. Click on the Main form. Step 10 − You can see the newly added fields in the Field Explorer panel on the right. Step 11 − Drag and drop these fields in the General tab. Step 12 − Click Save and then click Publish. Step 13 − You can now create employer records with the updates fields. Navigate to CRM Home → Sales → Employers → New. The new form which will open this time will contain all the new fields that you added in this chapter. You can fill in some details and click Save and Close. In this chapter, we learnt working with CRM forms and how to customize them by placing various types of fields in them. We also learnt to add as many fields as we want on any form and arrange them using various tabs and sections as per the business requirement. Microsoft Dynamics CRM is a vast product which has evolved significantly over the years. The product comes with a lot of out-of-the-box functionalities that are inbuilt in the system. You do not need to write any code for utilizing these features. One of the important out-of-the-box features is the searching capability of CRM, in that it supports advanced querying and filtering capabilities. By default, the grid view of every entity in CRM supports a Quick Search functionality using a search bar on top right. Following is a screenshot of quick search on Contact entity. You can try entering a search string like 'Robert' and it will return all the matching records. You can prefix the search keyword with * (asterisk) to perform a wildcard search. Note − When using the web client version of Microsoft Dynamics CRM, Quick Search always searches All Active records irrespective of the view selected. You can customize the Quick Search (like customizing any other View) to modify the filter criteria, configure sorting, add view columns, add find columns and change other properties. Advanced Search allows you to search records of any entity in CRM. It is one of the strongest and one of the most useful feature that comes out-of-the-box with CRM. The Advanced Search icon appears on the top ribbon bar of Microsoft Dynamics CRM irrespective of which screen you are on. Click the Advanced Find icon to open the Advanced Find window. This window will allow you to select the entity for which you want to search records, apply filtering and grouping criteria, and save your Advanced Find views as personal views. Let’s take an example. Suppose, you want to search for all the Contacts with FirstName containing Robert and who are Divorced. For this − Step 1 − Select Contacts from the Look for dropdown. This dropdown will contain all the entities present in your system. Step 2 − Enter the search criteria as shown in the following screenshot. You can add as many search query parameters as you want. You can even group such criteria using group parameters. For example, if you would like to search all contacts whose first name is either Robert or Mark, you can add two search criteria and group them using GroupOR. Step 3 − Click the Results button. It will show the matched records in a new tab. Step 4 − You can also edit the columns that you would like to see in the search results by clicking Edit Columns. For example, our current grid contains only two columns – Full Name and Business Phone. However, if you would like to have an additional column of Email ID added to this grid, you can do so using this option. At this stage, if you would like to save this search criteria, along with the filters and edited columns, you can do so by clicking the Save button. Once saved, you can use this saved view when you are on that entity page. For example, consider that as a customer executive you serve two types of customers: Normal and Premium. Hence, you can create an advanced filter with these respective categories and save them as Normal Contacts Assigned to Me and Premium Contacts Assigned to Me. You can then quickly access these views directly from the Contact entity page without carrying out a quick search or an advanced find search every time you use the system. Web Resources in CRM are the virtual web files that are stored in CRM database and used to implement web page functionalities in CRM. These files can be of HTML, JScript, Silverlight, or any other supported types. CRM being a product, comes with an extensive set of features and functionalities. However, most of the times, you would have to extend these existing functionalities to meet your custom requirements. Extending these functionalities generally happens in two ways − Extending on Client Side − Using Web Resources and Form Scripting. Extending on Client Side − Using Web Resources and Form Scripting. Extending on Server Side − Plugins, Workflows and Web Services (we are going to learn this part in the upcoming chapters). Extending on Server Side − Plugins, Workflows and Web Services (we are going to learn this part in the upcoming chapters). As mentioned above, extending CRM on the client side is where Web Resources comes in picture. To understand this clearly, consider the following use cases − You have a CRM form containing certain fields. CRM provides out-of-the-box features for basic validations such as mandatory fields, field lengths, etc. However what if you would like to have a more complex validation such as validating if the entered phone number is in the correct format, or validating if the entered address actually exists, or if the entered SSN is correct? You have a CRM form containing certain fields. CRM provides out-of-the-box features for basic validations such as mandatory fields, field lengths, etc. However what if you would like to have a more complex validation such as validating if the entered phone number is in the correct format, or validating if the entered address actually exists, or if the entered SSN is correct? CRM provides out-of-the-box UI customizations such as creating sections and tabs on a form, rearranging fields, etc. However, what if the client wants to build a custom page which shows all the information of the customer coming from their other ERP system? CRM provides out-of-the-box UI customizations such as creating sections and tabs on a form, rearranging fields, etc. However, what if the client wants to build a custom page which shows all the information of the customer coming from their other ERP system? CRM comes with a standard ribbon bar, which contains all the buttons and options. What if you want to add a ribbon button of your own? CRM comes with a standard ribbon bar, which contains all the buttons and options. What if you want to add a ribbon button of your own? Consider that you have an ERP system already in place. What if you would like to open some CRM screens from this ERP system? Consider that you have an ERP system already in place. What if you would like to open some CRM screens from this ERP system? You can always call any external web services in your server-side plugin code. However, what if you would like to call any external web services while you are still on the client-side? You can always call any external web services in your server-side plugin code. However, what if you would like to call any external web services while you are still on the client-side? The answer to all these “What ifs” is Web Resources. Every Web Resource can be accessed via its unique URL. You can either upload a Web Resource file or for codebased resources (such as HTML, Jscript, etc.) you can even edit them directly inside CRM. Since Web Resources are stored within CRM, they can easily be migrated from one environment to another together, along with any CRM customizations. Out of all these types of web resources, we will be studying the most important types of web resources - HTML Web Resources and JScript Web Resources, in the subsequent chapters. All the Web Resources stored in the database can be accessed in CRM. Following are the steps involved − Step 1 − Go to Settings → Customizations → Customize the System. Step 2 − From the left navigation, select Web Resources. Currently, you will not be able to see any Web Resources since we have not created anything yet. We will be looking at how to create web resources in the next chapters. JScript Web Resources are probably the most important type of web resources that you will be using with Microsoft Dynamics CRM. Form Event Programming is used to handle client-side behaviors such as what happens when a user opens a form, changes some data, moves through tabs, etc. To achieve such client-side interactions you will be writing JavaScript code and adding it as a JScript Web Resource in CRM. However, the JavaScript code which you will write has to use Dynamic CRM’s Xrm.Page model and not the standard JavaScript DOM. Using Xrm.Page model is Microsoft’s way of coding which ensures that any code you write using this model will be compatible with any future versions of CRM. In addition to being used in Form Event Programming, JavaScript is used in other applications of CRM such as − Open Forms, Views and Dialogs with a unique URL. Open Forms, Views and Dialogs with a unique URL. Using OData and SOAP endpoints to interact with web services. Using OData and SOAP endpoints to interact with web services. Referencing JavaScript code inside other Web Resources (such as HTML web resources). Referencing JavaScript code inside other Web Resources (such as HTML web resources). In such cases, you would write your JavaScript code (using Xrm.Page model) and add it as a JScript Web Resource in CRM, which can then be referenced anywhere with a unique URI. Finally, one of the other common use of JavaScript is to handle ribbon customizations such as − Display/Hide ribbon buttons based on some logic Enable/Disable ribbon buttons based on some logic Handle what happens when you click a certain ribbon button To handle such scenarios, you will write your JavaScript logic (using Xrm.Page model) and then add it as a JScript Web Resource. This Web Resource can then be referenced in the ribbon button’s XML and we can specify which method in which JScript file to call to check if a ribbon button should be displayed/hidden or enabled/disabled or handle click events. Following is the Xrm.Page object’s hierarchy showing the available namespaces, objects, and their collections. You will be using these properties while writing JScript code. Context Provides methods to retrieve context-specific information such as organization details, logged-in user details, or parameters that were passed to the form in a query string. Data Provides access to the entity data and methods to manage the data in the form as well as in the business process flow control. UI Contains methods to retrieve information about the user interface, in addition to collections for several sub-components of the form. Entity Provides method to − Retrieve record information Save method Collection attributes Process Methods to retrieve properties of business process flow. Navigation Provides access to navigation items using items collection. FormSelector Uses Items collection to access available forms to the user. Also uses the navigation method to close and open forms. Stages Each process has a collection of stages that can be accessed using getStages method of process. Steps Each stage comprises of various steps that can be accessed using getSteps method of stage. Attributes Provides access to entity attributes available on the form. Controls ui.controls − Provides access to each control present on the form. attribute.controls − Provides access to all the controls within an attribute. section.controls − Provides access to all the controls within a section. Items Provides access to all the navigation items on a form. Tabs Provides access to all the tabs on a form. Sections Provides access to all the sections on a form. The Form Programming using Xrm.Page model allows you to handle the following form events − onLoad onSave onChange TabStateChange OnReadyStateComplete PreSearch Business Process Flow control events In this example, we will put some validations on the Contact form based on the PreferredMethodofCommunication that the user selects. Hence, if the user selects his/her preferred method as Email, then the Email field should become mandatory and similarly for other fields of Phone and Fax. Step 1 − Create a JavaScript file named contacts.js and copy the following code. function validatePreferredMethodOfCommunication() { //get the value of Preffered Method of Communication code var prefferedContactMethodCode = Xrm.Page.getAttribute('preferredcontactmetho dcode').getValue(); //if Preferred Method = Any, make all fields as non-mandatory //else if Preferred Method = Phone, make Mobile Phone field mandatory //and all other fields as non-mandatory //else if Preferred Method = Fax, make Fax field mandatory //and all other fields as non-mandatory if(prefferedContactMethodCode == 1) { clearAllMandatoryFields(); } if(prefferedContactMethodCode == 2) { clearAllMandatoryFields(); Xrm.Page.getAttribute('emailaddress1').setRequiredLevel('required'); } else if(prefferedContactMethodCode == 3) { clearAllMandatoryFields(); Xrm.Page.getAttribute('mobilephone').setRequiredLevel('required'); } else if(prefferedContactMethodCode == 4) { clearAllMandatoryFields(); Xrm.Page.getAttribute('fax').setRequiredLevel('required'); } } function clearAllMandatoryFields() { //clear all mandatory fields Xrm.Page.getAttribute('emailaddress1').setRequiredLevel('none'); Xrm.Page.getAttribute('mobilephone').setRequiredLevel('none'); Xrm.Page.getAttribute('fax').setRequiredLevel('none'); } Step 2 − Open the Contact entity form by navigating to Settings → Customizations → Customize the System → Contact entity → Forms → Main Form. Step 3 − Click Form Properties. Step 4 − From the Form Properties window, click Add. Step 5 − In the next Look Up Web Resource Record window, click New since we are creating a new web resource. Step 6 − In the New Web Resource window, enter the following details − Name − new_contacts.js Display Name − contacts.js Type − JScript Upload File − Upload the JavaScript file that you created from your local machine. Step 7 − Click Save followed by Publish. After this close the window and you will be back to Look Up Web Resource Record window. Step 8 − Here, you can now see the new_contacts.js web resource. Select it and click Add. You have now successfully added a new web resource and registered it on the form. Step 9 − Now we will add an event handler on the change of Preferred Method of Communication field. This event handler will call the JavaScript function that we just wrote. Select the following options from the Event Handler section. Control − Preferred Method of Communication Event − OnChange Then, click the Add button, as shown in the following screenshot. Step 10 − In the next window of Handler Properties, we will specify the method to be called when the change event occurs. Select Library as new_contacts.js and Function as validatePreferredMethodOfCommunication. Click OK. Step 11 − You will now be able to see the Form Library (Web Resource) and events registered on it. Click OK. Step 12 − Click Save followed by Publish. Step 13 − Now open any Contact form and set the Preferred Method of Communication as Phone. This will make the Mobile Phone field as mandatory. If you now try to save this contact without entering any mobile number, it will give you an error saying ‘You must provide a value for Mobile Phone’. In this chapter, we started by understanding the three important applications of JavaScript in CRM. Later, we explored the Xrm.Page model and used it to learn Form programming along with an example. In this chapter, we will learn about the various web resources in Microsoft Dynamics CRM. An HTML Web Resource in CRM can contain any HTML content that can be rendered on a browser. Consider the following scenarios where you would like to use HTML Web Resources − You have a static HTML page that you want to show inside CRM screen. You have a static HTML page that you want to show inside CRM screen. You have a custom HTML page that expects some input parameters and gets rendered based on those input parameters. For example, consider you are fetching information from an external API or web service, and you want to display this in CRM. You have a custom HTML page that expects some input parameters and gets rendered based on those input parameters. For example, consider you are fetching information from an external API or web service, and you want to display this in CRM. You want to display some information with a different look and feel from the standard CRM UI. You want to display some information with a different look and feel from the standard CRM UI. You have a custom ASPX page (outside CRM application) which gets rendered based on the input parameters. Since CRM does not allow you to have ASPX web resources, you can create an HTML Web Resource and call the external ASPX page from this HTML page. We will create a very simple HTML Web Resource which will display a custom text ‘Welcome to TutorialsPoint’. Note that this is a very simple example of an HTML Web Resource. Practically, the HTML Web Resources would be more complex than this. Step 1 − Create an HTML file named sampleHTMLWebResource.html and copy the following code. <!DOCTYPE html> <htmllang = "en"xmlns = "http://www.w3.org/1999/xhtml"> <head> <metacharset = "utf-8"/> <title>Welcome to Tutorials Point</title> </head> <body> <h1>Welcome to Tutorials Point. This is an example of HTML Web Resource.</h1> </body> </html> Step 2 − First, we will create a new Web Resource and then reference it on the Contact form. Open the DefaultSolution and navigate to WebResources tab from the left panel. Click New. Step 3 − It will open a New Web Resource window. Enter the details as shown in the following screenshot and browse the HTML file that we created in Step 1. Click Save and Publish. Close the window. Step 4 − You will see the new Web Resource added to the Web Resources grid. Step 5 − Now open the Contact form via Settings → Customizations → Customize the System → Contact → Main Form. Select the Contact Information section and switch to Insert tab from the top ribbon bar. Click Web Resource. Step 6 − It will open an Add Web Resource window. Click the Web Resource Lookup from this window, which will open the Web Resource Lookup Record window. Search the Web Resource that you just created (new_sampleHTMLWebResource), select it from the grid and click Add. Step 7 − Coming back to Add Web Resource, enter the Name and Label as shown in the following screenshot and click OK. Close the window. You will see the HTML Web Resource added below the Address field. Step 8 − To test this out, open any Contact record and you will see the HTML Web Resource content displayed there. There is no supported way of using the server-side code in HTML Web Resources. There is no supported way of using the server-side code in HTML Web Resources. HTML Web Resources can accept only limited number of parameters. To pass more than one value in the data parameter, you will have to encode the parameters include decoding logic on the other end. HTML Web Resources can accept only limited number of parameters. To pass more than one value in the data parameter, you will have to encode the parameters include decoding logic on the other end. Workflows in CRM allow you to automate simple and complex business processes within CRM. You can either create workflows using CRM out-of-the-box functionalities or write custom workflows with .NET code for implementing complex workflows. Workflow processes run in the background or in real-time and can optionally require a user input. Workflows can be triggered based on specific conditions or can even be started manually by the users. Internally, CRM workflows are implemented using Windows Workflow Foundation. In this chapter, we will be learning about configuring workflows. Configuring a workflow has the following major parts (in sequence) − Configure the entity on which the workflow will run Configure whether the workflow will run synchronously or asynchronously Configure the message (event) on which the workflow will run Configure the scope in which the workflow will run Configure the stages and steps (actions) of the workflow When you create a workflow, you will see the option of Run this workflow in the background (recommended) which determines whether the workflow will run in real-time (synchronously) or in background (asynchronously). Generally, the recommended approach is to run the workflows in the background since they use system resources as and when available. However, you can always switch back from a real-time workflow to background workflow and vice versa. Workflows can be registered on specific events as follows − When a record is created When a record status changes When a record is assigned When a record field value changes When a record is deleted Workflows allow you to set the scope in which the workflow will run. Following are the supported workflow scopes − Workflows in CRM are a combination of series of steps which the workflow will follow. You can even divide these steps in logical stages. Following steps are supported by CRM workflows − In this example, we will create a simple workflow that runs in the background to assign any newly created Contact record to a specific user and then send out a welcome email to the customer. Step 1 − Go to Settings → Processes. Step 2 − Click New. Step 3 − In the CreateProcess window, enter the following details − Process Name − New Customer Workflow (This can be any name that you want) Category − Workflow Entity − Contact (This will be the entity on which you are creating the workflow. In our case it is Contact) Run this workflow in the background (recommended) − Check this option as we are creating a background asynchronous workflow. Finally, click OK. Step 4 − In the New Process Window enter the following details − Activate As − Process Scope − User Start when − Record is created Click Add Step → Assign Record. Step 5 − You will see a new step added to the workflow. In this step, we will specify the user to whom all the created contacts should be assigned. Enter the name of step as Assign Record to Team. The Assign option will be defaulted as the entity on which we are creating the workflow (Contact in our case). Click the Lookup icon. Step 6 − In the Lookup window, select any user that you want. You can even select a specific team to whom you want to assign the records to. Click Add. Step 7 − Add another step by clicking Add Step → Send Email. In this step, we will configure sending email to the customer. Step 8 − A new step will be added. Enter its name as Send email to Customer. Click Set Properties. Step 9 − In the next window to configure email, perform the following operations− From − Click From field. On the right panel, select OwningUser and User. Click Add → OK. To − Click To field. On the right panel, select Contact and Contact. Click Add → OK. Subject − Enter a relevant Subject. Body − Enter a relevant Body content. Step 10 − Click Save and then Activate. Step 11 − In the Process Activate Confirmation popup that follows, click Activate. Step 12 − Go to Contacts tab and create a new contact. As soon as you create a new contact by saving the record, you will see the Owner field set to the user, which you had configured in the workflow. Also, if you click the Activities tab, you will see an email activity being created for this contact. This confirms that the workflow ran successfully. Workflows and plugins can both be used to extend and automate CRM functionalities. In many scenarios, both the approaches can be interchangeably used in place of each other. For example, if you have a simple requirement of sending an email to your customers, you can either do it via a plugin or a workflow. So, how do you choose between creating a workflow vs plugin? The following list tries to explain the same − Although plugins and workflows both can be used to run synchronous as well as asynchronous logic, plugins are generally preferred for synchronous logic, while workflows for asynchronous logic. Although plugins and workflows both can be used to run synchronous as well as asynchronous logic, plugins are generally preferred for synchronous logic, while workflows for asynchronous logic. Generally, to implement complex business logic, plugins are preferred over workflows. Workflows are preferred when you want to achieve relatively easier functionalities (such as sending emails, assigning users, etc.) Generally, to implement complex business logic, plugins are preferred over workflows. Workflows are preferred when you want to achieve relatively easier functionalities (such as sending emails, assigning users, etc.) Plugins need to be developed with coding, while workflows can be configured directly by business users without any knowledge of workflows. Plugins need to be developed with coding, while workflows can be configured directly by business users without any knowledge of workflows. Workflows can run on-demand. Hence, if there are requirements where the user wants to run some logic manually, workflows would be a better choice. Workflows can run on-demand. Hence, if there are requirements where the user wants to run some logic manually, workflows would be a better choice. From performance impact, synchronous plugins provide a better performance (and throughput) as compared to real-time workflows in scenarios where the request frequency is higher. From performance impact, synchronous plugins provide a better performance (and throughput) as compared to real-time workflows in scenarios where the request frequency is higher. This chapter introduced us to one of the very important functionalities of CRM – Workflows. We first understood the sync/async workflows, messages, scope, steps and finally looked at a live example of creating and running a workflow. Finally, we saw the differences between a workflow and a plugin. A plug-in is a custom business logic that integrates with Microsoft Dynamics CRM to modify or extend the standard behavior of the platform. Plug-ins act as event handlers and are registered to execute on a particular event in CRM. Plugins are written in either C# or VB and can run either in synchronous or asynchronous mode. Some scenarios where you would write a plugin are − You want to execute some business logic such as updating certain fields of a record or updating related records, etc. when you create or update a CRM record. You want to execute some business logic such as updating certain fields of a record or updating related records, etc. when you create or update a CRM record. You want to call an external web service on certain events such as saving or updating a record. You want to call an external web service on certain events such as saving or updating a record. You want to dynamically calculate the field values when any record is opened. You want to dynamically calculate the field values when any record is opened. You want to automate processes such as sending e-mails to your customers on certain events in CRM. You want to automate processes such as sending e-mails to your customers on certain events in CRM. The Event Processing Framework in CRM processes the synchronous and asynchronous plugin requests by passing it to the event execution pipeline. Whenever an event triggers a plugin logic, a message is sent to the CRM Organization Web Service where it can be read or modified by other plugins or any core operations of the platform. The entire plugin pipeline is divided in multiple stages on which you can register your custom business logic. The pipeline stage specified indicates at which stage of the plugin execution cycle, your plugin code runs. Out of all the specified pipeline stages in the following table, you can register your custom plugins only on Pre- and Post-events. You can’t register plugins on Platform Core Main Operations. Whenever the CRM application invokes an event (like saving or updating a record), the following sequence of actions takes place − The event triggers a Web service call and the execution is passed through the event pipeline stages (pre-event, platform core operations, post-event). The event triggers a Web service call and the execution is passed through the event pipeline stages (pre-event, platform core operations, post-event). The information is internally packaged as an OrganizationRequest message and finally sent to the internal CRM Web service methods and platform core operations. The information is internally packaged as an OrganizationRequest message and finally sent to the internal CRM Web service methods and platform core operations. The OrganizationRequest message is first received by pre-event plugins, which can modify the information before passing it to platform core operations. After the platform core operations, the message is packaged as OrganizationResponse and passed to the post-operation plugins. The postoperations plugins can optionally modify this information before passing it to the async plugin. The OrganizationRequest message is first received by pre-event plugins, which can modify the information before passing it to platform core operations. After the platform core operations, the message is packaged as OrganizationResponse and passed to the post-operation plugins. The postoperations plugins can optionally modify this information before passing it to the async plugin. The plugins receive this information in the form of context object that is passed to the Execute method after which the further processing happens. The plugins receive this information in the form of context object that is passed to the Execute method after which the further processing happens. After all the plugin processing completes, the execution is passed back to the application which triggered the event. After all the plugin processing completes, the execution is passed back to the application which triggered the event. Messages are the events on which the plugin (or business logic) is registered. For example, you can register a plugin on Create Message of Contact entity. This would fire the business logic whenever a new Contact record is created. For custom entities, following are the supported messages based on whether the entity is user-owned or organization-owned. For default out-of-the-box entities, there are more than 100 supported messages. Some of these messages are applicable for all the entities while some of them are specific to certain entities. You can find the complete list of supported message in an excel file inside the SDK: SDK\Message-entity support for plug-ins.xlsx In this section, we will learn the basics of writing a plugin. We will be creating a sample plugin that creates a Task activity to follow-up with the customer whenever a new customer is added to the system, i.e. whenever a new Contactrecord is created in CRM. First of all, you would need to include the references to Microsoft.Xrm.Sdk namespace. The CRM SDK contains all the required SDK assemblies. Assuming that you have already downloaded and installed the SDK in Chapter 2, open Visual Studio. Create a new project of type Class Library. You can name the project as SamplePlugins and click OK. Add the reference of Microsoft.Xrm.Sdk assembly to your project. The assembly is present in SDK/Bin. Now, create a class named PostCreateContact.cs and extend the class from IPlugin. Till now, your code will look something like the following. You will also need to add reference to System.Runtime.Serialization. Once you have added the required references, copy the following code inside the PostCreateContact class. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Xrm.Sdk; namespace SamplePlugins { public class PostCreateContact:IPlugin { /// A plug-in that creates a follow-up task activity when a new account is created. /// Register this plug-in on the Create message, account entity, /// and asynchronous mode. public void Execute(IServiceProviderserviceProvider) { // Obtain the execution context from the service provider. IPluginExecutionContext context =(IPluginExecutionContext) serviceProvider.GetService(typeof(IPluginExecutionContext)); // The InputParameters collection contains all the data passed in the message request. if(context.InputParameters.Contains("Target")&& context.InputParameters["Target"]isEntity) { // Obtain the target entity from the input parameters. Entity entity = (Entity)context.InputParameters["Target"]; try { // Create a task activity to follow up with the account customer in 7 days Entity followup = new Entity("task"); followup["subject"] = "Send e-mail to the new customer."; followup["description"] = "Follow up with the customer. Check if there are any new issues that need resolution."; followup["scheduledstart"] = DateTime.Now; followup["scheduledend"] = DateTime.Now.AddDays(2); followup["category"] = context.PrimaryEntityName; // Refer to the contact in the task activity. if(context.OutputParameters.Contains("id")) { Guid regardingobjectid = new Guid(context.OutputParameter s["id"].ToString()); string regardingobjectidType = "contact"; followup["regardingobjectid"] = new EntityReference(rega rdingobjectidType,regardingobjectid); } // Obtain the organization service reference. IOrganizationServiceFactory serviceFactory = (IOrganizationSer viceFactory)serviceProvider.GetService (typeof(IOrganizationServiceFactory)); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); // Create the followup activity service.Create(followup); } catch(Exception ex) { throw new InvalidPluginExecutionException(ex.Message); } } } } } Following is a step-by-step explanation of what this code does − Step 1 − Implements the Execute method by taking IServiceProvider object as its parameter. The service provider contains references to many useful objects that you are going to use within plugin. Step 2 − Obtains the IPluginExecutionContext object using the GetService method of IServiceProvider. Step 3 − Gets the target entity’s object from the context object’s InputParameters collection. This Entity class object refers to the Contact entity record on which our plugin would be registered. Step 4 − It then creates an object of Task entity and sets proper subject, description, dates, category and regardingobjectid. The regardingobjectid indicates for which contact record this activity record is being created. You can see that the code gets the id of the parent Contact record using context.OutputParameters and associates it with the Task entity record which you have created. Step 5 − Creates object of IOrganizationServiceFactory using the IServiceProvider object. Step 6 − Creates object of IOrganizationService using the IOrganizationServiceFactory object. Step 7 − Finally, using the Create method of this service object. It creates the follow-up activity which gets saved in CRM. This section is applicable only if you are registering your plugin assembly for the first time. You need to sign in the assembly with a key to be able to deploy the plugin. Rightclick the solution and click Properties. Select the Signing tab from the left options and check the ‘Sign the assembly’ option. Then, select New from Choose a strong name key file option. Enter the Key file name as sampleplugins (This can be any other name you want). Uncheck the Protect my key file with a password option and click OK. Click Save. Finally, build the solution. Right Click → Build. Building the solution will generate assembly DLL, which we will use in the next chapter to register this plugin. More often than not, your plugin logic will need to handle run-time exceptions. For synchronous plugins, you can return an InvalidPluginExecutionException exception, which will show an error dialog box to the user. The error dialog will contain the custom error message that you pass to the Message object of the exception object. If you look at our code, we are throwing the InvalidPluginExecutionException exception in our catch block. throw new InvalidPluginExecutionException(ex.Message); Plugins are definitely crucial to any custom CRM implementation. In this chapter, we focused on understanding the event framework model, pipeline stages, messages, and writing a sample plugin. In the next chapter, we will register this plugin in CRM and see it working from end-to-end scenario. In the last chapter, we created a sample plugin to create a follow-up Task activity when a Contact record is created. In this chapter, we will see how to register this plugin in CRM using Plugin Registration Tool. You can find the tool at this location: SDK/Tools/PluginRegistration/PluginRegistration.exe. For convenience, the plugin registration process is divided into three sections − Connecting to the Server Registering the Assembly Registering the Plugin Step 1 − Run the PluginRegistration.exe from the location specified earlier. Click the Create New Connection button. Step 2 − In the Login window, choose Office 365 since we are using the online version of CRM. Enter your credentials and click Login. Step 3 − The tool will open and look like the following screenshot. Step 1 − Go to Register → Register New Assembly. Step 2 − This will open the Register New Assembly window. Click the Navigate icon and locate the Plugin DLL that you created in the last chapter. Step 3 − After navigating the DLL, click Load Assembly. This will populate the SamplePlugins assembly and all its plugin classes. You can see the PostCreateContact plugin class highlighted below. If your plugin assembly had 3 plugin classes, it would have shown three plugins listed there. Step 4 − Select Isolation Mode as Sandbox, Location as Database and click Register Selected Plugins. It will show you a success message, if the registration is successful. Now we will be registering the specific steps on which the individual plugins will be called. Step 1 − Select the PostCreateContact plugin. Step 2 − Click Register → Register New Step. Step 3 − We will be registering this plugin on the creation of the Contact entity, on postoperation stage and in the synchronous mode. Message − Create Primary Entity − Contact Event Pipeline Stage of Execution − Post-operation Execution Mode − Synchronous Keep the rest of the options by default and click Register New Step. You can see a new step added to the plugin. Now we will go to CRM and test if our plugin is working correctly. Note that these test steps are specific to our example plugin. Go to Contacts tab and create a new record. Once you save the record, you can see a new activity created and associated with this record. You can click the activity to see the details that we had set in the code. This confirms that our plugin ran successfully. Similarly, you can extend your plugins to achieve highly complex functionalities. Microsoft Dynamics CRM provides two important web services that are used to access CRM from an external application and invoke web methods to perform common business data operations such as create, delete, update, and find in CRM. Consider the following scenarios − You have an external .NET application, which needs to talk to CRM. For example, you may want to insert a Contact record in CRM when a new customer is registered in your external application. You have an external .NET application, which needs to talk to CRM. For example, you may want to insert a Contact record in CRM when a new customer is registered in your external application. Or maybe, you want to search records in CRM and display the search results in your external application. Or maybe, you want to search records in CRM and display the search results in your external application. In such scenarios, you can use the web services exposed by CRM to consume them in your application and perform create, delete, update, and find operations in CRM. This web service returns a list of organizations that the specified user belongs to and the URL endpoint for each of the organization. This web service is the primary web service used for accessing data and metadata in CRM. The IOrganizationService uses two important assemblies –Microsoft.Xrm.Sdk.dll and Microsoft.Crm.Sdk.Proxy.dll. These assemblies can be found in the CRM SDK package inside the Bin folder. Microsoft.Xrm.Sdk.dll This assembly defines the core xRM methods and types, including proxy classes to make the connection to Microsoft Dynamics CRM simpler, authentication methods, and the service contracts. Microsoft.Crm.Sdk.Proxy.dll This assembly defines the requests and responses for non-core messages as well as enumerations required for working with the organization data. Following are the namespaces supported by these two assemblies. Each of these assemblies support certain messages, which will be used to work with the data stored in any entity. A complete list of messages supported by them can be found in the following links − Supported xRM Messages − https://msdn.microsoft.com/en-us/library/gg334698.aspx Supported CRM Messages − https://msdn.microsoft.com/en-us/library/gg309482.aspx The IOrganizationService provides eight methods that allows you to perform all the common operations on the system and custom entities as well as organization metadata. IOrganizationService.Create Creates a record. IOrganizationService.Update Updates an existing record. IOrganizationService. Retrieve Retrieves a record. IOrganizationService. RetrieveMultiple Retrieves a collection of records. IOrganizationService. Delete Deletes a record. IOrganizationService. Associate Creates a link between records. IOrganizationService.Disassociate Deletes a link between records. IOrganizationService.Execute Used for common record processing as well as specialized processing such as case resolution, duplicate detection, etc. To understand how the web services work in CRM, we will look at an example provided by CRM SDK. In this example, we will create a new Account record, update it, and then finally delete it using the CRM IOrganizationService web service. Step 1 − Open the folder where you had extracted CRM SDK. Now open the QuickStartCS.sln solution by browsing to the following location:SDK\SampleCode\CS\QuickStart Step 2 − We will be exploring the QuickStart with Simplified Connection project. Open app.config in this project. By default, the connectionStrings section in this file will be commented. From this, uncomment the first connection string key and edit the following three details − Url − Specify the URL of your CRM instance. In our case, since we are using the online version of CRM, you will have to mention that URL. Username − Your CRM Online user name. Password − Your CRM Online password. Step 3 − Open the SimplifiedConnection.cs file in this project and Runmethod inside it. public void Run(StringconnectionString, boolpromptforDelete) { try { // Establish a connection to the organization web service using CrmConnection. Microsoft.Xrm.Client.CrmConnection connection = CrmConnection.Parse(connectionString); // Obtain an organization service proxy. // The using statement assures that the service proxy will be properly disposed. using(_orgService = new OrganizationService(connection)) { //Create any entity records this sample requires. CreateRequiredRecords(); // Obtain information about the logged on user from the web service. Guid userid = ((WhoAmIResponse)_orgService.Execute(new WhoAmIRequest())).UserId; SystemUser systemUser = (SystemUser)_orgService.Retrieve("systemuser",userid, new ColumnSet(newstring[]{"firstname","lastname"})); Console.WriteLine("Logged on user is {0} {1}.", systemUser.FirstName,systemUser.LastName); // Retrieve the version of Microsoft Dynamics CRM. RetrieveVersionRequest versionRequest = new RetrieveVersionRequest(); RetrieveVersionResponse versionResponse = (RetrieveVersionResponse)_orgService.Execute(versionRequest); Console.WriteLine("Microsoft Dynamics CRM version {0}.", versionResponse.Version); // Instantiate an account object. Note the use of option set enumerations defined in OptionSets.cs. // Refer to the Entity Metadata topic in the SDK documentation to determine which attributes must // be set for each entity. Account account = new Account{Name = "Fourth Coffee"}; account.AccountCategoryCode = new OptionSetValue( (int)AccountAccountCateg oryCode.PreferredCustomer); account.CustomerTypeCode = new OptionSetValue( (int)AccountCustomerTypeCod e.Investor); // Create an account record named Fourth Coffee. _accountId = _orgService.Create(account); Console.Write("{0} {1} created, ",account.LogicalName,account.Name); // Retrieve the several attributes from the new account. ColumnSet cols = new ColumnSet( new String[]{"name","address1_postalcode","lastusedincampaign"}); Account retrievedAccount = (Account)_orgService.Retrieve("account", _accountId, cols); Console.Write("retrieved, "); // Update the postal code attribute. retrievedAccount.Address1_PostalCode = "98052"; // The address 2 postal code was set accidentally, so set it to null. retrievedAccount.Address2_PostalCode = null; // Shows use of a Money value. retrievedAccount.Revenue = new Money(5000000); // Shows use of a Boolean value. retrievedAccount.CreditOnHold = false; // Update the account record. _orgService.Update(retrievedAccount); Console.WriteLine("and updated."); // Delete any entity records this sample created. DeleteRequiredRecords(promptforDelete); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch(FaultException<microsoft.xrm.sdk.organizationservicefault>) { // You can handle an exception here or pass it back to the calling method. throw; } } Step 4 − This method basically demonstrates all the CRUD operations using CRM web services. The code first creates an organization instance, then creates an Account record, updates the created record and then finally deletes it. Let us look at the important components of this code. To see on-the-go changes in CRM when this code runs, you can debug this code step-by-step (as we discuss below) and simultaneously see the changes in CRM. Step 4.1 − Establishes the connection to the organization using the connection string that we had modified in Step 2. Microsoft.Xrm.Client.CrmConnection connection = CrmConnection.Parse(connectionString); Step 4.2 − Obtains a proxy instance of CRM organization web service. _orgService = new OrganizationService(connection) Step 4.3 − Creates a new Account entity object and sets its Name, AccountCategoryCode and CustomerTypeCode. Account account = new Account{Name = "Fifth Coffee"}; account.AccountCategoryCode = new OptionSetValue( (int)AccountAccountCategoryCode.P referredCustomer); account.CustomerTypeCode = new OptionSetValue( (int)AccountCustomerTypeCode.Investor); Step 4.4 − Creates the new record using the Create method of organization service. _accountId = _orgService.Create(account); If you navigate to CRM, you will see a newly created account record. Step 4.5 − Once the account gets created, the service retrieves back the record from CRM using Retrieve web service method. ColumnSet cols = new ColumnSet(new String[]{ "name","address1_postalcode","lastusedincampaign"}); Account retrievedAccount = (Account)_orgService.Retrieve("account", _accountId, cols); Step 4.6 − Once you have the retrieved record, you can set the updated value of the record. retrievedAccount.Address1_PostalCode = "98052"; retrievedAccount.Address2_PostalCode = null; retrievedAccount.Revenue = new Money(5000000); retrievedAccount.CreditOnHold = false; Step 4.7 − After setting the updated value of the record, update the record back to CRM database using the Update web service method. _orgService.Update(retrievedAccount); If you open the record in CRM, you will see these values updated there. Step 4.8 − Finally, delete the record using the Delete web service method. _orgService.Delete(Account.EntityLogicalName, _accountId); If you now refresh the same record in CRM, you will see that the record is no more available since it is already deleted. In this chapter, we dealt with two important web services provided by CRM and a working example of how these web services can be used from an external application to perform various CRUD operations. Solutions provide a framework for packaging, installing, and uninstalling components to match your business functionalities. Solutions allow the customizers and developers to author, package, and maintain units of software that extend CRM. Any customizations, extensions, or configurations performed in CRM are packaged, managed, and distributed using solutions. The solutions can be exported as a zip file from the source organization, which can then be imported in the target organization. For understanding this, consider the following example scenarios − You, as a developer or customizer, have extended or customized CRM in the development environment. Now you want to package your changes and move it to the next environment. For this, you can create individual solutions and publish them in higher environments. You, as a developer or customizer, have extended or customized CRM in the development environment. Now you want to package your changes and move it to the next environment. For this, you can create individual solutions and publish them in higher environments. You, as a third party CRM provider, have created a CRM module, which allows managing data in Microsoft Dynamics CRM entities using external Web service APIs. Now, you want to sell this module to other clients. Using solutions, you can package this module and distribute them to other clients who will be able to install this solution and use the functionalities provided by your module. You, as a third party CRM provider, have created a CRM module, which allows managing data in Microsoft Dynamics CRM entities using external Web service APIs. Now, you want to sell this module to other clients. Using solutions, you can package this module and distribute them to other clients who will be able to install this solution and use the functionalities provided by your module. The system solution contains the out-of-the-box solution components defined within Microsoft Dynamics CRM without any customizations. Many of the components in the system solution are customizable and can be used in managed solutions or unmanaged customizations. Throughout this tutorial, we did not create any solution and were customizing the default system solution. If you recall, we went to Settings → Customizations → Customize the System. This option directly customizes the default solution. A managed solution is a solution that is completed and intended to be distributed and installed. Managed solutions can be installed on the top of the system solution or other managed solutions. Important Points − If you export a managed solution from one organization and import it to another, you can’t edit the solution in the new organization. If you export a managed solution from one organization and import it to another, you can’t edit the solution in the new organization. A managed solution does not directly reference the system solution. A managed solution does not directly reference the system solution. Uninstalling a managed solution uninstalls all the customizations associated with the solution. Uninstalling a managed solution uninstalls all the customizations associated with the solution. By default, a managed solution can’t be customized in the target organization. However, using the concept of managed properties you can define whether a solution component will be customizable and if yes, then which specific parts of the component will be customizable once the solution gets exported as a managed solution. By default, a managed solution can’t be customized in the target organization. However, using the concept of managed properties you can define whether a solution component will be customizable and if yes, then which specific parts of the component will be customizable once the solution gets exported as a managed solution. An unmanaged solution is a solution that is still under development and not intended to be distributed. An unmanaged solution contains all the unmanaged customizations of CRM components including any added, modified, removed, or deleted components. By default, any new solution is an unmanaged solution. However, you can export an unmanaged solution as a managed or unmanaged solution. Important Points − If you export an unmanaged solution from one organization and import it to another, you can edit the solution in the new organization. If you export an unmanaged solution from one organization and import it to another, you can edit the solution in the new organization. An unmanaged solution directly references the system solution. Hence, the changes made to one unmanaged solution will be applied to all the unmanaged solutions that references the same components, including the system solution. An unmanaged solution directly references the system solution. Hence, the changes made to one unmanaged solution will be applied to all the unmanaged solutions that references the same components, including the system solution. If you delete a solution component from an unmanaged solution, the component gets deleted permanently from the system and will no longer be available. In case you just want to remove the component from specific unmanaged solution, use remove instead of delete. If you delete a solution component from an unmanaged solution, the component gets deleted permanently from the system and will no longer be available. In case you just want to remove the component from specific unmanaged solution, use remove instead of delete. Uninstalling an unmanaged solution does not remove the associated customizations. It just deletes the solution from the system, but the changes you made will still be there. Uninstalling an unmanaged solution does not remove the associated customizations. It just deletes the solution from the system, but the changes you made will still be there. A solution can be used to package the following components which can be customized using default, unmanaged, or managed solutions. Step 1 − Navigate to Settings → Solutions. Click New. Step 2 − In the window that follows, enter the following details and click Save and Close. Display Name − Sample Solution (This can be any name that you want). Name − Will be automatically set based on the Display Name. However, you can change this. Publisher − Default Publisher. Solution publisher provides a common customization prefix and option value prefix. Defining a solution publisher controls how your managed solutions can be updated once distributed. However, for this example and for most of the general cases, you can set this as Default Publisher. Version − Specify a version with the following format: major.minor.build.revision. For example: 1.0.0.0. By default, every solution is added as an unmanaged solution. Once a solution is added, you can add solution components by creating them in the context of this solution or by adding the existing components from other solutions. For example, you can create new entities, forms, etc. in the context of this new solution. Once you have all the changes in place that you want to package as a managed or unmanaged solution, you can export your solution as follows. Step 1 − Open the source organization and navigate to Settings → Solutions. Select the solution that you want to export and click the Export button. Step 2 − In the Publish Customizations window, click Publish All Customizations and then click Next. Step 3 − In the window that follows, you can optionally select any system setting such as auto-numbering, calendar settings, etc. to be exported with the solution. For now, you can avoid selecting any option and click Next. Step 4 − In the Package Type window, you can select whether you want to export the package as a managed or unmanaged solution. For this example, let us export it as unmanaged. Once done, click Next. Step 5 − In the next window, you can see the source version of CRM that you are using and can select the target version. Click Export. Step 6 − Once you click Export, the solution will be exported as a zip file. Save this zip file at a desired location on your system. Now, we will import the solution zip file that we exported in the previous section to a new target organization. Step 1 − Open the target organization and navigate to Settings → Solutions. Click Import. Step 2 − Browse the zip file that you downloaded from the export step and click Next. Step 3 − From the next window, you can view the solution package details if needed. Clicking Import will start the solution import process. Step 4 − Once the import process completes, it will show the status of success or failure. If the process succeeds, click Publish All Customizations. In case the solution importing fails, it will give you a detailed error log on which step of the import process failed. Step 5 − We’re done. The solution will be successfully imported to the target organization. Click Close. Since you can have multiple developers working on customizing and extending CRM, you will have multiple managed and unmanaged solutions. Exporting and importing these solutions can sometimes result in conflict scenarios. For example, suppose ‘Solution A’ contains a field on a form while ‘Solution B’ has removed the field and ‘Solution C’ has renamed the field. In this scenario, what would be the final change? In such conflicting scenarios, CRM uses two approaches. Merge − This approach is used for user interface components such as command bar, ribbons and site maps. As per this approach, the solution components are re-calculated from the bottom and the organization’s unmanaged customizations are the last to apply. Top Wins − This approach is used for all other conflict scenarios except the user interface components. As per this approach, the last change (either managed or unmanaged) takes the priority and gets applied. In this chapter, we introduced the concept of solutions and different types of solution and their components. We then learnt how to create, export, and import a solution. Finally, we studied about the two conflict resolution strategies, which takes place when we have multiple managed and unmanaged solution affecting the same solution components. 16 Lectures 11.5 hours SHIVPRASAD KOIRALA 33 Lectures 3 hours Abhishek And Pukhraj 33 Lectures 5.5 hours Abhishek And Pukhraj 40 Lectures 6.5 hours Syed Raza 15 Lectures 2 hours Harshit Srivastava, Pranjal Srivastava 18 Lectures 1.5 hours Pranjal Srivastava, Harshit Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2447, "s": 2041, "text": "Customer Relationship Management (CRM) is a system for managing a company’s interactions with current and future customers. It often involves using technology to organize, automate, and synchronize sales, marketing, customer service, and technical support. CRM can help reduce costs and increase profitability by organizing and automating business processes that nurture customer satisfaction and loyalty." }, { "code": null, "e": 2951, "s": 2447, "text": "Microsoft Dynamics CRM is a customer relationship management software package developed by Microsoft focused on enhancing the customer relationship for any organization. Out of the box, the product focuses mainly on Sales, Marketing, and Customer Service sectors, though Microsoft has been marketing Dynamics CRM as an XRM platform and has been encouraging partners to use its proprietary (.NET based) framework to customize it. In recent years, it has also grown as an Analytics platform driven by CRM." }, { "code": null, "e": 3333, "s": 2951, "text": "The CRM Solution can be used to drive the sales productivity and marketing effectiveness for an organization, handle the complete customer support chain, and provide social insights, business intelligence, and a lot of other out-of-the-box functionalities and features. As a product, Microsoft Dynamics CRM also offers full mobile support for using CRM apps on mobiles and tablets." }, { "code": null, "e": 3671, "s": 3333, "text": "As of writing this tutorial, the latest version of CRM is CRM 2016. However, in this tutorial we will be using CRM 2015 Online version as it is the latest stable version as well as frequently used in many organizations. Nevertheless, even if you are using any other versions of CRM, all the concepts in the tutorial will still hold true." }, { "code": null, "e": 3725, "s": 3671, "text": "Microsoft Dynamics CRM is offered in two categories −" }, { "code": null, "e": 4228, "s": 3725, "text": "CRM Online is a cloud-based offering of Microsoft Dynamics CRM where all the backend processes (such as application servers, setups, deployments, databases, licensing, etc.) are managed on Microsoft servers. CRM Online is a subscription-based offering which is preferred for organizations who may not want to manage all the technicalities involved in a CRM implementation. You can get started with setting up your system in a few days (not weeks, months or years) and access it on web via your browser." }, { "code": null, "e": 4691, "s": 4228, "text": "CRM on-premise is a more customized and robust offering of Microsoft Dynamics CRM, where the CRM application and databases will be deployed on your servers. This offering allows you to control all your databases, customizations, deployments, backups, licensing and other network and hardware setups. Generally, organizations who want to go for a customized CRM solution prefer on-premise deployment as it offers better integration and customization capabilities." }, { "code": null, "e": 4891, "s": 4691, "text": "From the functional standpoint, both the offerings offer similar functionalities; however, they differ significantly in terms of implementation. The differences are summarized in the following table." }, { "code": null, "e": 4965, "s": 4891, "text": "Microsoft Dynamics CRM can be accessed via any of the following options −" }, { "code": null, "e": 4973, "s": 4965, "text": "Browser" }, { "code": null, "e": 4992, "s": 4973, "text": "Mobile and Tablets" }, { "code": null, "e": 5000, "s": 4992, "text": "Outlook" }, { "code": null, "e": 5164, "s": 5000, "text": "Microsoft Dynamics CRM is undoubtedly one of the top products in the CRM space. However, following are the other products that compete with Microsoft Dynamics CRM." }, { "code": null, "e": 5179, "s": 5164, "text": "Salesforce.com" }, { "code": null, "e": 5186, "s": 5179, "text": "Oracle" }, { "code": null, "e": 5190, "s": 5186, "text": "SAP" }, { "code": null, "e": 5199, "s": 5190, "text": "Sage CRM" }, { "code": null, "e": 5209, "s": 5199, "text": "Sugar CRM" }, { "code": null, "e": 5218, "s": 5209, "text": "NetSuite" }, { "code": null, "e": 5420, "s": 5218, "text": "Microsoft Dynamics CRM has grown over the years starting from its 1.0 version in 2003. The latest version (as of writing this article) is 2015. Following is the chronological list of release versions −" }, { "code": null, "e": 5438, "s": 5420, "text": "Microsoft CRM 1.0" }, { "code": null, "e": 5456, "s": 5438, "text": "Microsoft CRM 1.2" }, { "code": null, "e": 5483, "s": 5456, "text": "Microsoft Dynamics CRM 3.0" }, { "code": null, "e": 5510, "s": 5483, "text": "Microsoft Dynamics CRM 4.0" }, { "code": null, "e": 5538, "s": 5510, "text": "Microsoft Dynamics CRM 2011" }, { "code": null, "e": 5566, "s": 5538, "text": "Microsoft Dynamics CRM 2013" }, { "code": null, "e": 5594, "s": 5566, "text": "Microsoft Dynamics CRM 2015" }, { "code": null, "e": 5622, "s": 5594, "text": "Microsoft Dynamics CRM 2016" }, { "code": null, "e": 5852, "s": 5622, "text": "Let's start by setting up our CRM environment. We will be using the online version of CRM 2015, since the online version provides one-month free trial access. By doing this, you will not need to purchase any license to learn CRM." }, { "code": null, "e": 6338, "s": 5852, "text": "Note − Since Microsoft Dynamics CRM is a growing product, it is possible that by the time you are learning this, you will have a newer version of the product. In that case, the application may not look exactly as you would see in the screenshots of this tutorial. However, the core concepts of the product remain the same. The look-and-feel and the navigation of the product may change, however, in most of the cases you will be able to easily navigate and locate the required options." }, { "code": null, "e": 6379, "s": 6338, "text": "Step 1 − Navigate to the following URL −" }, { "code": null, "e": 6428, "s": 6379, "text": "https://www.microsoft.com/en-us/dynamics365/home" }, { "code": null, "e": 6571, "s": 6428, "text": "In case you do not see the options of Trial version via this link in future, just try searching \"Microsoft Dynamics CRM Free Trial\" on Google." }, { "code": null, "e": 6793, "s": 6571, "text": "Step 2 − Click the Try it free button. This will start a 3-step registration process as shown in the following screenshot. In Step 1 of 3-step registration, fill in the mandatory details such as name, email, and language." }, { "code": null, "e": 7015, "s": 6793, "text": "Step 3 − Click the Try it free button. This will start a 3-step registration process as shown in the following screenshot. In Step 1 of 3-step registration, fill in the mandatory details such as name, email, and language." }, { "code": null, "e": 7293, "s": 7015, "text": "Step 4 − In Step 3 of 3-step registration, Microsoft will validate the mobile number that you have specified. For this, you can provide your mobile number and click Text me. It will then send an OTP to your mobile using which you will be able to proceed further with the setup." }, { "code": null, "e": 7399, "s": 7293, "text": "Step 5 − Your Office 365 user ID will be created. You can save this user ID information for later access." }, { "code": null, "e": 7511, "s": 7399, "text": "After setting up the account, it will now open your CRM Dashboard which will look something like the following." }, { "code": null, "e": 7660, "s": 7511, "text": "Just to emphasize again, the screenshots above may change with a future version, however setting up the environment will be a pretty simple process." }, { "code": null, "e": 8244, "s": 7660, "text": "The Software Development Kit (SDK) of Microsoft Dynamics CRM contains important code samples including server side code, client side code, extensions, plugins, web services, workflows, security model, etc. Basically, the SDK contains every development resource that you would need to get started with CRM. Whether you are planning to set up a new plugin project or setting up a web services project for CRM, the SDK provides the basic architecture and examples ranging from simple to advanced level to help you kick-off. We will now look at the steps to download and install the SDK." }, { "code": null, "e": 8531, "s": 8244, "text": "Step 1 − Every version of Microsoft Dynamics CRM comes with its own SDK version. The best way to get the correct SDK version would be to search on Google for your respective CRM version. For example, if your CRM version is 2015, then try searching for \"Microsoft Dynamics CRM 2015 SDK\"." }, { "code": null, "e": 8592, "s": 8531, "text": "Step 2 − Once downloaded, run the exe setup. Click Continue." }, { "code": null, "e": 8755, "s": 8592, "text": "Step 3 − It will ask you to choose the location where the SDK should be extracted. Select any appropriate location where you would like to keep the reference SDK." }, { "code": null, "e": 8851, "s": 8755, "text": "Step 4 − Open the folder where you had extracted. You can access all the SDK content from here." }, { "code": null, "e": 9171, "s": 8851, "text": "In this chapter, we have set up our environment by creating a CRM Online account. We then downloaded the CRM SDK, which will be used in the subsequent chapters of this tutorial. Make sure to note down the credentials with which you have set up the account, since you will need these credentials the next time you login." }, { "code": null, "e": 9258, "s": 9171, "text": "The entire Microsoft Dynamics CRM is designed around the following functional modules." }, { "code": null, "e": 9264, "s": 9258, "text": "Sales" }, { "code": null, "e": 9274, "s": 9264, "text": "Marketing" }, { "code": null, "e": 9293, "s": 9274, "text": "Service Management" }, { "code": null, "e": 9350, "s": 9293, "text": "These functional modules are often called as Work Areas." }, { "code": null, "e": 9703, "s": 9350, "text": "The entire CRM application is divided functionally for different types of users and teams. Hence, if an organization is using CRM to manage its processes, the users from the Sales team would use the functionalities that come under the Sales module, while the users from the Marketing team would use functionalities that fall under the Marketing module." }, { "code": null, "e": 9916, "s": 9703, "text": "All these three functional modules come together to drive the entire lifecycle of gaining a new customer (Marketing), selling them the services (Sales) and maintaining the existing customers (Service Management)." }, { "code": null, "e": 10208, "s": 9916, "text": "To understand this flow in a better way, consider a bank which sells credit cards to its customers. The typical lifecycle of selling a credit card to a customer would be as follows. In each step of this lifecycle, you will see how the Sales, Marketing and Service modules perform their role." }, { "code": null, "e": 10434, "s": 10208, "text": "Sales & Marketing − The bank’s call center office executive receives data of potential customers; often called as Leads in CRM. These Leads are captured in the CRM system via marketing campaigns, sales drives, referrals, etc." }, { "code": null, "e": 10667, "s": 10434, "text": "Sales − The call center executive communicates with these Leads either through phone calls/emails/etc. If the customer is interested in the credit card offering, the Lead record will be converted to an Opportunity record (won Lead)." }, { "code": null, "e": 11059, "s": 10667, "text": "Service − Once a customer becomes a part of the system, the company would assist him/her with payments, billing, refunds, etc. Whenever the customer has any queries or concerns, they will make a call to the call center and raise incidents. The executive will followup to resolve the case with the aim to provide quality service to the customer. These tasks fall under CRM Service Management." }, { "code": null, "e": 11088, "s": 11059, "text": "Step 1 − Open CRM Home Page." }, { "code": null, "e": 11155, "s": 11088, "text": "Step 2 − By default, you will see the Sales work area as selected." }, { "code": null, "e": 11293, "s": 11155, "text": "Step 3 − To change the work area, click the Show work areas option. You will see the options for selecting Sales, Service, and Marketing." }, { "code": null, "e": 11559, "s": 11293, "text": "Step 4 − Click Sales. This will show you all the entities which fall under Sales such as Accounts, Contacts, Leads, Opportunities, Competitors, etc. Each of these entities are categorized by their business process such as My Work, Customers, Sales, Collateral, etc." }, { "code": null, "e": 11694, "s": 11559, "text": "Step 5 − Similarly, if you click the Marketing work area, you will see all the entities related to Marketing business functionalities." }, { "code": null, "e": 11842, "s": 11694, "text": "The Sales module of CRM is designed to drive the entire sales lifecycle of a new customer. The Sales module consists of the following sub-modules −" }, { "code": null, "e": 12023, "s": 11842, "text": "Leads − Represents a person or an organization that can be a potential customer to the company in future. This is the first step towards getting a potential customer in the system." }, { "code": null, "e": 12208, "s": 12023, "text": "Opportunities − Represents a potential sale to the customer. Once a Lead shows interest in the offering, it gets converted to an Opportunity. An Opportunity will either be won or lost." }, { "code": null, "e": 12361, "s": 12208, "text": "Accounts − Represents a company with which the organization has relations. Once an Opportunity wins, it gets converted to either an Account or Contacts." }, { "code": null, "e": 12636, "s": 12361, "text": "Contacts − Represents a person, or any individual with whom the organization has relations. Mostly these Contacts are the customers of the organizations (e.g. all credit card customers of a bank). Once an Opportunity wins, it gets converted to either an Account or Contacts." }, { "code": null, "e": 12706, "s": 12636, "text": "Competitors − Manages all the market competitors of the organization." }, { "code": null, "e": 12825, "s": 12706, "text": "Products − Manages all the products offered by the organization to its customers (Example, all the credit card plans)." }, { "code": null, "e": 13011, "s": 12825, "text": "Quotes − A formal offer for products or services proposed at specific prices sent to a prospective customer (Example, yearly pricing of a certain credit card plan sent to the customer)." }, { "code": null, "e": 13188, "s": 13011, "text": "Orders − A quote that gets accepted by the customer turns into an Order (Example, out of all the plans that the organization offers you, you may go for a 6-month subscription)." }, { "code": null, "e": 13236, "s": 13188, "text": "Invoices − A billed order generates an invoice." }, { "code": null, "e": 13436, "s": 13236, "text": "The Marketing module of CRM is designed to drive the entire marketing process of an organization for its existing and potential customers. The Marketing module consists of the following sub-modules −" }, { "code": null, "e": 13750, "s": 13436, "text": "Marketing Lists − Provides a way to group your Contacts, Accounts, and Leads and interact with them via sending promotional emails, event details, newsletters and other updates relevant to the target customers. You can define the criteria to create your marketing lists (Example, contacts aged between 25 and 35)." }, { "code": null, "e": 14008, "s": 13750, "text": "Campaigns − Campaigns are designed to measure the effectiveness and accomplish a specific result, such as introducing a new product or increasing the market share and may include various communication channels such as email, newspaper ads, YouTube ads, etc." }, { "code": null, "e": 14122, "s": 14008, "text": "Quick Campaigns − A Quick Campaign is similar to Campaign however it can be related to only one type of activity." }, { "code": null, "e": 14205, "s": 14122, "text": "All the above Marketing modules work in close co-ordination with the Sales module." }, { "code": null, "e": 14437, "s": 14205, "text": "The Service Management module of CRM is designed to focus, manage, and track the customer service operations of an organization such as supporting the incident-based services, supporting the customers using service scheduling, etc." }, { "code": null, "e": 14502, "s": 14437, "text": "The Service Management module covers the following sub-modules −" }, { "code": null, "e": 14718, "s": 14502, "text": "Cases (Incidents) − Supports any customer requests, issues, or complaints to be tracked via incidents/cases. A case follows various stages of an issue resolution process and then finally gets resolved and is closed." }, { "code": null, "e": 14934, "s": 14718, "text": "Cases (Incidents) − Supports any customer requests, issues, or complaints to be tracked via incidents/cases. A case follows various stages of an issue resolution process and then finally gets resolved and is closed." }, { "code": null, "e": 15057, "s": 14934, "text": "Knowledge Base − Maintains a master repository for all the common questions and answers that the customer frequently asks." }, { "code": null, "e": 15180, "s": 15057, "text": "Knowledge Base − Maintains a master repository for all the common questions and answers that the customer frequently asks." }, { "code": null, "e": 15277, "s": 15180, "text": "Contracts − Contracts work with Cases indicating all the active contracts that the customer has." }, { "code": null, "e": 15374, "s": 15277, "text": "Contracts − Contracts work with Cases indicating all the active contracts that the customer has." }, { "code": null, "e": 15562, "s": 15374, "text": "Resources/Resource Groups − Represents the people, tools, rooms, or pieces of equipment that are used to deliver a service. These resources can be used to solve a specific customer issue." }, { "code": null, "e": 15750, "s": 15562, "text": "Resources/Resource Groups − Represents the people, tools, rooms, or pieces of equipment that are used to deliver a service. These resources can be used to solve a specific customer issue." }, { "code": null, "e": 15836, "s": 15750, "text": "Services − Represents all the services that the organization offers to the customers." }, { "code": null, "e": 15922, "s": 15836, "text": "Services − Represents all the services that the organization offers to the customers." }, { "code": null, "e": 16028, "s": 15922, "text": "Service Calendar − Used to schedule work timings and schedules of the users who work in the organization." }, { "code": null, "e": 16134, "s": 16028, "text": "Service Calendar − Used to schedule work timings and schedules of the users who work in the organization." }, { "code": null, "e": 16504, "s": 16134, "text": "All the modules explained above use the Activity Management module of CRM. An Activity represents any kind of interaction with the customer such as a Phone Call, Email, Letter, etc. These activities can be related to any of the entities explained earlier such as Account, Contact, Lead, Case, etc. By default, CRM provides following types of activities out-of-the-box −" }, { "code": null, "e": 16515, "s": 16504, "text": "Phone Call" }, { "code": null, "e": 16521, "s": 16515, "text": "Email" }, { "code": null, "e": 16526, "s": 16521, "text": "Task" }, { "code": null, "e": 16538, "s": 16526, "text": "Appointment" }, { "code": null, "e": 16560, "s": 16538, "text": "Recurring Appointment" }, { "code": null, "e": 16567, "s": 16560, "text": "Letter" }, { "code": null, "e": 16571, "s": 16567, "text": "Fax" }, { "code": null, "e": 16589, "s": 16571, "text": "Campaign Response" }, { "code": null, "e": 16609, "s": 16589, "text": "Campaign Activities" }, { "code": null, "e": 16626, "s": 16609, "text": "Service Activity" }, { "code": null, "e": 16644, "s": 16626, "text": "Custom Activities" }, { "code": null, "e": 17018, "s": 16644, "text": "In this chapter, we have learnt about the three major modules of CRM – Sales, Marketing, and Service Management. We understood how the work areas are organized in CRM and how the entire lifecycle of a CRM organization works. We also looked at the Activity Management module of CRM which allows to create Phone, Email, Fax and other types of customer interaction activities." }, { "code": null, "e": 17146, "s": 17018, "text": "Now that we have a functional overview of all the CRM modules, let us learn and understand about the entities and forms in CRM." }, { "code": null, "e": 17483, "s": 17146, "text": "An entity is used to model and manage business data in CRM. Contacts, Cases, Accounts, Leads, Opportunities, Activities, etc. are all entities which hold data records. Conceptually, a CRM entity is equivalent to a database table. For example, Contacts entity would hold Contact records, Cases entity would hold Cases records, and so on." }, { "code": null, "e": 18025, "s": 17483, "text": "You can have both: out-of-the-box entities (which comes by default with the CRM) and custom entities (which you can create with customization). For instance, suppose that you are maintaining the data of the books your customers have read. For this, you will be storing the customer data using out-of-the-box Contacts entity but where would you store the books data? You do not have any entity that can store data for books. In such scenarios, you will create a new custom entity named Books and relate this with the existing Contacts entity." }, { "code": null, "e": 18456, "s": 18025, "text": "For this tutorial, let us take an example of storing employers and employees in CRM. Taking this example into consideration, out-of-the-box, CRM provides Contact entity in which you can ideally store all your employees. It also provides an Account entity in which you can store all your employers. But for the sake of learning entities, we will create a new custom entity called Employer (and not use the existing Account entity)." }, { "code": null, "e": 18615, "s": 18456, "text": "Step 1 − Click the top ribbon button followed by Settings option. Click Customizations option from the Customization section (Refer the following screenshot)." }, { "code": null, "e": 18663, "s": 18615, "text": "Step 2 − Now click Customize the System option." }, { "code": null, "e": 18827, "s": 18663, "text": "This will open up the Default Solution window. You will learn more about CRM Solutions in the next chapters but for now you will be using the default CRM Solution." }, { "code": null, "e": 18884, "s": 18827, "text": "Step 3 − Expand the Entities option from the left panel." }, { "code": null, "e": 18917, "s": 18884, "text": "Step 4 − Now click New → Entity." }, { "code": null, "e": 19202, "s": 18917, "text": "Step 5 − In the Entity Form, enter the Display Name as Employer and PluralName as Employers. In the section ‘Areas that display this entity’, check Sales, Service and Marketing. Checking these options will display the newly created entity in Sales, Service, and Marketing tabs of CRM." }, { "code": null, "e": 19310, "s": 19202, "text": "Step 6 − Click on the Save and Close icon. This will create a new entity in CRM database behind the scenes." }, { "code": null, "e": 19406, "s": 19310, "text": "Step 7 − In the Default Solution parent window, you will see the newly created Employer entity." }, { "code": null, "e": 19598, "s": 19406, "text": "Step 8 − Click Publish All Customizations option from the top ribbon bar. This will publish (aka commit) all the changes we did till now. You can close this window by clicking Save and Close." }, { "code": null, "e": 19818, "s": 19598, "text": "CRM is all about managing valuable data in your system. In this section, we will learn how to create, open, read, and delete records in CRM. We will continue with the employer entity that we created in the last chapter." }, { "code": null, "e": 19922, "s": 19818, "text": "Step 1 − Navigate to Employer entity records grid via Show work areas → Sales → Extensions → Employers." }, { "code": null, "e": 19951, "s": 19922, "text": "Step 2 − Click the New icon." }, { "code": null, "e": 20132, "s": 19951, "text": "This will open the default new employer form. You can see that there is only one editable field Name in this default form. Enter Employer 1 in the Name field. Click Save and Close." }, { "code": null, "e": 20218, "s": 20132, "text": "Step 3 − In the Active Employers view, you can see the newly created employer record." }, { "code": null, "e": 20459, "s": 20218, "text": "To access the already created records in CRM, go to that entity page. In our case, navigate to Show work areas → Sales → Extensions → Employers. You will see list of records present there in the grid. Click any Employer record to access it." }, { "code": null, "e": 20687, "s": 20459, "text": "Once you have a record open, you can just edit any details on the form. By default, CRM 2015 comes with auto-save option which saves any changes made to the form 30 seconds after the change. Alternatively, you can click Ctrl+S." }, { "code": null, "e": 20836, "s": 20687, "text": "In case you want to disable the auto-save feature, go to Settings → Administration → System Settings → Enable auto-save for all forms and select No." }, { "code": null, "e": 20930, "s": 20836, "text": "Step 1 − Select one or multiple records which you want to delete and click the Delete button." }, { "code": null, "e": 20991, "s": 20930, "text": "Step 2 − Confirm the deletion of records by clicking Delete." }, { "code": null, "e": 21345, "s": 20991, "text": "As seen in the above example, the default Employer form had only one field. However, in real life scenarios, you will have many custom fields on a form. For example, if you look at a sample Contact record (which is an out-of-the-box CRM entity), it will have many fields to store contact information such as Full Name, Email, Phone, Address, Cases, etc." }, { "code": null, "e": 21453, "s": 21345, "text": "In the next chapters, you will learn how to edit this default form and add different types of fields on it." }, { "code": null, "e": 21578, "s": 21453, "text": "Before you learn how to add custom fields to CRM forms, let us take a look at what type of data fields are supported by CRM." }, { "code": null, "e": 21661, "s": 21578, "text": "Out-of-the-box, CRM provides 11 types of data fields that can be placed on forms −" }, { "code": null, "e": 21681, "s": 21661, "text": "Single Line of Text" }, { "code": null, "e": 21703, "s": 21681, "text": "Option Set (Dropdown)" }, { "code": null, "e": 21730, "s": 21703, "text": "Two Options (Radio Button)" }, { "code": null, "e": 21736, "s": 21730, "text": "Image" }, { "code": null, "e": 21749, "s": 21736, "text": "Whole Number" }, { "code": null, "e": 21771, "s": 21749, "text": "Floating Point Number" }, { "code": null, "e": 21786, "s": 21771, "text": "Decimal Number" }, { "code": null, "e": 21795, "s": 21786, "text": "Currency" }, { "code": null, "e": 21818, "s": 21795, "text": "Multiple Lines of Text" }, { "code": null, "e": 21832, "s": 21818, "text": "Date and Time" }, { "code": null, "e": 21839, "s": 21832, "text": "Lookup" }, { "code": null, "e": 21896, "s": 21839, "text": "The following table lists each with a brief description." }, { "code": null, "e": 21916, "s": 21896, "text": "Single Line of Text" }, { "code": null, "e": 22132, "s": 21916, "text": "This field stores up to 4000 characters of text. You can also specify the format as one of these: Email, Text, Text Area, URL, Ticker Symbol, and Phone. You can set the maximum length and IME mode for each of these." }, { "code": null, "e": 22154, "s": 22132, "text": "Option Set (Dropdown)" }, { "code": null, "e": 22354, "s": 22154, "text": "This field stores a set of options each having a number value and label. In other words, it is a dropdown field in CRM. You can also define Global Option Sets which can be used across multiple forms." }, { "code": null, "e": 22381, "s": 22354, "text": "Two Options (Radio Button)" }, { "code": null, "e": 22490, "s": 22381, "text": "This field provides two options for the user to select (0 or 1). In other words, it is a radio button field." }, { "code": null, "e": 22496, "s": 22490, "text": "Image" }, { "code": null, "e": 22608, "s": 22496, "text": "When an entity has an image field, it can be configured to display the image for the record in the application." }, { "code": null, "e": 22621, "s": 22608, "text": "Whole Number" }, { "code": null, "e": 22823, "s": 22621, "text": "This field stores integer values between -2,147,483,648 and 2,147,483,647. It supports the specifying formats as None, Duration, Time Zone, and Language. You can set the minimum and maximum values too." }, { "code": null, "e": 22845, "s": 22823, "text": "Floating Point Number" }, { "code": null, "e": 23009, "s": 22845, "text": "This field stores the floating point numbers up to 5 decimal points of precision between 0.00 and 1,000,000,000.00. You can set the minimum and maximum values too." }, { "code": null, "e": 23024, "s": 23009, "text": "Decimal Number" }, { "code": null, "e": 23135, "s": 23024, "text": "This field stores up to 10 decimal points with values ranging from -100,000,000,000.00 and 100,000,000,000.00." }, { "code": null, "e": 23144, "s": 23135, "text": "Currency" }, { "code": null, "e": 23365, "s": 23144, "text": "This field is used to store any currency values in the range of 922,337,203,685,477.0000 to 922,337,203,685,477.0000. You can also specify the Precision as Pricing Decimal, Currency Precision or any value between 0 to 4." }, { "code": null, "e": 23388, "s": 23365, "text": "Multiple Lines of Text" }, { "code": null, "e": 23479, "s": 23388, "text": "This is a scrolling text box. You can set the maximum number of characters for this field." }, { "code": null, "e": 23493, "s": 23479, "text": "Date and Time" }, { "code": null, "e": 23690, "s": 23493, "text": "This field is used to store date-related data in CRM with two supported formats: Date Only, and Date and Time. You can also specify the behavior as User Local, Date Only and Time-Zone Independent." }, { "code": null, "e": 23697, "s": 23690, "text": "Lookup" }, { "code": null, "e": 23975, "s": 23697, "text": "You can create a lookup field using an entity relationship that has already been created, but not yet used with another lookup field. If you create a lookup field in an entity form, the relationship is automatically generated. A lookup field is created as a relationship field." }, { "code": null, "e": 24171, "s": 23975, "text": "In the last two chapters, you studied about creating new entities, creating new records and types of fields available in CRM. In this chapter, you will be learning to add new fields on CRM forms." }, { "code": null, "e": 24662, "s": 24171, "text": "Out of the 11 types of data fields studied in the previous chapter, you will be using three types of fields on your employer - Option Set (Dropdown), Multiple Lines of Text and DateTime. The Option Set field would be used to store the employer type, Multiple Lines of Text will be used to store brief description of employer and the DateTime field would be used to store date when the company was started. Note:You already had a Name field on your form which was a Single Line of Text type." }, { "code": null, "e": 24813, "s": 24662, "text": "Step 1 − Click the top ribbon button followed by Settings option. Click Customizations option from the Customization section (Refer screenshot below)." }, { "code": null, "e": 24865, "s": 24813, "text": "Step 2 − Now click the Customize the System option." }, { "code": null, "e": 25025, "s": 24865, "text": "This will open the DefaultSolution window. You will learn more about CRM Solutions in the next chapters but for now you will be using the default CRM Solution." }, { "code": null, "e": 25082, "s": 25025, "text": "Step 3 − Expand the Entities option from the left panel." }, { "code": null, "e": 25326, "s": 25082, "text": "Step 4 − From the expanded entities, select Employer. This will open the details of the entity on the right window. Expand Employer option from the left panel and you will be able to see Forms, Views, Charts, Fields, and other several options." }, { "code": null, "e": 25443, "s": 25326, "text": "Step 5 − Click Fields. It will open a grid showing all the fields that came by default when you created this entity." }, { "code": null, "e": 25534, "s": 25443, "text": "Step 6 − Click the New button. In the new window that opens, enter the following details −" }, { "code": null, "e": 25563, "s": 25534, "text": "Display Name − Employer Type" }, { "code": null, "e": 25707, "s": 25563, "text": "Name − This field will be populated automatically based on the display name you select. However, if you would like to change it, you can do so." }, { "code": null, "e": 26069, "s": 25707, "text": "Data Type − Option Set. As soon as you select the Data Type as Option Set, it will show you the Options panel. Clicking the plus(+) icon creates a new option set item with default Label as Item and default Value as 100,000,000. You can change the label of this item to add four options representing employer types: Private, Government, Multinational and Public." }, { "code": null, "e": 26171, "s": 26069, "text": "Step 7 − Click Save and Close from the top ribbon. You have successfully created Employer Type field." }, { "code": null, "e": 26318, "s": 26171, "text": "Step 8 − Similar to what you just did for adding Employer Type field, add three other fields as described and shown in the following screenshots −" }, { "code": null, "e": 26375, "s": 26318, "text": "Number of Employees − This will be a Whole Number field." }, { "code": null, "e": 26419, "s": 26375, "text": "Founded On − This will be a DateTime field." }, { "code": null, "e": 26487, "s": 26419, "text": "Employer Description − This will be a Multiple Lines of Text field." }, { "code": null, "e": 26750, "s": 26487, "text": "Step 9 − Now add these new fields on the employer form. For this, click Forms from the left navigation under Employer entity. This will show you two forms with name Information. By default, CRM creates two forms – Main and Mobile-Express. Click on the Main form." }, { "code": null, "e": 26837, "s": 26750, "text": "Step 10 − You can see the newly added fields in the Field Explorer panel on the right." }, { "code": null, "e": 26894, "s": 26837, "text": "Step 11 − Drag and drop these fields in the General tab." }, { "code": null, "e": 26939, "s": 26894, "text": "Step 12 − Click Save and then click Publish." }, { "code": null, "e": 27216, "s": 26939, "text": "Step 13 − You can now create employer records with the updates fields. Navigate to CRM Home → Sales → Employers → New. The new form which will open this time will contain all the new fields that you added in this chapter. You can fill in some details and click Save and Close." }, { "code": null, "e": 27478, "s": 27216, "text": "In this chapter, we learnt working with CRM forms and how to customize them by placing various types of fields in them. We also learnt to add as many fields as we want on any form and arrange them using various tabs and sections as per the business requirement." }, { "code": null, "e": 27873, "s": 27478, "text": "Microsoft Dynamics CRM is a vast product which has evolved significantly over the years. The product comes with a lot of out-of-the-box functionalities that are inbuilt in the system. You do not need to write any code for utilizing these features. One of the important out-of-the-box features is the searching capability of CRM, in that it supports advanced querying and filtering capabilities." }, { "code": null, "e": 28054, "s": 27873, "text": "By default, the grid view of every entity in CRM supports a Quick Search functionality using a search bar on top right. Following is a screenshot of quick search on Contact entity." }, { "code": null, "e": 28150, "s": 28054, "text": "You can try entering a search string like 'Robert' and it will return all the matching records." }, { "code": null, "e": 28232, "s": 28150, "text": "You can prefix the search keyword with * (asterisk) to perform a wildcard search." }, { "code": null, "e": 28383, "s": 28232, "text": "Note − When using the web client version of Microsoft Dynamics CRM, Quick Search always searches All Active records irrespective of the view selected." }, { "code": null, "e": 28566, "s": 28383, "text": "You can customize the Quick Search (like customizing any other View) to modify the filter criteria, configure sorting, add view columns, add find columns and change other properties." }, { "code": null, "e": 28853, "s": 28566, "text": "Advanced Search allows you to search records of any entity in CRM. It is one of the strongest and one of the most useful feature that comes out-of-the-box with CRM. The Advanced Search icon appears on the top ribbon bar of Microsoft Dynamics CRM irrespective of which screen you are on." }, { "code": null, "e": 29094, "s": 28853, "text": "Click the Advanced Find icon to open the Advanced Find window. This window will allow you to select the entity for which you want to search records, apply filtering and grouping criteria, and save your Advanced Find views as personal views." }, { "code": null, "e": 29232, "s": 29094, "text": "Let’s take an example. Suppose, you want to search for all the Contacts with FirstName containing Robert and who are Divorced. For this −" }, { "code": null, "e": 29353, "s": 29232, "text": "Step 1 − Select Contacts from the Look for dropdown. This dropdown will contain all the entities present in your system." }, { "code": null, "e": 29699, "s": 29353, "text": "Step 2 − Enter the search criteria as shown in the following screenshot. You can add as many search query parameters as you want. You can even group such criteria using group parameters. For example, if you would like to search all contacts whose first name is either Robert or Mark, you can add two search criteria and group them using GroupOR." }, { "code": null, "e": 29781, "s": 29699, "text": "Step 3 − Click the Results button. It will show the matched records in a new tab." }, { "code": null, "e": 30104, "s": 29781, "text": "Step 4 − You can also edit the columns that you would like to see in the search results by clicking Edit Columns. For example, our current grid contains only two columns – Full Name and Business Phone. However, if you would like to have an additional column of Email ID added to this grid, you can do so using this option." }, { "code": null, "e": 30327, "s": 30104, "text": "At this stage, if you would like to save this search criteria, along with the filters and edited columns, you can do so by clicking the Save button. Once saved, you can use this saved view when you are on that entity page." }, { "code": null, "e": 30763, "s": 30327, "text": "For example, consider that as a customer executive you serve two types of customers: Normal and Premium. Hence, you can create an advanced filter with these respective categories and save them as Normal Contacts Assigned to Me and Premium Contacts Assigned to Me. You can then quickly access these views directly from the Contact entity page without carrying out a quick search or an advanced find search every time you use the system." }, { "code": null, "e": 30977, "s": 30763, "text": "Web Resources in CRM are the virtual web files that are stored in CRM database and used to implement web page functionalities in CRM. These files can be of HTML, JScript, Silverlight, or any other supported types." }, { "code": null, "e": 31241, "s": 30977, "text": "CRM being a product, comes with an extensive set of features and functionalities. However, most of the times, you would have to extend these existing functionalities to meet your custom requirements. Extending these functionalities generally happens in two ways −" }, { "code": null, "e": 31308, "s": 31241, "text": "Extending on Client Side − Using Web Resources and Form Scripting." }, { "code": null, "e": 31375, "s": 31308, "text": "Extending on Client Side − Using Web Resources and Form Scripting." }, { "code": null, "e": 31498, "s": 31375, "text": "Extending on Server Side − Plugins, Workflows and Web Services (we are going to learn this part in the upcoming chapters)." }, { "code": null, "e": 31621, "s": 31498, "text": "Extending on Server Side − Plugins, Workflows and Web Services (we are going to learn this part in the upcoming chapters)." }, { "code": null, "e": 31778, "s": 31621, "text": "As mentioned above, extending CRM on the client side is where Web Resources comes in picture. To understand this clearly, consider the following use cases −" }, { "code": null, "e": 32157, "s": 31778, "text": "You have a CRM form containing certain fields. CRM provides out-of-the-box features for basic validations such as mandatory fields, field lengths, etc. However what if you would like to have a more complex validation such as validating if the entered phone number is in the correct format, or validating if the entered address actually exists, or if the entered SSN is correct?" }, { "code": null, "e": 32536, "s": 32157, "text": "You have a CRM form containing certain fields. CRM provides out-of-the-box features for basic validations such as mandatory fields, field lengths, etc. However what if you would like to have a more complex validation such as validating if the entered phone number is in the correct format, or validating if the entered address actually exists, or if the entered SSN is correct?" }, { "code": null, "e": 32794, "s": 32536, "text": "CRM provides out-of-the-box UI customizations such as creating sections and tabs on a form, rearranging fields, etc. However, what if the client wants to build a custom page which shows all the information of the customer coming from their other ERP system?" }, { "code": null, "e": 33052, "s": 32794, "text": "CRM provides out-of-the-box UI customizations such as creating sections and tabs on a form, rearranging fields, etc. However, what if the client wants to build a custom page which shows all the information of the customer coming from their other ERP system?" }, { "code": null, "e": 33187, "s": 33052, "text": "CRM comes with a standard ribbon bar, which contains all the buttons and options. What if you want to add a ribbon button of your own?" }, { "code": null, "e": 33322, "s": 33187, "text": "CRM comes with a standard ribbon bar, which contains all the buttons and options. What if you want to add a ribbon button of your own?" }, { "code": null, "e": 33447, "s": 33322, "text": "Consider that you have an ERP system already in place. What if you would like to open some CRM screens from this ERP system?" }, { "code": null, "e": 33572, "s": 33447, "text": "Consider that you have an ERP system already in place. What if you would like to open some CRM screens from this ERP system?" }, { "code": null, "e": 33757, "s": 33572, "text": "You can always call any external web services in your server-side plugin code. However, what if you would like to call any external web services while you are still on the client-side?" }, { "code": null, "e": 33942, "s": 33757, "text": "You can always call any external web services in your server-side plugin code. However, what if you would like to call any external web services while you are still on the client-side?" }, { "code": null, "e": 34341, "s": 33942, "text": "The answer to all these “What ifs” is Web Resources. Every Web Resource can be accessed via its unique URL. You can either upload a Web Resource file or for codebased resources (such as HTML, Jscript, etc.) you can even edit them directly inside CRM. Since Web Resources are stored within CRM, they can easily be migrated from one environment to another together, along with any CRM customizations." }, { "code": null, "e": 34520, "s": 34341, "text": "Out of all these types of web resources, we will be studying the most important types of web resources - HTML Web Resources and JScript Web Resources, in the subsequent chapters." }, { "code": null, "e": 34624, "s": 34520, "text": "All the Web Resources stored in the database can be accessed in CRM. Following are the steps involved −" }, { "code": null, "e": 34689, "s": 34624, "text": "Step 1 − Go to Settings → Customizations → Customize the System." }, { "code": null, "e": 34843, "s": 34689, "text": "Step 2 − From the left navigation, select Web Resources. Currently, you will not be able to see any Web Resources since we have not created anything yet." }, { "code": null, "e": 34915, "s": 34843, "text": "We will be looking at how to create web resources in the next chapters." }, { "code": null, "e": 35043, "s": 34915, "text": "JScript Web Resources are probably the most important type of web resources that you will be using with Microsoft Dynamics CRM." }, { "code": null, "e": 35606, "s": 35043, "text": "Form Event Programming is used to handle client-side behaviors such as what happens when a user opens a form, changes some data, moves through tabs, etc. To achieve such client-side interactions you will be writing JavaScript code and adding it as a JScript Web Resource in CRM. However, the JavaScript code which you will write has to use Dynamic CRM’s Xrm.Page model and not the standard JavaScript DOM. Using Xrm.Page model is Microsoft’s way of coding which ensures that any code you write using this model will be compatible with any future versions of CRM." }, { "code": null, "e": 35717, "s": 35606, "text": "In addition to being used in Form Event Programming, JavaScript is used in other applications of CRM such as −" }, { "code": null, "e": 35766, "s": 35717, "text": "Open Forms, Views and Dialogs with a unique URL." }, { "code": null, "e": 35815, "s": 35766, "text": "Open Forms, Views and Dialogs with a unique URL." }, { "code": null, "e": 35877, "s": 35815, "text": "Using OData and SOAP endpoints to interact with web services." }, { "code": null, "e": 35939, "s": 35877, "text": "Using OData and SOAP endpoints to interact with web services." }, { "code": null, "e": 36024, "s": 35939, "text": "Referencing JavaScript code inside other Web Resources (such as HTML web resources)." }, { "code": null, "e": 36109, "s": 36024, "text": "Referencing JavaScript code inside other Web Resources (such as HTML web resources)." }, { "code": null, "e": 36286, "s": 36109, "text": "In such cases, you would write your JavaScript code (using Xrm.Page model) and add it as a JScript Web Resource in CRM, which can then be referenced anywhere with a unique URI." }, { "code": null, "e": 36382, "s": 36286, "text": "Finally, one of the other common use of JavaScript is to handle ribbon customizations such as −" }, { "code": null, "e": 36430, "s": 36382, "text": "Display/Hide ribbon buttons based on some logic" }, { "code": null, "e": 36480, "s": 36430, "text": "Enable/Disable ribbon buttons based on some logic" }, { "code": null, "e": 36539, "s": 36480, "text": "Handle what happens when you click a certain ribbon button" }, { "code": null, "e": 36897, "s": 36539, "text": "To handle such scenarios, you will write your JavaScript logic (using Xrm.Page model) and then add it as a JScript Web Resource. This Web Resource can then be referenced in the ribbon button’s XML and we can specify which method in which JScript file to call to check if a ribbon button should be displayed/hidden or enabled/disabled or handle click events." }, { "code": null, "e": 37071, "s": 36897, "text": "Following is the Xrm.Page object’s hierarchy showing the available namespaces, objects, and their collections. You will be using these properties while writing JScript code." }, { "code": null, "e": 37079, "s": 37071, "text": "Context" }, { "code": null, "e": 37253, "s": 37079, "text": "Provides methods to retrieve context-specific information such as organization details, logged-in user details, or parameters that were passed to the form in a query string." }, { "code": null, "e": 37258, "s": 37253, "text": "Data" }, { "code": null, "e": 37385, "s": 37258, "text": "Provides access to the entity data and methods to manage the data in the form as well as in the business process flow control." }, { "code": null, "e": 37388, "s": 37385, "text": "UI" }, { "code": null, "e": 37522, "s": 37388, "text": "Contains methods to retrieve information about the user interface, in addition to collections for several sub-components of the form." }, { "code": null, "e": 37529, "s": 37522, "text": "Entity" }, { "code": null, "e": 37550, "s": 37529, "text": "Provides method to −" }, { "code": null, "e": 37578, "s": 37550, "text": "Retrieve record information" }, { "code": null, "e": 37590, "s": 37578, "text": "Save method" }, { "code": null, "e": 37612, "s": 37590, "text": "Collection attributes" }, { "code": null, "e": 37620, "s": 37612, "text": "Process" }, { "code": null, "e": 37677, "s": 37620, "text": "Methods to retrieve properties of business process flow." }, { "code": null, "e": 37688, "s": 37677, "text": "Navigation" }, { "code": null, "e": 37748, "s": 37688, "text": "Provides access to navigation items using items collection." }, { "code": null, "e": 37761, "s": 37748, "text": "FormSelector" }, { "code": null, "e": 37879, "s": 37761, "text": "Uses Items collection to access available forms to the user. Also uses the navigation method to close and open forms." }, { "code": null, "e": 37886, "s": 37879, "text": "Stages" }, { "code": null, "e": 37982, "s": 37886, "text": "Each process has a collection of stages that can be accessed using getStages method of process." }, { "code": null, "e": 37988, "s": 37982, "text": "Steps" }, { "code": null, "e": 38079, "s": 37988, "text": "Each stage comprises of various steps that can be accessed using getSteps method of stage." }, { "code": null, "e": 38090, "s": 38079, "text": "Attributes" }, { "code": null, "e": 38150, "s": 38090, "text": "Provides access to entity attributes available on the form." }, { "code": null, "e": 38159, "s": 38150, "text": "Controls" }, { "code": null, "e": 38226, "s": 38159, "text": "ui.controls − Provides access to each control present on the form." }, { "code": null, "e": 38304, "s": 38226, "text": "attribute.controls − Provides access to all the controls within an attribute." }, { "code": null, "e": 38377, "s": 38304, "text": "section.controls − Provides access to all the controls within a section." }, { "code": null, "e": 38383, "s": 38377, "text": "Items" }, { "code": null, "e": 38438, "s": 38383, "text": "Provides access to all the navigation items on a form." }, { "code": null, "e": 38443, "s": 38438, "text": "Tabs" }, { "code": null, "e": 38486, "s": 38443, "text": "Provides access to all the tabs on a form." }, { "code": null, "e": 38495, "s": 38486, "text": "Sections" }, { "code": null, "e": 38542, "s": 38495, "text": "Provides access to all the sections on a form." }, { "code": null, "e": 38633, "s": 38542, "text": "The Form Programming using Xrm.Page model allows you to handle the following form events −" }, { "code": null, "e": 38640, "s": 38633, "text": "onLoad" }, { "code": null, "e": 38647, "s": 38640, "text": "onSave" }, { "code": null, "e": 38656, "s": 38647, "text": "onChange" }, { "code": null, "e": 38671, "s": 38656, "text": "TabStateChange" }, { "code": null, "e": 38692, "s": 38671, "text": "OnReadyStateComplete" }, { "code": null, "e": 38702, "s": 38692, "text": "PreSearch" }, { "code": null, "e": 38739, "s": 38702, "text": "Business Process Flow control events" }, { "code": null, "e": 39028, "s": 38739, "text": "In this example, we will put some validations on the Contact form based on the PreferredMethodofCommunication that the user selects. Hence, if the user selects his/her preferred method as Email, then the Email field should become mandatory and similarly for other fields of Phone and Fax." }, { "code": null, "e": 39109, "s": 39028, "text": "Step 1 − Create a JavaScript file named contacts.js and copy the following code." }, { "code": null, "e": 40464, "s": 39109, "text": "function validatePreferredMethodOfCommunication() { \n\n //get the value of Preffered Method of Communication code \n var prefferedContactMethodCode = \n Xrm.Page.getAttribute('preferredcontactmetho dcode').getValue(); \n \n //if Preferred Method = Any, make all fields as non-mandatory \n \n //else if Preferred Method = Phone, make Mobile Phone field mandatory \n //and all other fields as non-mandatory \n \n //else if Preferred Method = Fax, make Fax field mandatory \n //and all other fields as non-mandatory \n \n if(prefferedContactMethodCode == 1) { \n clearAllMandatoryFields(); \n } \n if(prefferedContactMethodCode == 2) { \n clearAllMandatoryFields(); \n Xrm.Page.getAttribute('emailaddress1').setRequiredLevel('required'); \n } else if(prefferedContactMethodCode == 3) { \n clearAllMandatoryFields(); \n Xrm.Page.getAttribute('mobilephone').setRequiredLevel('required'); \n } else if(prefferedContactMethodCode == 4) { \n clearAllMandatoryFields(); \n Xrm.Page.getAttribute('fax').setRequiredLevel('required'); \n } \n} \nfunction clearAllMandatoryFields() { \n \n //clear all mandatory fields \n Xrm.Page.getAttribute('emailaddress1').setRequiredLevel('none'); \n Xrm.Page.getAttribute('mobilephone').setRequiredLevel('none'); \n Xrm.Page.getAttribute('fax').setRequiredLevel('none'); \n}" }, { "code": null, "e": 40606, "s": 40464, "text": "Step 2 − Open the Contact entity form by navigating to Settings → Customizations → Customize the System → Contact entity → Forms → Main Form." }, { "code": null, "e": 40638, "s": 40606, "text": "Step 3 − Click Form Properties." }, { "code": null, "e": 40691, "s": 40638, "text": "Step 4 − From the Form Properties window, click Add." }, { "code": null, "e": 40800, "s": 40691, "text": "Step 5 − In the next Look Up Web Resource Record window, click New since we are creating a new web resource." }, { "code": null, "e": 40871, "s": 40800, "text": "Step 6 − In the New Web Resource window, enter the following details −" }, { "code": null, "e": 40894, "s": 40871, "text": "Name − new_contacts.js" }, { "code": null, "e": 40921, "s": 40894, "text": "Display Name − contacts.js" }, { "code": null, "e": 40936, "s": 40921, "text": "Type − JScript" }, { "code": null, "e": 41019, "s": 40936, "text": "Upload File − Upload the JavaScript file that you created from your local machine." }, { "code": null, "e": 41148, "s": 41019, "text": "Step 7 − Click Save followed by Publish. After this close the window and you will be back to Look Up Web Resource Record window." }, { "code": null, "e": 41320, "s": 41148, "text": "Step 8 − Here, you can now see the new_contacts.js web resource. Select it and click Add. You have now successfully added a new web resource and registered it on the form." }, { "code": null, "e": 41554, "s": 41320, "text": "Step 9 − Now we will add an event handler on the change of Preferred Method of Communication field. This event handler will call the JavaScript function that we just wrote. Select the following options from the Event Handler section." }, { "code": null, "e": 41598, "s": 41554, "text": "Control − Preferred Method of Communication" }, { "code": null, "e": 41615, "s": 41598, "text": "Event − OnChange" }, { "code": null, "e": 41681, "s": 41615, "text": "Then, click the Add button, as shown in the following screenshot." }, { "code": null, "e": 41803, "s": 41681, "text": "Step 10 − In the next window of Handler Properties, we will specify the method to be called when the change event occurs." }, { "code": null, "e": 41903, "s": 41803, "text": "Select Library as new_contacts.js and Function as validatePreferredMethodOfCommunication. Click OK." }, { "code": null, "e": 42012, "s": 41903, "text": "Step 11 − You will now be able to see the Form Library (Web Resource) and events registered on it. Click OK." }, { "code": null, "e": 42054, "s": 42012, "text": "Step 12 − Click Save followed by Publish." }, { "code": null, "e": 42348, "s": 42054, "text": "Step 13 − Now open any Contact form and set the Preferred Method of Communication as Phone. This will make the Mobile Phone field as mandatory. If you now try to save this contact without entering any mobile number, it will give you an error saying ‘You must provide a value for Mobile Phone’." }, { "code": null, "e": 42547, "s": 42348, "text": "In this chapter, we started by understanding the three important applications of JavaScript in CRM. Later, we explored the Xrm.Page model and used it to learn Form programming along with an example." }, { "code": null, "e": 42637, "s": 42547, "text": "In this chapter, we will learn about the various web resources in Microsoft Dynamics CRM." }, { "code": null, "e": 42811, "s": 42637, "text": "An HTML Web Resource in CRM can contain any HTML content that can be rendered on a browser. Consider the following scenarios where you would like to use HTML Web Resources −" }, { "code": null, "e": 42880, "s": 42811, "text": "You have a static HTML page that you want to show inside CRM screen." }, { "code": null, "e": 42949, "s": 42880, "text": "You have a static HTML page that you want to show inside CRM screen." }, { "code": null, "e": 43188, "s": 42949, "text": "You have a custom HTML page that expects some input parameters and gets rendered based on those input parameters. For example, consider you are fetching information from an external API or web service, and you want to display this in CRM." }, { "code": null, "e": 43427, "s": 43188, "text": "You have a custom HTML page that expects some input parameters and gets rendered based on those input parameters. For example, consider you are fetching information from an external API or web service, and you want to display this in CRM." }, { "code": null, "e": 43521, "s": 43427, "text": "You want to display some information with a different look and feel from the standard CRM UI." }, { "code": null, "e": 43615, "s": 43521, "text": "You want to display some information with a different look and feel from the standard CRM UI." }, { "code": null, "e": 43866, "s": 43615, "text": "You have a custom ASPX page (outside CRM application) which gets rendered based on the input parameters. Since CRM does not allow you to have ASPX web resources, you can create an HTML Web Resource and call the external ASPX page from this HTML page." }, { "code": null, "e": 44109, "s": 43866, "text": "We will create a very simple HTML Web Resource which will display a custom text ‘Welcome to TutorialsPoint’. Note that this is a very simple example of an HTML Web Resource. Practically, the HTML Web Resources would be more complex than this." }, { "code": null, "e": 44200, "s": 44109, "text": "Step 1 − Create an HTML file named sampleHTMLWebResource.html and copy the following code." }, { "code": null, "e": 44499, "s": 44200, "text": "<!DOCTYPE html> \n<htmllang = \"en\"xmlns = \"http://www.w3.org/1999/xhtml\"> \n <head> \n <metacharset = \"utf-8\"/> \n <title>Welcome to Tutorials Point</title> \n </head> \n \n <body> \n <h1>Welcome to Tutorials Point. This is an example of HTML Web Resource.</h1> \n </body> \n</html> " }, { "code": null, "e": 44682, "s": 44499, "text": "Step 2 − First, we will create a new Web Resource and then reference it on the Contact form. Open the DefaultSolution and navigate to WebResources tab from the left panel. Click New." }, { "code": null, "e": 44880, "s": 44682, "text": "Step 3 − It will open a New Web Resource window. Enter the details as shown in the following screenshot and browse the HTML file that we created in Step 1. Click Save and Publish. Close the window." }, { "code": null, "e": 44956, "s": 44880, "text": "Step 4 − You will see the new Web Resource added to the Web Resources grid." }, { "code": null, "e": 45176, "s": 44956, "text": "Step 5 − Now open the Contact form via Settings → Customizations → Customize the System → Contact → Main Form. Select the Contact Information section and switch to Insert tab from the top ribbon bar. Click Web Resource." }, { "code": null, "e": 45443, "s": 45176, "text": "Step 6 − It will open an Add Web Resource window. Click the Web Resource Lookup from this window, which will open the Web Resource Lookup Record window. Search the Web Resource that you just created (new_sampleHTMLWebResource), select it from the grid and click Add." }, { "code": null, "e": 45579, "s": 45443, "text": "Step 7 − Coming back to Add Web Resource, enter the Name and Label as shown in the following screenshot and click OK. Close the window." }, { "code": null, "e": 45645, "s": 45579, "text": "You will see the HTML Web Resource added below the Address field." }, { "code": null, "e": 45760, "s": 45645, "text": "Step 8 − To test this out, open any Contact record and you will see the HTML Web Resource content displayed there." }, { "code": null, "e": 45839, "s": 45760, "text": "There is no supported way of using the server-side code in HTML Web Resources." }, { "code": null, "e": 45918, "s": 45839, "text": "There is no supported way of using the server-side code in HTML Web Resources." }, { "code": null, "e": 46114, "s": 45918, "text": "HTML Web Resources can accept only limited number of parameters. To pass more than one value in the data parameter, you will have to encode the parameters include decoding logic on the other end." }, { "code": null, "e": 46310, "s": 46114, "text": "HTML Web Resources can accept only limited number of parameters. To pass more than one value in the data parameter, you will have to encode the parameters include decoding logic on the other end." }, { "code": null, "e": 46647, "s": 46310, "text": "Workflows in CRM allow you to automate simple and complex business processes within CRM. You can either create workflows using CRM out-of-the-box functionalities or write custom workflows with .NET code for implementing complex workflows. Workflow processes run in the background or in real-time and can optionally require a user input." }, { "code": null, "e": 46892, "s": 46647, "text": "Workflows can be triggered based on specific conditions or can even be started manually by the users. Internally, CRM workflows are implemented using Windows Workflow Foundation. In this chapter, we will be learning about configuring workflows." }, { "code": null, "e": 46961, "s": 46892, "text": "Configuring a workflow has the following major parts (in sequence) −" }, { "code": null, "e": 47013, "s": 46961, "text": "Configure the entity on which the workflow will run" }, { "code": null, "e": 47085, "s": 47013, "text": "Configure whether the workflow will run synchronously or asynchronously" }, { "code": null, "e": 47146, "s": 47085, "text": "Configure the message (event) on which the workflow will run" }, { "code": null, "e": 47197, "s": 47146, "text": "Configure the scope in which the workflow will run" }, { "code": null, "e": 47254, "s": 47197, "text": "Configure the stages and steps (actions) of the workflow" }, { "code": null, "e": 47470, "s": 47254, "text": "When you create a workflow, you will see the option of Run this workflow in the background (recommended) which determines whether the workflow will run in real-time (synchronously) or in background (asynchronously)." }, { "code": null, "e": 47704, "s": 47470, "text": "Generally, the recommended approach is to run the workflows in the background since they use system resources as and when available. However, you can always switch back from a real-time workflow to background workflow and vice versa." }, { "code": null, "e": 47764, "s": 47704, "text": "Workflows can be registered on specific events as follows −" }, { "code": null, "e": 47789, "s": 47764, "text": "When a record is created" }, { "code": null, "e": 47818, "s": 47789, "text": "When a record status changes" }, { "code": null, "e": 47844, "s": 47818, "text": "When a record is assigned" }, { "code": null, "e": 47878, "s": 47844, "text": "When a record field value changes" }, { "code": null, "e": 47903, "s": 47878, "text": "When a record is deleted" }, { "code": null, "e": 48018, "s": 47903, "text": "Workflows allow you to set the scope in which the workflow will run. Following are the supported workflow scopes −" }, { "code": null, "e": 48204, "s": 48018, "text": "Workflows in CRM are a combination of series of steps which the workflow will follow. You can even divide these steps in logical stages. Following steps are supported by CRM workflows −" }, { "code": null, "e": 48395, "s": 48204, "text": "In this example, we will create a simple workflow that runs in the background to assign any newly created Contact record to a specific user and then send out a welcome email to the customer." }, { "code": null, "e": 48432, "s": 48395, "text": "Step 1 − Go to Settings → Processes." }, { "code": null, "e": 48452, "s": 48432, "text": "Step 2 − Click New." }, { "code": null, "e": 48520, "s": 48452, "text": "Step 3 − In the CreateProcess window, enter the following details −" }, { "code": null, "e": 48594, "s": 48520, "text": "Process Name − New Customer Workflow (This can be any name that you want)" }, { "code": null, "e": 48614, "s": 48594, "text": "Category − Workflow" }, { "code": null, "e": 48723, "s": 48614, "text": "Entity − Contact (This will be the entity on which you are creating the workflow. In our case it is Contact)" }, { "code": null, "e": 48867, "s": 48723, "text": "Run this workflow in the background (recommended) − Check this option as we are creating a background asynchronous workflow. Finally, click OK." }, { "code": null, "e": 48932, "s": 48867, "text": "Step 4 − In the New Process Window enter the following details −" }, { "code": null, "e": 48954, "s": 48932, "text": "Activate As − Process" }, { "code": null, "e": 48967, "s": 48954, "text": "Scope − User" }, { "code": null, "e": 48998, "s": 48967, "text": "Start when − Record is created" }, { "code": null, "e": 49030, "s": 48998, "text": "Click Add Step → Assign Record." }, { "code": null, "e": 49361, "s": 49030, "text": "Step 5 − You will see a new step added to the workflow. In this step, we will specify the user to whom all the created contacts should be assigned. Enter the name of step as Assign Record to Team. The Assign option will be defaulted as the entity on which we are creating the workflow (Contact in our case). Click the Lookup icon." }, { "code": null, "e": 49513, "s": 49361, "text": "Step 6 − In the Lookup window, select any user that you want. You can even select a specific team to whom you want to assign the records to. Click Add." }, { "code": null, "e": 49637, "s": 49513, "text": "Step 7 − Add another step by clicking Add Step → Send Email. In this step, we will configure sending email to the customer." }, { "code": null, "e": 49736, "s": 49637, "text": "Step 8 − A new step will be added. Enter its name as Send email to Customer. Click Set Properties." }, { "code": null, "e": 49818, "s": 49736, "text": "Step 9 − In the next window to configure email, perform the following operations−" }, { "code": null, "e": 49907, "s": 49818, "text": "From − Click From field. On the right panel, select OwningUser and User. Click Add → OK." }, { "code": null, "e": 49992, "s": 49907, "text": "To − Click To field. On the right panel, select Contact and Contact. Click Add → OK." }, { "code": null, "e": 50028, "s": 49992, "text": "Subject − Enter a relevant Subject." }, { "code": null, "e": 50066, "s": 50028, "text": "Body − Enter a relevant Body content." }, { "code": null, "e": 50106, "s": 50066, "text": "Step 10 − Click Save and then Activate." }, { "code": null, "e": 50189, "s": 50106, "text": "Step 11 − In the Process Activate Confirmation popup that follows, click Activate." }, { "code": null, "e": 50542, "s": 50189, "text": "Step 12 − Go to Contacts tab and create a new contact. As soon as you create a new contact by saving the record, you will see the Owner field set to the user, which you had configured in the workflow. Also, if you click the Activities tab, you will see an email activity being created for this contact. This confirms that the workflow ran successfully." }, { "code": null, "e": 50850, "s": 50542, "text": "Workflows and plugins can both be used to extend and automate CRM functionalities. In many scenarios, both the approaches can be interchangeably used in place of each other. For example, if you have a simple requirement of sending an email to your customers, you can either do it via a plugin or a workflow." }, { "code": null, "e": 50958, "s": 50850, "text": "So, how do you choose between creating a workflow vs plugin? The following list tries to explain the same −" }, { "code": null, "e": 51151, "s": 50958, "text": "Although plugins and workflows both can be used to run synchronous as well as asynchronous logic, plugins are generally preferred for synchronous logic, while workflows for asynchronous logic." }, { "code": null, "e": 51344, "s": 51151, "text": "Although plugins and workflows both can be used to run synchronous as well as asynchronous logic, plugins are generally preferred for synchronous logic, while workflows for asynchronous logic." }, { "code": null, "e": 51561, "s": 51344, "text": "Generally, to implement complex business logic, plugins are preferred over workflows. Workflows are preferred when you want to achieve relatively easier functionalities (such as sending emails, assigning users, etc.)" }, { "code": null, "e": 51778, "s": 51561, "text": "Generally, to implement complex business logic, plugins are preferred over workflows. Workflows are preferred when you want to achieve relatively easier functionalities (such as sending emails, assigning users, etc.)" }, { "code": null, "e": 51917, "s": 51778, "text": "Plugins need to be developed with coding, while workflows can be configured directly by business users without any knowledge of workflows." }, { "code": null, "e": 52056, "s": 51917, "text": "Plugins need to be developed with coding, while workflows can be configured directly by business users without any knowledge of workflows." }, { "code": null, "e": 52203, "s": 52056, "text": "Workflows can run on-demand. Hence, if there are requirements where the user wants to run some logic manually, workflows would be a better choice." }, { "code": null, "e": 52350, "s": 52203, "text": "Workflows can run on-demand. Hence, if there are requirements where the user wants to run some logic manually, workflows would be a better choice." }, { "code": null, "e": 52528, "s": 52350, "text": "From performance impact, synchronous plugins provide a better performance (and throughput) as compared to real-time workflows in scenarios where the request frequency is higher." }, { "code": null, "e": 52706, "s": 52528, "text": "From performance impact, synchronous plugins provide a better performance (and throughput) as compared to real-time workflows in scenarios where the request frequency is higher." }, { "code": null, "e": 53005, "s": 52706, "text": "This chapter introduced us to one of the very important functionalities of CRM – Workflows. We first understood the sync/async workflows, messages, scope, steps and finally looked at a live example of creating and running a workflow. Finally, we saw the differences between a workflow and a plugin." }, { "code": null, "e": 53331, "s": 53005, "text": "A plug-in is a custom business logic that integrates with Microsoft Dynamics CRM to modify or extend the standard behavior of the platform. Plug-ins act as event handlers and are registered to execute on a particular event in CRM. Plugins are written in either C# or VB and can run either in synchronous or asynchronous mode." }, { "code": null, "e": 53383, "s": 53331, "text": "Some scenarios where you would write a plugin are −" }, { "code": null, "e": 53541, "s": 53383, "text": "You want to execute some business logic such as updating certain fields of a record or updating related records, etc. when you create or update a CRM record." }, { "code": null, "e": 53699, "s": 53541, "text": "You want to execute some business logic such as updating certain fields of a record or updating related records, etc. when you create or update a CRM record." }, { "code": null, "e": 53795, "s": 53699, "text": "You want to call an external web service on certain events such as saving or updating a record." }, { "code": null, "e": 53891, "s": 53795, "text": "You want to call an external web service on certain events such as saving or updating a record." }, { "code": null, "e": 53969, "s": 53891, "text": "You want to dynamically calculate the field values when any record is opened." }, { "code": null, "e": 54047, "s": 53969, "text": "You want to dynamically calculate the field values when any record is opened." }, { "code": null, "e": 54146, "s": 54047, "text": "You want to automate processes such as sending e-mails to your customers on certain events in CRM." }, { "code": null, "e": 54245, "s": 54146, "text": "You want to automate processes such as sending e-mails to your customers on certain events in CRM." }, { "code": null, "e": 54576, "s": 54245, "text": "The Event Processing Framework in CRM processes the synchronous and asynchronous plugin requests by passing it to the event execution pipeline. Whenever an event triggers a plugin logic, a message is sent to the CRM Organization Web Service where it can be read or modified by other plugins or any core operations of the platform." }, { "code": null, "e": 54988, "s": 54576, "text": "The entire plugin pipeline is divided in multiple stages on which you can register your custom business logic. The pipeline stage specified indicates at which stage of the plugin execution cycle, your plugin code runs. Out of all the specified pipeline stages in the following table, you can register your custom plugins only on Pre- and Post-events. You can’t register plugins on Platform Core Main Operations." }, { "code": null, "e": 55118, "s": 54988, "text": "Whenever the CRM application invokes an event (like saving or updating a record), the following sequence of actions takes place −" }, { "code": null, "e": 55269, "s": 55118, "text": "The event triggers a Web service call and the execution is passed through the event pipeline stages (pre-event, platform core operations, post-event)." }, { "code": null, "e": 55420, "s": 55269, "text": "The event triggers a Web service call and the execution is passed through the event pipeline stages (pre-event, platform core operations, post-event)." }, { "code": null, "e": 55580, "s": 55420, "text": "The information is internally packaged as an OrganizationRequest message and finally sent to the internal CRM Web service methods and platform core operations." }, { "code": null, "e": 55740, "s": 55580, "text": "The information is internally packaged as an OrganizationRequest message and finally sent to the internal CRM Web service methods and platform core operations." }, { "code": null, "e": 56123, "s": 55740, "text": "The OrganizationRequest message is first received by pre-event plugins, which can modify the information before passing it to platform core operations. After the platform core operations, the message is packaged as OrganizationResponse and passed to the post-operation plugins. The postoperations plugins can optionally modify this information before passing it to the async plugin." }, { "code": null, "e": 56506, "s": 56123, "text": "The OrganizationRequest message is first received by pre-event plugins, which can modify the information before passing it to platform core operations. After the platform core operations, the message is packaged as OrganizationResponse and passed to the post-operation plugins. The postoperations plugins can optionally modify this information before passing it to the async plugin." }, { "code": null, "e": 56654, "s": 56506, "text": "The plugins receive this information in the form of context object that is passed to the Execute method after which the further processing happens." }, { "code": null, "e": 56802, "s": 56654, "text": "The plugins receive this information in the form of context object that is passed to the Execute method after which the further processing happens." }, { "code": null, "e": 56920, "s": 56802, "text": "After all the plugin processing completes, the execution is passed back to the application which triggered the event." }, { "code": null, "e": 57038, "s": 56920, "text": "After all the plugin processing completes, the execution is passed back to the application which triggered the event." }, { "code": null, "e": 57270, "s": 57038, "text": "Messages are the events on which the plugin (or business logic) is registered. For example, you can register a plugin on Create Message of Contact entity. This would fire the business logic whenever a new Contact record is created." }, { "code": null, "e": 57393, "s": 57270, "text": "For custom entities, following are the supported messages based on whether the entity is user-owned or organization-owned." }, { "code": null, "e": 57716, "s": 57393, "text": "For default out-of-the-box entities, there are more than 100 supported messages. Some of these messages are applicable for all the entities while some of them are specific to certain entities. You can find the complete list of supported message in an excel file inside the SDK: SDK\\Message-entity support for plug-ins.xlsx" }, { "code": null, "e": 57976, "s": 57716, "text": "In this section, we will learn the basics of writing a plugin. We will be creating a sample plugin that creates a Task activity to follow-up with the customer whenever a new customer is added to the system, i.e. whenever a new Contactrecord is created in CRM." }, { "code": null, "e": 58315, "s": 57976, "text": "First of all, you would need to include the references to Microsoft.Xrm.Sdk namespace. The CRM SDK contains all the required SDK assemblies. Assuming that you have already downloaded and installed the SDK in Chapter 2, open Visual Studio. Create a new project of type Class Library. You can name the project as SamplePlugins and click OK." }, { "code": null, "e": 58416, "s": 58315, "text": "Add the reference of Microsoft.Xrm.Sdk assembly to your project. The assembly is present in SDK/Bin." }, { "code": null, "e": 58558, "s": 58416, "text": "Now, create a class named PostCreateContact.cs and extend the class from IPlugin. Till now, your code will look something like the following." }, { "code": null, "e": 58732, "s": 58558, "text": "You will also need to add reference to System.Runtime.Serialization. Once you have added the required references, copy the following code inside the PostCreateContact class." }, { "code": null, "e": 61485, "s": 58732, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing Microsoft.Xrm.Sdk;\n\nnamespace SamplePlugins {\n public class PostCreateContact:IPlugin {\n /// A plug-in that creates a follow-up task activity when a new account is created.\n /// Register this plug-in on the Create message, account entity,\n /// and asynchronous mode.\n\n public void Execute(IServiceProviderserviceProvider) {\n // Obtain the execution context from the service provider.\n IPluginExecutionContext context =(IPluginExecutionContext)\n serviceProvider.GetService(typeof(IPluginExecutionContext));\n\n // The InputParameters collection contains all the data\n passed in the message request.\n\n if(context.InputParameters.Contains(\"Target\")&&\n context.InputParameters[\"Target\"]isEntity) {\n \n // Obtain the target entity from the input parameters.\n Entity entity = (Entity)context.InputParameters[\"Target\"];\n try {\n \n // Create a task activity to follow up with the account customer in 7 days\n Entity followup = new Entity(\"task\");\n followup[\"subject\"] = \"Send e-mail to the new customer.\";\n followup[\"description\"] =\n \"Follow up with the customer. Check if there are any new issues\n that need resolution.\";\n \n followup[\"scheduledstart\"] = DateTime.Now;\n followup[\"scheduledend\"] = DateTime.Now.AddDays(2);\n followup[\"category\"] = context.PrimaryEntityName;\n\n // Refer to the contact in the task activity.\n if(context.OutputParameters.Contains(\"id\")) {\n Guid regardingobjectid = new Guid(context.OutputParameter\n s[\"id\"].ToString());\n string regardingobjectidType = \"contact\";\n followup[\"regardingobjectid\"] = \n new EntityReference(rega rdingobjectidType,regardingobjectid);\n }\n \n // Obtain the organization service reference.\n IOrganizationServiceFactory serviceFactory =\n (IOrganizationSer viceFactory)serviceProvider.GetService\n (typeof(IOrganizationServiceFactory));\n IOrganizationService service = \n serviceFactory.CreateOrganizationService(context.UserId);\n\n // Create the followup activity\n service.Create(followup);\n } catch(Exception ex) {\n throw new InvalidPluginExecutionException(ex.Message);\n }\n }\n }\n }\n}" }, { "code": null, "e": 61550, "s": 61485, "text": "Following is a step-by-step explanation of what this code does −" }, { "code": null, "e": 61746, "s": 61550, "text": "Step 1 − Implements the Execute method by taking IServiceProvider object as its parameter. The service provider contains references to many useful objects that you are going to use within plugin." }, { "code": null, "e": 61847, "s": 61746, "text": "Step 2 − Obtains the IPluginExecutionContext object using the GetService method of IServiceProvider." }, { "code": null, "e": 62044, "s": 61847, "text": "Step 3 − Gets the target entity’s object from the context object’s InputParameters collection. This Entity class object refers to the Contact entity record on which our plugin would be registered." }, { "code": null, "e": 62435, "s": 62044, "text": "Step 4 − It then creates an object of Task entity and sets proper subject, description, dates, category and regardingobjectid. The regardingobjectid indicates for which contact record this activity record is being created. You can see that the code gets the id of the parent Contact record using context.OutputParameters and associates it with the Task entity record which you have created." }, { "code": null, "e": 62525, "s": 62435, "text": "Step 5 − Creates object of IOrganizationServiceFactory using the IServiceProvider object." }, { "code": null, "e": 62619, "s": 62525, "text": "Step 6 − Creates object of IOrganizationService using the IOrganizationServiceFactory object." }, { "code": null, "e": 62744, "s": 62619, "text": "Step 7 − Finally, using the Create method of this service object. It creates the follow-up activity which gets saved in CRM." }, { "code": null, "e": 62963, "s": 62744, "text": "This section is applicable only if you are registering your plugin assembly for the first time. You need to sign in the assembly with a key to be able to deploy the plugin. Rightclick the solution and click Properties." }, { "code": null, "e": 63110, "s": 62963, "text": "Select the Signing tab from the left options and check the ‘Sign the assembly’ option. Then, select New from Choose a strong name key file option." }, { "code": null, "e": 63271, "s": 63110, "text": "Enter the Key file name as sampleplugins (This can be any other name you want). Uncheck the Protect my key file with a password option and click OK. Click Save." }, { "code": null, "e": 63434, "s": 63271, "text": "Finally, build the solution. Right Click → Build. Building the solution will generate assembly DLL, which we will use in the next chapter to register this plugin." }, { "code": null, "e": 63765, "s": 63434, "text": "More often than not, your plugin logic will need to handle run-time exceptions. For synchronous plugins, you can return an InvalidPluginExecutionException exception, which will show an error dialog box to the user. The error dialog will contain the custom error message that you pass to the Message object of the exception object." }, { "code": null, "e": 63872, "s": 63765, "text": "If you look at our code, we are throwing the InvalidPluginExecutionException exception in our catch block." }, { "code": null, "e": 63929, "s": 63872, "text": "throw new InvalidPluginExecutionException(ex.Message); \n" }, { "code": null, "e": 64224, "s": 63929, "text": "Plugins are definitely crucial to any custom CRM implementation. In this chapter, we focused on understanding the event framework model, pipeline stages, messages, and writing a sample plugin. In the next chapter, we will register this plugin in CRM and see it working from end-to-end scenario." }, { "code": null, "e": 64531, "s": 64224, "text": "In the last chapter, we created a sample plugin to create a follow-up Task activity when a Contact record is created. In this chapter, we will see how to register this plugin in CRM using Plugin Registration Tool. You can find the tool at this location: SDK/Tools/PluginRegistration/PluginRegistration.exe." }, { "code": null, "e": 64613, "s": 64531, "text": "For convenience, the plugin registration process is divided into three sections −" }, { "code": null, "e": 64638, "s": 64613, "text": "Connecting to the Server" }, { "code": null, "e": 64663, "s": 64638, "text": "Registering the Assembly" }, { "code": null, "e": 64686, "s": 64663, "text": "Registering the Plugin" }, { "code": null, "e": 64803, "s": 64686, "text": "Step 1 − Run the PluginRegistration.exe from the location specified earlier. Click the Create New Connection button." }, { "code": null, "e": 64937, "s": 64803, "text": "Step 2 − In the Login window, choose Office 365 since we are using the online version of CRM. Enter your credentials and click Login." }, { "code": null, "e": 65005, "s": 64937, "text": "Step 3 − The tool will open and look like the following screenshot." }, { "code": null, "e": 65054, "s": 65005, "text": "Step 1 − Go to Register → Register New Assembly." }, { "code": null, "e": 65200, "s": 65054, "text": "Step 2 − This will open the Register New Assembly window. Click the Navigate icon and locate the Plugin DLL that you created in the last chapter." }, { "code": null, "e": 65490, "s": 65200, "text": "Step 3 − After navigating the DLL, click Load Assembly. This will populate the SamplePlugins assembly and all its plugin classes. You can see the PostCreateContact plugin class highlighted below. If your plugin assembly had 3 plugin classes, it would have shown three plugins listed there." }, { "code": null, "e": 65662, "s": 65490, "text": "Step 4 − Select Isolation Mode as Sandbox, Location as Database and click Register Selected Plugins. It will show you a success message, if the registration is successful." }, { "code": null, "e": 65756, "s": 65662, "text": "Now we will be registering the specific steps on which the individual plugins will be called." }, { "code": null, "e": 65802, "s": 65756, "text": "Step 1 − Select the PostCreateContact plugin." }, { "code": null, "e": 65847, "s": 65802, "text": "Step 2 − Click Register → Register New Step." }, { "code": null, "e": 65982, "s": 65847, "text": "Step 3 − We will be registering this plugin on the creation of the Contact entity, on postoperation stage and in the synchronous mode." }, { "code": null, "e": 65999, "s": 65982, "text": "Message − Create" }, { "code": null, "e": 66024, "s": 65999, "text": "Primary Entity − Contact" }, { "code": null, "e": 66075, "s": 66024, "text": "Event Pipeline Stage of Execution − Post-operation" }, { "code": null, "e": 66104, "s": 66075, "text": "Execution Mode − Synchronous" }, { "code": null, "e": 66173, "s": 66104, "text": "Keep the rest of the options by default and click Register New Step." }, { "code": null, "e": 66217, "s": 66173, "text": "You can see a new step added to the plugin." }, { "code": null, "e": 66347, "s": 66217, "text": "Now we will go to CRM and test if our plugin is working correctly. Note that these test steps are specific to our example plugin." }, { "code": null, "e": 66485, "s": 66347, "text": "Go to Contacts tab and create a new record. Once you save the record, you can see a new activity created and associated with this record." }, { "code": null, "e": 66560, "s": 66485, "text": "You can click the activity to see the details that we had set in the code." }, { "code": null, "e": 66690, "s": 66560, "text": "This confirms that our plugin ran successfully. Similarly, you can extend your plugins to achieve highly complex functionalities." }, { "code": null, "e": 66921, "s": 66690, "text": "Microsoft Dynamics CRM provides two important web services that are used to access CRM from an external application and invoke web methods to perform common business data operations such as create, delete, update, and find in CRM." }, { "code": null, "e": 66956, "s": 66921, "text": "Consider the following scenarios −" }, { "code": null, "e": 67147, "s": 66956, "text": "You have an external .NET application, which needs to talk to CRM. For example, you may want to insert a Contact record in CRM when a new customer is registered in your external application." }, { "code": null, "e": 67338, "s": 67147, "text": "You have an external .NET application, which needs to talk to CRM. For example, you may want to insert a Contact record in CRM when a new customer is registered in your external application." }, { "code": null, "e": 67443, "s": 67338, "text": "Or maybe, you want to search records in CRM and display the search results in your external application." }, { "code": null, "e": 67548, "s": 67443, "text": "Or maybe, you want to search records in CRM and display the search results in your external application." }, { "code": null, "e": 67711, "s": 67548, "text": "In such scenarios, you can use the web services exposed by CRM to consume them in your application and perform create, delete, update, and find operations in CRM." }, { "code": null, "e": 67846, "s": 67711, "text": "This web service returns a list of organizations that the specified user belongs to and the URL endpoint for each of the organization." }, { "code": null, "e": 68122, "s": 67846, "text": "This web service is the primary web service used for accessing data and metadata in CRM. The IOrganizationService uses two important assemblies –Microsoft.Xrm.Sdk.dll and Microsoft.Crm.Sdk.Proxy.dll. These assemblies can be found in the CRM SDK package inside the Bin folder." }, { "code": null, "e": 68144, "s": 68122, "text": "Microsoft.Xrm.Sdk.dll" }, { "code": null, "e": 68331, "s": 68144, "text": "This assembly defines the core xRM methods and types, including proxy classes to make the connection to Microsoft Dynamics CRM simpler, authentication methods, and the service contracts." }, { "code": null, "e": 68359, "s": 68331, "text": "Microsoft.Crm.Sdk.Proxy.dll" }, { "code": null, "e": 68567, "s": 68359, "text": "This assembly defines the requests and responses for non-core messages as well as enumerations required for working with the organization data. Following are the namespaces supported by these two assemblies." }, { "code": null, "e": 68765, "s": 68567, "text": "Each of these assemblies support certain messages, which will be used to work with the data stored in any entity. A complete list of messages supported by them can be found in the following links −" }, { "code": null, "e": 68845, "s": 68765, "text": "Supported xRM Messages − https://msdn.microsoft.com/en-us/library/gg334698.aspx" }, { "code": null, "e": 68925, "s": 68845, "text": "Supported CRM Messages − https://msdn.microsoft.com/en-us/library/gg309482.aspx" }, { "code": null, "e": 69094, "s": 68925, "text": "The IOrganizationService provides eight methods that allows you to perform all the common operations on the system and custom entities as well as organization metadata." }, { "code": null, "e": 69122, "s": 69094, "text": "IOrganizationService.Create" }, { "code": null, "e": 69140, "s": 69122, "text": "Creates a record." }, { "code": null, "e": 69168, "s": 69140, "text": "IOrganizationService.Update" }, { "code": null, "e": 69196, "s": 69168, "text": "Updates an existing record." }, { "code": null, "e": 69227, "s": 69196, "text": "IOrganizationService. Retrieve" }, { "code": null, "e": 69247, "s": 69227, "text": "Retrieves a record." }, { "code": null, "e": 69286, "s": 69247, "text": "IOrganizationService. RetrieveMultiple" }, { "code": null, "e": 69321, "s": 69286, "text": "Retrieves a collection of records." }, { "code": null, "e": 69350, "s": 69321, "text": "IOrganizationService. Delete" }, { "code": null, "e": 69368, "s": 69350, "text": "Deletes a record." }, { "code": null, "e": 69400, "s": 69368, "text": "IOrganizationService. Associate" }, { "code": null, "e": 69432, "s": 69400, "text": "Creates a link between records." }, { "code": null, "e": 69466, "s": 69432, "text": "IOrganizationService.Disassociate" }, { "code": null, "e": 69498, "s": 69466, "text": "Deletes a link between records." }, { "code": null, "e": 69527, "s": 69498, "text": "IOrganizationService.Execute" }, { "code": null, "e": 69646, "s": 69527, "text": "Used for common record processing as well as specialized processing such as case resolution, duplicate detection, etc." }, { "code": null, "e": 69882, "s": 69646, "text": "To understand how the web services work in CRM, we will look at an example provided by CRM SDK. In this example, we will create a new Account record, update it, and then finally delete it using the CRM IOrganizationService web service." }, { "code": null, "e": 70046, "s": 69882, "text": "Step 1 − Open the folder where you had extracted CRM SDK. Now open the QuickStartCS.sln solution by browsing to the following location:SDK\\SampleCode\\CS\\QuickStart" }, { "code": null, "e": 70234, "s": 70046, "text": "Step 2 − We will be exploring the QuickStart with Simplified Connection project. Open app.config in this project. By default, the connectionStrings section in this file will be commented." }, { "code": null, "e": 70326, "s": 70234, "text": "From this, uncomment the first connection string key and edit the following three details −" }, { "code": null, "e": 70464, "s": 70326, "text": "Url − Specify the URL of your CRM instance. In our case, since we are using the online version of CRM, you will have to mention that URL." }, { "code": null, "e": 70502, "s": 70464, "text": "Username − Your CRM Online user name." }, { "code": null, "e": 70539, "s": 70502, "text": "Password − Your CRM Online password." }, { "code": null, "e": 70627, "s": 70539, "text": "Step 3 − Open the SimplifiedConnection.cs file in this project and Runmethod inside it." }, { "code": null, "e": 74099, "s": 70627, "text": "public void Run(StringconnectionString, boolpromptforDelete) {\n try {\n \n // Establish a connection to the organization web service using CrmConnection.\n Microsoft.Xrm.Client.CrmConnection connection =\n CrmConnection.Parse(connectionString);\n \n // Obtain an organization service proxy.\n // The using statement assures that the service proxy will be properly disposed.\n using(_orgService = new OrganizationService(connection)) {\n\n //Create any entity records this sample requires.\n CreateRequiredRecords();\n \n // Obtain information about the logged on user from the web service.\n Guid userid = ((WhoAmIResponse)_orgService.Execute(new WhoAmIRequest())).UserId;\n SystemUser systemUser = (SystemUser)_orgService.Retrieve(\"systemuser\",userid,\n new ColumnSet(newstring[]{\"firstname\",\"lastname\"}));\n \n Console.WriteLine(\"Logged on user is {0} {1}.\",\n systemUser.FirstName,systemUser.LastName);\n\n // Retrieve the version of Microsoft Dynamics CRM.\n RetrieveVersionRequest versionRequest = new RetrieveVersionRequest();\n RetrieveVersionResponse versionResponse =\n (RetrieveVersionResponse)_orgService.Execute(versionRequest);\n Console.WriteLine(\"Microsoft Dynamics CRM version {0}.\",\n versionResponse.Version);\n \n // Instantiate an account object. Note the use of option set\n enumerations defined in OptionSets.cs.\n \n // Refer to the Entity Metadata topic in the SDK documentation to\n determine which attributes must\n \n // be set for each entity.\n Account account = new Account{Name = \"Fourth Coffee\"};\n account.AccountCategoryCode = new OptionSetValue(\n (int)AccountAccountCateg oryCode.PreferredCustomer);\n account.CustomerTypeCode = new OptionSetValue(\n (int)AccountCustomerTypeCod e.Investor);\n \n // Create an account record named Fourth Coffee.\n _accountId = _orgService.Create(account);\n Console.Write(\"{0} {1} created, \",account.LogicalName,account.Name);\n \n // Retrieve the several attributes from the new account.\n ColumnSet cols = new ColumnSet(\n new String[]{\"name\",\"address1_postalcode\",\"lastusedincampaign\"});\n Account retrievedAccount =\n (Account)_orgService.Retrieve(\"account\", _accountId, cols);\n Console.Write(\"retrieved, \");\n\n // Update the postal code attribute.\n retrievedAccount.Address1_PostalCode = \"98052\";\n\n // The address 2 postal code was set accidentally, so set it to null.\n retrievedAccount.Address2_PostalCode = null;\n\n // Shows use of a Money value.\n retrievedAccount.Revenue = new Money(5000000);\n\n // Shows use of a Boolean value.\n retrievedAccount.CreditOnHold = false;\n \n // Update the account record.\n _orgService.Update(retrievedAccount);\n Console.WriteLine(\"and updated.\");\n \n // Delete any entity records this sample created.\n DeleteRequiredRecords(promptforDelete);\n } \n } \n // Catch any service fault exceptions that Microsoft Dynamics CRM throws.\n catch(FaultException<microsoft.xrm.sdk.organizationservicefault>) {\n\n // You can handle an exception here or pass it back to the calling method.\n throw;\n }\n}" }, { "code": null, "e": 74537, "s": 74099, "text": "Step 4 − This method basically demonstrates all the CRUD operations using CRM web services. The code first creates an organization instance, then creates an Account record, updates the created record and then finally deletes it. Let us look at the important components of this code. To see on-the-go changes in CRM when this code runs, you can debug this code step-by-step (as we discuss below) and simultaneously see the changes in CRM." }, { "code": null, "e": 74655, "s": 74537, "text": "Step 4.1 − Establishes the connection to the organization using the connection string that we had modified in Step 2." }, { "code": null, "e": 74743, "s": 74655, "text": "Microsoft.Xrm.Client.CrmConnection connection = CrmConnection.Parse(connectionString);\n" }, { "code": null, "e": 74812, "s": 74743, "text": "Step 4.2 − Obtains a proxy instance of CRM organization web service." }, { "code": null, "e": 74864, "s": 74812, "text": "_orgService = new OrganizationService(connection) \n" }, { "code": null, "e": 74972, "s": 74864, "text": "Step 4.3 − Creates a new Account entity object and sets its Name, AccountCategoryCode and CustomerTypeCode." }, { "code": null, "e": 75225, "s": 74972, "text": "Account account = new Account{Name = \"Fifth Coffee\"}; \naccount.AccountCategoryCode = new OptionSetValue(\n (int)AccountAccountCategoryCode.P referredCustomer); \naccount.CustomerTypeCode = new OptionSetValue(\n (int)AccountCustomerTypeCode.Investor); " }, { "code": null, "e": 75308, "s": 75225, "text": "Step 4.4 − Creates the new record using the Create method of organization service." }, { "code": null, "e": 75352, "s": 75308, "text": "_accountId = _orgService.Create(account); \n" }, { "code": null, "e": 75421, "s": 75352, "text": "If you navigate to CRM, you will see a newly created account record." }, { "code": null, "e": 75545, "s": 75421, "text": "Step 4.5 − Once the account gets created, the service retrieves back the record from CRM using Retrieve web service method." }, { "code": null, "e": 75739, "s": 75545, "text": "ColumnSet cols = new ColumnSet(new String[]{\n \"name\",\"address1_postalcode\",\"lastusedincampaign\"}); \nAccount retrievedAccount = \n (Account)_orgService.Retrieve(\"account\", _accountId, cols); " }, { "code": null, "e": 75831, "s": 75739, "text": "Step 4.6 − Once you have the retrieved record, you can set the updated value of the record." }, { "code": null, "e": 76015, "s": 75831, "text": "retrievedAccount.Address1_PostalCode = \"98052\"; \nretrievedAccount.Address2_PostalCode = null; \nretrievedAccount.Revenue = new Money(5000000); \nretrievedAccount.CreditOnHold = false; \n" }, { "code": null, "e": 76149, "s": 76015, "text": "Step 4.7 − After setting the updated value of the record, update the record back to CRM database using the Update web service method." }, { "code": null, "e": 76189, "s": 76149, "text": "_orgService.Update(retrievedAccount); \n" }, { "code": null, "e": 76261, "s": 76189, "text": "If you open the record in CRM, you will see these values updated there." }, { "code": null, "e": 76336, "s": 76261, "text": "Step 4.8 − Finally, delete the record using the Delete web service method." }, { "code": null, "e": 76397, "s": 76336, "text": "_orgService.Delete(Account.EntityLogicalName, _accountId); \n" }, { "code": null, "e": 76519, "s": 76397, "text": "If you now refresh the same record in CRM, you will see that the record is no more available since it is already deleted." }, { "code": null, "e": 76718, "s": 76519, "text": "In this chapter, we dealt with two important web services provided by CRM and a working example of how these web services can be used from an external application to perform various CRUD operations." }, { "code": null, "e": 77210, "s": 76718, "text": "Solutions provide a framework for packaging, installing, and uninstalling components to match your business functionalities. Solutions allow the customizers and developers to author, package, and maintain units of software that extend CRM. Any customizations, extensions, or configurations performed in CRM are packaged, managed, and distributed using solutions. The solutions can be exported as a zip file from the source organization, which can then be imported in the target organization." }, { "code": null, "e": 77277, "s": 77210, "text": "For understanding this, consider the following example scenarios −" }, { "code": null, "e": 77537, "s": 77277, "text": "You, as a developer or customizer, have extended or customized CRM in the development environment. Now you want to package your changes and move it to the next environment. For this, you can create individual solutions and publish them in higher environments." }, { "code": null, "e": 77797, "s": 77537, "text": "You, as a developer or customizer, have extended or customized CRM in the development environment. Now you want to package your changes and move it to the next environment. For this, you can create individual solutions and publish them in higher environments." }, { "code": null, "e": 78184, "s": 77797, "text": "You, as a third party CRM provider, have created a CRM module, which allows managing data in Microsoft Dynamics CRM entities using external Web service APIs. Now, you want to sell this module to other clients. Using solutions, you can package this module and distribute them to other clients who will be able to install this solution and use the functionalities provided by your module." }, { "code": null, "e": 78571, "s": 78184, "text": "You, as a third party CRM provider, have created a CRM module, which allows managing data in Microsoft Dynamics CRM entities using external Web service APIs. Now, you want to sell this module to other clients. Using solutions, you can package this module and distribute them to other clients who will be able to install this solution and use the functionalities provided by your module." }, { "code": null, "e": 78834, "s": 78571, "text": "The system solution contains the out-of-the-box solution components defined within Microsoft Dynamics CRM without any customizations. Many of the components in the system solution are customizable and can be used in managed solutions or unmanaged customizations." }, { "code": null, "e": 79071, "s": 78834, "text": "Throughout this tutorial, we did not create any solution and were customizing the default system solution. If you recall, we went to Settings → Customizations → Customize the System. This option directly customizes the default solution." }, { "code": null, "e": 79265, "s": 79071, "text": "A managed solution is a solution that is completed and intended to be distributed and installed. Managed solutions can be installed on the top of the system solution or other managed solutions." }, { "code": null, "e": 79284, "s": 79265, "text": "Important Points −" }, { "code": null, "e": 79418, "s": 79284, "text": "If you export a managed solution from one organization and import it to another, you can’t edit the solution in the new organization." }, { "code": null, "e": 79552, "s": 79418, "text": "If you export a managed solution from one organization and import it to another, you can’t edit the solution in the new organization." }, { "code": null, "e": 79620, "s": 79552, "text": "A managed solution does not directly reference the system solution." }, { "code": null, "e": 79688, "s": 79620, "text": "A managed solution does not directly reference the system solution." }, { "code": null, "e": 79784, "s": 79688, "text": "Uninstalling a managed solution uninstalls all the customizations associated with the solution." }, { "code": null, "e": 79880, "s": 79784, "text": "Uninstalling a managed solution uninstalls all the customizations associated with the solution." }, { "code": null, "e": 80204, "s": 79880, "text": "By default, a managed solution can’t be customized in the target organization. However, using the concept of managed properties you can define whether a solution component will be customizable and if yes, then which specific parts of the component will be customizable once the solution gets exported as a managed solution." }, { "code": null, "e": 80528, "s": 80204, "text": "By default, a managed solution can’t be customized in the target organization. However, using the concept of managed properties you can define whether a solution component will be customizable and if yes, then which specific parts of the component will be customizable once the solution gets exported as a managed solution." }, { "code": null, "e": 80914, "s": 80528, "text": "An unmanaged solution is a solution that is still under development and not intended to be distributed. An unmanaged solution contains all the unmanaged customizations of CRM components including any added, modified, removed, or deleted components. By default, any new solution is an unmanaged solution. However, you can export an unmanaged solution as a managed or unmanaged solution." }, { "code": null, "e": 80933, "s": 80914, "text": "Important Points −" }, { "code": null, "e": 81068, "s": 80933, "text": "If you export an unmanaged solution from one organization and import it to another, you can edit the solution in the new organization." }, { "code": null, "e": 81203, "s": 81068, "text": "If you export an unmanaged solution from one organization and import it to another, you can edit the solution in the new organization." }, { "code": null, "e": 81431, "s": 81203, "text": "An unmanaged solution directly references the system solution. Hence, the changes made to one unmanaged solution will be applied to all the unmanaged solutions that references the same components, including the system solution." }, { "code": null, "e": 81659, "s": 81431, "text": "An unmanaged solution directly references the system solution. Hence, the changes made to one unmanaged solution will be applied to all the unmanaged solutions that references the same components, including the system solution." }, { "code": null, "e": 81920, "s": 81659, "text": "If you delete a solution component from an unmanaged solution, the component gets deleted permanently from the system and will no longer be available. In case you just want to remove the component from specific unmanaged solution, use remove instead of delete." }, { "code": null, "e": 82181, "s": 81920, "text": "If you delete a solution component from an unmanaged solution, the component gets deleted permanently from the system and will no longer be available. In case you just want to remove the component from specific unmanaged solution, use remove instead of delete." }, { "code": null, "e": 82355, "s": 82181, "text": "Uninstalling an unmanaged solution does not remove the associated customizations. It just deletes the solution from the system, but the changes you made will still be there." }, { "code": null, "e": 82529, "s": 82355, "text": "Uninstalling an unmanaged solution does not remove the associated customizations. It just deletes the solution from the system, but the changes you made will still be there." }, { "code": null, "e": 82660, "s": 82529, "text": "A solution can be used to package the following components which can be customized using default, unmanaged, or managed solutions." }, { "code": null, "e": 82714, "s": 82660, "text": "Step 1 − Navigate to Settings → Solutions. Click New." }, { "code": null, "e": 82805, "s": 82714, "text": "Step 2 − In the window that follows, enter the following details and click Save and Close." }, { "code": null, "e": 82874, "s": 82805, "text": "Display Name − Sample Solution (This can be any name that you want)." }, { "code": null, "e": 82964, "s": 82874, "text": "Name − Will be automatically set based on the Display Name. However, you can change this." }, { "code": null, "e": 83277, "s": 82964, "text": "Publisher − Default Publisher. Solution publisher provides a common customization prefix and option value prefix. Defining a solution publisher controls how your managed solutions can be updated once distributed. However, for this example and for most of the general cases, you can set this as Default Publisher." }, { "code": null, "e": 83382, "s": 83277, "text": "Version − Specify a version with the following format: major.minor.build.revision. For example: 1.0.0.0." }, { "code": null, "e": 83701, "s": 83382, "text": "By default, every solution is added as an unmanaged solution. Once a solution is added, you can add solution components by creating them in the context of this solution or by adding the existing components from other solutions. For example, you can create new entities, forms, etc. in the context of this new solution." }, { "code": null, "e": 83842, "s": 83701, "text": "Once you have all the changes in place that you want to package as a managed or unmanaged solution, you can export your solution as follows." }, { "code": null, "e": 83991, "s": 83842, "text": "Step 1 − Open the source organization and navigate to Settings → Solutions. Select the solution that you want to export and click the Export button." }, { "code": null, "e": 84092, "s": 83991, "text": "Step 2 − In the Publish Customizations window, click Publish All Customizations and then click Next." }, { "code": null, "e": 84316, "s": 84092, "text": "Step 3 − In the window that follows, you can optionally select any system setting such as auto-numbering, calendar settings, etc. to be exported with the solution. For now, you can avoid selecting any option and click Next." }, { "code": null, "e": 84515, "s": 84316, "text": "Step 4 − In the Package Type window, you can select whether you want to export the package as a managed or unmanaged solution. For this example, let us export it as unmanaged. Once done, click Next." }, { "code": null, "e": 84650, "s": 84515, "text": "Step 5 − In the next window, you can see the source version of CRM that you are using and can select the target version. Click Export." }, { "code": null, "e": 84784, "s": 84650, "text": "Step 6 − Once you click Export, the solution will be exported as a zip file. Save this zip file at a desired location on your system." }, { "code": null, "e": 84897, "s": 84784, "text": "Now, we will import the solution zip file that we exported in the previous section to a new target organization." }, { "code": null, "e": 84987, "s": 84897, "text": "Step 1 − Open the target organization and navigate to Settings → Solutions. Click Import." }, { "code": null, "e": 85073, "s": 84987, "text": "Step 2 − Browse the zip file that you downloaded from the export step and click Next." }, { "code": null, "e": 85213, "s": 85073, "text": "Step 3 − From the next window, you can view the solution package details if needed. Clicking Import will start the solution import process." }, { "code": null, "e": 85483, "s": 85213, "text": "Step 4 − Once the import process completes, it will show the status of success or failure. If the process succeeds, click Publish All Customizations. In case the solution importing fails, it will give you a detailed error log on which step of the import process failed." }, { "code": null, "e": 85588, "s": 85483, "text": "Step 5 − We’re done. The solution will be successfully imported to the target organization. Click Close." }, { "code": null, "e": 86057, "s": 85588, "text": "Since you can have multiple developers working on customizing and extending CRM, you will have multiple managed and unmanaged solutions. Exporting and importing these solutions can sometimes result in conflict scenarios. For example, suppose ‘Solution A’ contains a field on a form while ‘Solution B’ has removed the field and ‘Solution C’ has renamed the field. In this scenario, what would be the final change? In such conflicting scenarios, CRM uses two approaches." }, { "code": null, "e": 86312, "s": 86057, "text": "Merge − This approach is used for user interface components such as command bar, ribbons and site maps. As per this approach, the solution components are re-calculated from the bottom and the organization’s unmanaged customizations are the last to apply." }, { "code": null, "e": 86521, "s": 86312, "text": "Top Wins − This approach is used for all other conflict scenarios except the user interface components. As per this approach, the last change (either managed or unmanaged) takes the priority and gets applied." }, { "code": null, "e": 86869, "s": 86521, "text": "In this chapter, we introduced the concept of solutions and different types of solution and their components. We then learnt how to create, export, and import a solution. Finally, we studied about the two conflict resolution strategies, which takes place when we have multiple managed and unmanaged solution affecting the same solution components." }, { "code": null, "e": 86905, "s": 86869, "text": "\n 16 Lectures \n 11.5 hours \n" }, { "code": null, "e": 86925, "s": 86905, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 86958, "s": 86925, "text": "\n 33 Lectures \n 3 hours \n" }, { "code": null, "e": 86980, "s": 86958, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 87015, "s": 86980, "text": "\n 33 Lectures \n 5.5 hours \n" }, { "code": null, "e": 87037, "s": 87015, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 87072, "s": 87037, "text": "\n 40 Lectures \n 6.5 hours \n" }, { "code": null, "e": 87083, "s": 87072, "text": " Syed Raza" }, { "code": null, "e": 87116, "s": 87083, "text": "\n 15 Lectures \n 2 hours \n" }, { "code": null, "e": 87156, "s": 87116, "text": " Harshit Srivastava, Pranjal Srivastava" }, { "code": null, "e": 87191, "s": 87156, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 87231, "s": 87191, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 87238, "s": 87231, "text": " Print" }, { "code": null, "e": 87249, "s": 87238, "text": " Add Notes" } ]
Run Python 3 on Sublime Text (Mac) | by Wafiq Syed | Towards Data Science
Sublime Text is one of the most widely used lightweight text editors when it comes to programming. If you’re a Python programmer, you may not be running your preferred version of Python. This tutorial explains how to get Sublime Text running Python 3.7. If you prefer a video tutorial, here’s my accompanying YouTube video: Create a new Python file. I called mine scratch.py. It’s important that you save your file as a .py extension before running Python code. Otherwise, you won’t be able to execute Python code. Also, it’s always nice to have a scratch Python file to run quick code. Now type the following code: import sysprint(sys.version) To run the code, press Command B or go to Tools -> Build. As you can see, my Sublime Text is running Python 2.7. To change this to Python 3.7, we have to add a “Build System.” Go to Tools -> Build System -> New Build System.. Notice, in my list of Build Systems, I have both Python and Python 3. Python comes automatically and runs 2.7. Python3 is what we’re going to add. Once you click New Build System... you’ll be brought to a new window called untitled.sublime-build. We need to change the text between the curly brackets. First delete the code between the brackets. Next copy and paste the following code: "cmd": ["python3", "-i", "-u", "$file"], "file_regex": "^[ ]File \"(...?)\", line ([0-9]*)", "selector": "source.python" You might have to press Tab to indent the second and third lines. Now save the file by pressing Command S. Rename the file to what you’d like to call your Build System. Something short and clear to understand. I named mine Python3. Note, don’t change the extension, it must be .sublime-build. And don’t change the path either. Sublime Text will put it in the right path by default. Once you click save, close the file so that you’re back on your scratch.py file. Now go to Tools -> Build System, and select Python3 (or whatever you named your Build System). If you don’t see your new build system, you may have to quit Sublime Text and reopen it. Now run the same code to test which version of Python you’re using. There you go, Python 3.7 up and running. Happy coding! If you’d like to see my video tutorial on running python 3 in Sublime Text, click this link: https://youtu.be/IprbE2C_rsEv
[ { "code": null, "e": 425, "s": 171, "text": "Sublime Text is one of the most widely used lightweight text editors when it comes to programming. If you’re a Python programmer, you may not be running your preferred version of Python. This tutorial explains how to get Sublime Text running Python 3.7." }, { "code": null, "e": 495, "s": 425, "text": "If you prefer a video tutorial, here’s my accompanying YouTube video:" }, { "code": null, "e": 758, "s": 495, "text": "Create a new Python file. I called mine scratch.py. It’s important that you save your file as a .py extension before running Python code. Otherwise, you won’t be able to execute Python code. Also, it’s always nice to have a scratch Python file to run quick code." }, { "code": null, "e": 787, "s": 758, "text": "Now type the following code:" }, { "code": null, "e": 816, "s": 787, "text": "import sysprint(sys.version)" }, { "code": null, "e": 874, "s": 816, "text": "To run the code, press Command B or go to Tools -> Build." }, { "code": null, "e": 992, "s": 874, "text": "As you can see, my Sublime Text is running Python 2.7. To change this to Python 3.7, we have to add a “Build System.”" }, { "code": null, "e": 1042, "s": 992, "text": "Go to Tools -> Build System -> New Build System.." }, { "code": null, "e": 1189, "s": 1042, "text": "Notice, in my list of Build Systems, I have both Python and Python 3. Python comes automatically and runs 2.7. Python3 is what we’re going to add." }, { "code": null, "e": 1289, "s": 1189, "text": "Once you click New Build System... you’ll be brought to a new window called untitled.sublime-build." }, { "code": null, "e": 1428, "s": 1289, "text": "We need to change the text between the curly brackets. First delete the code between the brackets. Next copy and paste the following code:" }, { "code": null, "e": 1557, "s": 1428, "text": "\"cmd\": [\"python3\", \"-i\", \"-u\", \"$file\"], \"file_regex\": \"^[ ]File \\\"(...?)\\\", line ([0-9]*)\", \"selector\": \"source.python\"" }, { "code": null, "e": 1939, "s": 1557, "text": "You might have to press Tab to indent the second and third lines. Now save the file by pressing Command S. Rename the file to what you’d like to call your Build System. Something short and clear to understand. I named mine Python3. Note, don’t change the extension, it must be .sublime-build. And don’t change the path either. Sublime Text will put it in the right path by default." }, { "code": null, "e": 2204, "s": 1939, "text": "Once you click save, close the file so that you’re back on your scratch.py file. Now go to Tools -> Build System, and select Python3 (or whatever you named your Build System). If you don’t see your new build system, you may have to quit Sublime Text and reopen it." }, { "code": null, "e": 2272, "s": 2204, "text": "Now run the same code to test which version of Python you’re using." }, { "code": null, "e": 2327, "s": 2272, "text": "There you go, Python 3.7 up and running. Happy coding!" } ]
How to Read a Text File in Android? - GeeksforGeeks
11 Aug, 2021 A text file is a type of file that can store a sequence of characters or text. These characters can be anything that is human-readable. Such kind of files does not have any formatting for the text like Bold, Italics, Underline, Font, Font Size, etc. A Text file in Android can be used for accessing or reading the information or text present in it. Meaning, information could be stored in a text file and could be accessed whenever required in the run-time. So, through this article, we will show you how you could read or fetch text from a text file in Android. Step 1: Create a New Project in Android Studio To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project. Step 2: Create an asset folder Please refer to Assets Folder in Android Studio to create an assets folder in Android Studio. We shall be creating a text file in the assets folder. Step 3: Create a text file in the asset folder We can create a text file by simply right-clicking on the assets folder, drag the mouse on new, and click on File. Now type in some desired name, add “.txt” extension, and press Enter. Another way of doing the same is creating a text file on Desktop and simply copying it into the assets folder. This is how our text file looks like: MyText.txt: GeeksforGeeks A computer science portal for geeks Step 4: Add a TextView in the layout file (activity_main.xml) We will add a TextView in the layout to display the text from the text file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!-- A TextView to show the data from the text file--> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:gravity="center"/> </RelativeLayout> Step 5: Write the below program in the main code (MainActivity.kt) In the main code, we will be reading the text file and displaying the text from this file in the TextView. Please refer to the comments available at almost every line of code for better understanding. Kotlin import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.TextViewimport java.io.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declaring and initializing the TextView from the layout val myTextView = findViewById<TextView>(R.id.textView) // A string variable to store the text from the text file val myOutput: String // Declaring an input stream to read data val myInputStream: InputStream // Try to open the text file, reads // the data and stores it in the string try { myInputStream = assets.open("MyText.txt") val size: Int = myInputStream.available() val buffer = ByteArray(size) myInputStream.read(buffer) myOutput = String(buffer) // Sets the TextView with the string myTextView.text = myOutput } catch (e: IOException) { // Exception e.printStackTrace() } }} Output: As soon as the application launches, we can see that the text from the text file is displayed in the TextView. Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? Flexbox-Layout in Android How to Post Data to API using Retrofit in Android? Android UI Layouts Kotlin Array Retrofit with Kotlin Coroutine in Android Kotlin Setters and Getters Kotlin when expression
[ { "code": null, "e": 26491, "s": 26463, "text": "\n11 Aug, 2021" }, { "code": null, "e": 27054, "s": 26491, "text": "A text file is a type of file that can store a sequence of characters or text. These characters can be anything that is human-readable. Such kind of files does not have any formatting for the text like Bold, Italics, Underline, Font, Font Size, etc. A Text file in Android can be used for accessing or reading the information or text present in it. Meaning, information could be stored in a text file and could be accessed whenever required in the run-time. So, through this article, we will show you how you could read or fetch text from a text file in Android." }, { "code": null, "e": 27101, "s": 27054, "text": "Step 1: Create a New Project in Android Studio" }, { "code": null, "e": 27340, "s": 27101, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project." }, { "code": null, "e": 27371, "s": 27340, "text": "Step 2: Create an asset folder" }, { "code": null, "e": 27520, "s": 27371, "text": "Please refer to Assets Folder in Android Studio to create an assets folder in Android Studio. We shall be creating a text file in the assets folder." }, { "code": null, "e": 27567, "s": 27520, "text": "Step 3: Create a text file in the asset folder" }, { "code": null, "e": 27901, "s": 27567, "text": "We can create a text file by simply right-clicking on the assets folder, drag the mouse on new, and click on File. Now type in some desired name, add “.txt” extension, and press Enter. Another way of doing the same is creating a text file on Desktop and simply copying it into the assets folder. This is how our text file looks like:" }, { "code": null, "e": 27913, "s": 27901, "text": "MyText.txt:" }, { "code": null, "e": 27963, "s": 27913, "text": "GeeksforGeeks\nA computer science portal for geeks" }, { "code": null, "e": 28025, "s": 27963, "text": "Step 4: Add a TextView in the layout file (activity_main.xml)" }, { "code": null, "e": 28102, "s": 28025, "text": "We will add a TextView in the layout to display the text from the text file." }, { "code": null, "e": 28106, "s": 28102, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!-- A TextView to show the data from the text file--> <TextView android:id=\"@+id/textView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:gravity=\"center\"/> </RelativeLayout>", "e": 28677, "s": 28106, "text": null }, { "code": null, "e": 28744, "s": 28677, "text": "Step 5: Write the below program in the main code (MainActivity.kt)" }, { "code": null, "e": 28945, "s": 28744, "text": "In the main code, we will be reading the text file and displaying the text from this file in the TextView. Please refer to the comments available at almost every line of code for better understanding." }, { "code": null, "e": 28952, "s": 28945, "text": "Kotlin" }, { "code": "import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.TextViewimport java.io.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declaring and initializing the TextView from the layout val myTextView = findViewById<TextView>(R.id.textView) // A string variable to store the text from the text file val myOutput: String // Declaring an input stream to read data val myInputStream: InputStream // Try to open the text file, reads // the data and stores it in the string try { myInputStream = assets.open(\"MyText.txt\") val size: Int = myInputStream.available() val buffer = ByteArray(size) myInputStream.read(buffer) myOutput = String(buffer) // Sets the TextView with the string myTextView.text = myOutput } catch (e: IOException) { // Exception e.printStackTrace() } }}", "e": 30095, "s": 28952, "text": null }, { "code": null, "e": 30103, "s": 30095, "text": "Output:" }, { "code": null, "e": 30214, "s": 30103, "text": "As soon as the application launches, we can see that the text from the text file is displayed in the TextView." }, { "code": null, "e": 30222, "s": 30214, "text": "Android" }, { "code": null, "e": 30229, "s": 30222, "text": "Kotlin" }, { "code": null, "e": 30237, "s": 30229, "text": "Android" }, { "code": null, "e": 30335, "s": 30237, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30373, "s": 30335, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 30412, "s": 30373, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 30462, "s": 30412, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 30488, "s": 30462, "text": "Flexbox-Layout in Android" }, { "code": null, "e": 30539, "s": 30488, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 30558, "s": 30539, "text": "Android UI Layouts" }, { "code": null, "e": 30571, "s": 30558, "text": "Kotlin Array" }, { "code": null, "e": 30613, "s": 30571, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 30640, "s": 30613, "text": "Kotlin Setters and Getters" } ]
Dart Programming - Runes
Strings are a sequence of characters. Dart represents strings as a sequence of Unicode UTF-16 code units. Unicode is a format that defines a unique numeric value for each letter, digit, and symbol. Since a Dart string is a sequence of UTF-16 code units, 32-bit Unicode values within a string are represented using a special syntax. A rune is an integer representing a Unicode code point. The String class in the dart:core library provides mechanisms to access runes. String code units / runes can be accessed in three ways − Using String.codeUnitAt() function Using String.codeUnits property Using String.runes property Code units in a string can be accessed through their indexes. Returns the 16-bit UTF-16 code unit at the given index. String.codeUnitAt(int index); import 'dart:core'; void main(){ f1(); } f1() { String x = 'Runes'; print(x.codeUnitAt(0)); } It will produce the following output − 82 This property returns an unmodifiable list of the UTF-16 code units of the specified string. String. codeUnits; import 'dart:core'; void main(){ f1(); } f1() { String x = 'Runes'; print(x.codeUnits); } It will produce the following output − [82, 117, 110, 101, 115] This property returns an iterable of Unicode code-points of this string.Runes extends iterable. String.runes void main(){ "A string".runes.forEach((int rune) { var character=new String.fromCharCode(rune); print(character); }); } It will produce the following output − A s t r i n g Unicode code points are usually expressed as \uXXXX, where XXXX is a 4-digit hexadecimal value. To specify more or less than 4 hex digits, place the value in curly brackets. One can use the constructor of the Runes class in the dart:core library for the same. main() { Runes input = new Runes(' \u{1f605} '); print(new String.fromCharCodes(input)); } It will produce the following output − 44 Lectures 4.5 hours Sriyank Siddhartha 34 Lectures 4 hours Sriyank Siddhartha 69 Lectures 4 hours Frahaan Hussain 117 Lectures 10 hours Frahaan Hussain 22 Lectures 1.5 hours Pranjal Srivastava 34 Lectures 3 hours Pranjal Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2724, "s": 2525, "text": "Strings are a sequence of characters. Dart represents strings as a sequence of Unicode UTF-16 code units. Unicode is a format that defines a unique numeric value for each letter, digit, and symbol." }, { "code": null, "e": 2914, "s": 2724, "text": "Since a Dart string is a sequence of UTF-16 code units, 32-bit Unicode values within a string are represented using a special syntax. A rune is an integer representing a Unicode code point." }, { "code": null, "e": 3051, "s": 2914, "text": "The String class in the dart:core library provides mechanisms to access runes. String code units / runes can be accessed in three ways −" }, { "code": null, "e": 3086, "s": 3051, "text": "Using String.codeUnitAt() function" }, { "code": null, "e": 3118, "s": 3086, "text": "Using String.codeUnits property" }, { "code": null, "e": 3146, "s": 3118, "text": "Using String.runes property" }, { "code": null, "e": 3264, "s": 3146, "text": "Code units in a string can be accessed through their indexes. Returns the 16-bit UTF-16 code unit at the given index." }, { "code": null, "e": 3295, "s": 3264, "text": "String.codeUnitAt(int index);\n" }, { "code": null, "e": 3405, "s": 3295, "text": "import 'dart:core'; \nvoid main(){ \n f1(); \n} \nf1() { \n String x = 'Runes'; \n print(x.codeUnitAt(0)); \n}" }, { "code": null, "e": 3444, "s": 3405, "text": "It will produce the following output −" }, { "code": null, "e": 3448, "s": 3444, "text": "82\n" }, { "code": null, "e": 3541, "s": 3448, "text": "This property returns an unmodifiable list of the UTF-16 code units of the specified string." }, { "code": null, "e": 3561, "s": 3541, "text": "String. codeUnits;\n" }, { "code": null, "e": 3670, "s": 3561, "text": "import 'dart:core'; \nvoid main(){ \n f1(); \n} \nf1() { \n String x = 'Runes'; \n print(x.codeUnits); \n} " }, { "code": null, "e": 3709, "s": 3670, "text": "It will produce the following output −" }, { "code": null, "e": 3735, "s": 3709, "text": "[82, 117, 110, 101, 115]\n" }, { "code": null, "e": 3831, "s": 3735, "text": "This property returns an iterable of Unicode code-points of this string.Runes extends iterable." }, { "code": null, "e": 3845, "s": 3831, "text": "String.runes\n" }, { "code": null, "e": 3990, "s": 3845, "text": "void main(){ \n \"A string\".runes.forEach((int rune) { \n var character=new String.fromCharCode(rune); \n print(character); \n }); \n} " }, { "code": null, "e": 4029, "s": 3990, "text": "It will produce the following output −" }, { "code": null, "e": 4050, "s": 4029, "text": "A \ns \nt \nr \ni \nn \ng\n" }, { "code": null, "e": 4311, "s": 4050, "text": "Unicode code points are usually expressed as \\uXXXX, where XXXX is a 4-digit hexadecimal value. To specify more or less than 4 hex digits, place the value in curly brackets. One can use the constructor of the Runes class in the dart:core library for the same." }, { "code": null, "e": 4413, "s": 4311, "text": "main() { \n Runes input = new Runes(' \\u{1f605} '); \n print(new String.fromCharCodes(input)); \n} " }, { "code": null, "e": 4452, "s": 4413, "text": "It will produce the following output −" }, { "code": null, "e": 4487, "s": 4452, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4507, "s": 4487, "text": " Sriyank Siddhartha" }, { "code": null, "e": 4540, "s": 4507, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 4560, "s": 4540, "text": " Sriyank Siddhartha" }, { "code": null, "e": 4593, "s": 4560, "text": "\n 69 Lectures \n 4 hours \n" }, { "code": null, "e": 4610, "s": 4593, "text": " Frahaan Hussain" }, { "code": null, "e": 4645, "s": 4610, "text": "\n 117 Lectures \n 10 hours \n" }, { "code": null, "e": 4662, "s": 4645, "text": " Frahaan Hussain" }, { "code": null, "e": 4697, "s": 4662, "text": "\n 22 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4717, "s": 4697, "text": " Pranjal Srivastava" }, { "code": null, "e": 4750, "s": 4717, "text": "\n 34 Lectures \n 3 hours \n" }, { "code": null, "e": 4770, "s": 4750, "text": " Pranjal Srivastava" }, { "code": null, "e": 4777, "s": 4770, "text": " Print" }, { "code": null, "e": 4788, "s": 4777, "text": " Add Notes" } ]
WebGL - Cube Rotation
In this chapter, we will take an example to demonstrate how to draw a rotating 3D cube using WebGL. The following program shows how to draw a rotating 3D cube − <!doctype html> <html> <body> <canvas width = "570" height = "570" id = "my_Canvas"></canvas> <script> /*============= Creating a canvas =================*/ var canvas = document.getElementById('my_Canvas'); gl = canvas.getContext('experimental-webgl'); /*============ Defining and storing the geometry =========*/ var vertices = [ -1,-1,-1, 1,-1,-1, 1, 1,-1, -1, 1,-1, -1,-1, 1, 1,-1, 1, 1, 1, 1, -1, 1, 1, -1,-1,-1, -1, 1,-1, -1, 1, 1, -1,-1, 1, 1,-1,-1, 1, 1,-1, 1, 1, 1, 1,-1, 1, -1,-1,-1, -1,-1, 1, 1,-1, 1, 1,-1,-1, -1, 1,-1, -1, 1, 1, 1, 1, 1, 1, 1,-1, ]; var colors = [ 5,3,7, 5,3,7, 5,3,7, 5,3,7, 1,1,3, 1,1,3, 1,1,3, 1,1,3, 0,0,1, 0,0,1, 0,0,1, 0,0,1, 1,0,0, 1,0,0, 1,0,0, 1,0,0, 1,1,0, 1,1,0, 1,1,0, 1,1,0, 0,1,0, 0,1,0, 0,1,0, 0,1,0 ]; var indices = [ 0,1,2, 0,2,3, 4,5,6, 4,6,7, 8,9,10, 8,10,11, 12,13,14, 12,14,15, 16,17,18, 16,18,19, 20,21,22, 20,22,23 ]; // Create and store data into vertex buffer var vertex_buffer = gl.createBuffer (); gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); // Create and store data into color buffer var color_buffer = gl.createBuffer (); gl.bindBuffer(gl.ARRAY_BUFFER, color_buffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW); // Create and store data into index buffer var index_buffer = gl.createBuffer (); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW); /*=================== Shaders =========================*/ var vertCode = 'attribute vec3 position;'+ 'uniform mat4 Pmatrix;'+ 'uniform mat4 Vmatrix;'+ 'uniform mat4 Mmatrix;'+ 'attribute vec3 color;'+//the color of the point 'varying vec3 vColor;'+ 'void main(void) { '+//pre-built function 'gl_Position = Pmatrix*Vmatrix*Mmatrix*vec4(position, 1.);'+ 'vColor = color;'+ '}'; var fragCode = 'precision mediump float;'+ 'varying vec3 vColor;'+ 'void main(void) {'+ 'gl_FragColor = vec4(vColor, 1.);'+ '}'; var vertShader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vertShader, vertCode); gl.compileShader(vertShader); var fragShader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(fragShader, fragCode); gl.compileShader(fragShader); var shaderProgram = gl.createProgram(); gl.attachShader(shaderProgram, vertShader); gl.attachShader(shaderProgram, fragShader); gl.linkProgram(shaderProgram); /* ====== Associating attributes to vertex shader =====*/ var Pmatrix = gl.getUniformLocation(shaderProgram, "Pmatrix"); var Vmatrix = gl.getUniformLocation(shaderProgram, "Vmatrix"); var Mmatrix = gl.getUniformLocation(shaderProgram, "Mmatrix"); gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer); var position = gl.getAttribLocation(shaderProgram, "position"); gl.vertexAttribPointer(position, 3, gl.FLOAT, false,0,0) ; // Position gl.enableVertexAttribArray(position); gl.bindBuffer(gl.ARRAY_BUFFER, color_buffer); var color = gl.getAttribLocation(shaderProgram, "color"); gl.vertexAttribPointer(color, 3, gl.FLOAT, false,0,0) ; // Color gl.enableVertexAttribArray(color); gl.useProgram(shaderProgram); /*==================== MATRIX =====================*/ function get_projection(angle, a, zMin, zMax) { var ang = Math.tan((angle*.5)*Math.PI/180);//angle*.5 return [ 0.5/ang, 0 , 0, 0, 0, 0.5*a/ang, 0, 0, 0, 0, -(zMax+zMin)/(zMax-zMin), -1, 0, 0, (-2*zMax*zMin)/(zMax-zMin), 0 ]; } var proj_matrix = get_projection(40, canvas.width/canvas.height, 1, 100); var mov_matrix = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1]; var view_matrix = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1]; // translating z view_matrix[14] = view_matrix[14]-6;//zoom /*==================== Rotation ====================*/ function rotateZ(m, angle) { var c = Math.cos(angle); var s = Math.sin(angle); var mv0 = m[0], mv4 = m[4], mv8 = m[8]; m[0] = c*m[0]-s*m[1]; m[4] = c*m[4]-s*m[5]; m[8] = c*m[8]-s*m[9]; m[1]=c*m[1]+s*mv0; m[5]=c*m[5]+s*mv4; m[9]=c*m[9]+s*mv8; } function rotateX(m, angle) { var c = Math.cos(angle); var s = Math.sin(angle); var mv1 = m[1], mv5 = m[5], mv9 = m[9]; m[1] = m[1]*c-m[2]*s; m[5] = m[5]*c-m[6]*s; m[9] = m[9]*c-m[10]*s; m[2] = m[2]*c+mv1*s; m[6] = m[6]*c+mv5*s; m[10] = m[10]*c+mv9*s; } function rotateY(m, angle) { var c = Math.cos(angle); var s = Math.sin(angle); var mv0 = m[0], mv4 = m[4], mv8 = m[8]; m[0] = c*m[0]+s*m[2]; m[4] = c*m[4]+s*m[6]; m[8] = c*m[8]+s*m[10]; m[2] = c*m[2]-s*mv0; m[6] = c*m[6]-s*mv4; m[10] = c*m[10]-s*mv8; } /*================= Drawing ===========================*/ var time_old = 0; var animate = function(time) { var dt = time-time_old; rotateZ(mov_matrix, dt*0.005);//time rotateY(mov_matrix, dt*0.002); rotateX(mov_matrix, dt*0.003); time_old = time; gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.LEQUAL); gl.clearColor(0.5, 0.5, 0.5, 0.9); gl.clearDepth(1.0); gl.viewport(0.0, 0.0, canvas.width, canvas.height); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); gl.uniformMatrix4fv(Pmatrix, false, proj_matrix); gl.uniformMatrix4fv(Vmatrix, false, view_matrix); gl.uniformMatrix4fv(Mmatrix, false, mov_matrix); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer); gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT, 0); window.requestAnimationFrame(animate); } animate(0); </script> </body> </html> If you run this example, it will produce the following output −
[ { "code": null, "e": 2281, "s": 2181, "text": "In this chapter, we will take an example to demonstrate how to draw a rotating 3D cube using WebGL." }, { "code": null, "e": 2342, "s": 2281, "text": "The following program shows how to draw a rotating 3D cube −" }, { "code": null, "e": 9255, "s": 2342, "text": "<!doctype html>\n<html>\n <body>\n <canvas width = \"570\" height = \"570\" id = \"my_Canvas\"></canvas>\n\n <script>\n /*============= Creating a canvas =================*/\n var canvas = document.getElementById('my_Canvas');\n gl = canvas.getContext('experimental-webgl');\n\n /*============ Defining and storing the geometry =========*/\n\n var vertices = [\n -1,-1,-1, 1,-1,-1, 1, 1,-1, -1, 1,-1,\n -1,-1, 1, 1,-1, 1, 1, 1, 1, -1, 1, 1,\n -1,-1,-1, -1, 1,-1, -1, 1, 1, -1,-1, 1,\n 1,-1,-1, 1, 1,-1, 1, 1, 1, 1,-1, 1,\n -1,-1,-1, -1,-1, 1, 1,-1, 1, 1,-1,-1,\n -1, 1,-1, -1, 1, 1, 1, 1, 1, 1, 1,-1, \n ];\n\n var colors = [\n 5,3,7, 5,3,7, 5,3,7, 5,3,7,\n 1,1,3, 1,1,3, 1,1,3, 1,1,3,\n 0,0,1, 0,0,1, 0,0,1, 0,0,1,\n 1,0,0, 1,0,0, 1,0,0, 1,0,0,\n 1,1,0, 1,1,0, 1,1,0, 1,1,0,\n 0,1,0, 0,1,0, 0,1,0, 0,1,0\n ];\n\n var indices = [\n 0,1,2, 0,2,3, 4,5,6, 4,6,7,\n 8,9,10, 8,10,11, 12,13,14, 12,14,15,\n 16,17,18, 16,18,19, 20,21,22, 20,22,23 \n ];\n\n // Create and store data into vertex buffer\n var vertex_buffer = gl.createBuffer ();\n gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);\n\n // Create and store data into color buffer\n var color_buffer = gl.createBuffer ();\n gl.bindBuffer(gl.ARRAY_BUFFER, color_buffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);\n\n // Create and store data into index buffer\n var index_buffer = gl.createBuffer ();\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer);\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);\n\n /*=================== Shaders =========================*/\n\n var vertCode = 'attribute vec3 position;'+\n 'uniform mat4 Pmatrix;'+\n 'uniform mat4 Vmatrix;'+\n 'uniform mat4 Mmatrix;'+\n 'attribute vec3 color;'+//the color of the point\n 'varying vec3 vColor;'+\n\n 'void main(void) { '+//pre-built function\n 'gl_Position = Pmatrix*Vmatrix*Mmatrix*vec4(position, 1.);'+\n 'vColor = color;'+\n '}';\n\n var fragCode = 'precision mediump float;'+\n 'varying vec3 vColor;'+\n 'void main(void) {'+\n 'gl_FragColor = vec4(vColor, 1.);'+\n '}';\n\n var vertShader = gl.createShader(gl.VERTEX_SHADER);\n gl.shaderSource(vertShader, vertCode);\n gl.compileShader(vertShader);\n\n var fragShader = gl.createShader(gl.FRAGMENT_SHADER);\n gl.shaderSource(fragShader, fragCode);\n gl.compileShader(fragShader);\n\n var shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vertShader);\n gl.attachShader(shaderProgram, fragShader);\n gl.linkProgram(shaderProgram);\n\n /* ====== Associating attributes to vertex shader =====*/\n var Pmatrix = gl.getUniformLocation(shaderProgram, \"Pmatrix\");\n var Vmatrix = gl.getUniformLocation(shaderProgram, \"Vmatrix\");\n var Mmatrix = gl.getUniformLocation(shaderProgram, \"Mmatrix\");\n\n gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);\n var position = gl.getAttribLocation(shaderProgram, \"position\");\n gl.vertexAttribPointer(position, 3, gl.FLOAT, false,0,0) ;\n\n // Position\n gl.enableVertexAttribArray(position);\n gl.bindBuffer(gl.ARRAY_BUFFER, color_buffer);\n var color = gl.getAttribLocation(shaderProgram, \"color\");\n gl.vertexAttribPointer(color, 3, gl.FLOAT, false,0,0) ;\n\n // Color\n gl.enableVertexAttribArray(color);\n gl.useProgram(shaderProgram);\n\n /*==================== MATRIX =====================*/\n\n function get_projection(angle, a, zMin, zMax) {\n var ang = Math.tan((angle*.5)*Math.PI/180);//angle*.5\n return [\n 0.5/ang, 0 , 0, 0,\n 0, 0.5*a/ang, 0, 0,\n 0, 0, -(zMax+zMin)/(zMax-zMin), -1,\n 0, 0, (-2*zMax*zMin)/(zMax-zMin), 0 \n ];\n }\n\n var proj_matrix = get_projection(40, canvas.width/canvas.height, 1, 100);\n\n var mov_matrix = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1];\n var view_matrix = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1];\n\n // translating z\n view_matrix[14] = view_matrix[14]-6;//zoom\n\n /*==================== Rotation ====================*/\n\n function rotateZ(m, angle) {\n var c = Math.cos(angle);\n var s = Math.sin(angle);\n var mv0 = m[0], mv4 = m[4], mv8 = m[8];\n\n m[0] = c*m[0]-s*m[1];\n m[4] = c*m[4]-s*m[5];\n m[8] = c*m[8]-s*m[9];\n\n m[1]=c*m[1]+s*mv0;\n m[5]=c*m[5]+s*mv4;\n m[9]=c*m[9]+s*mv8;\n }\n\n function rotateX(m, angle) {\n var c = Math.cos(angle);\n var s = Math.sin(angle);\n var mv1 = m[1], mv5 = m[5], mv9 = m[9];\n\n m[1] = m[1]*c-m[2]*s;\n m[5] = m[5]*c-m[6]*s;\n m[9] = m[9]*c-m[10]*s;\n\n m[2] = m[2]*c+mv1*s;\n m[6] = m[6]*c+mv5*s;\n m[10] = m[10]*c+mv9*s;\n }\n\n function rotateY(m, angle) {\n var c = Math.cos(angle);\n var s = Math.sin(angle);\n var mv0 = m[0], mv4 = m[4], mv8 = m[8];\n\n m[0] = c*m[0]+s*m[2];\n m[4] = c*m[4]+s*m[6];\n m[8] = c*m[8]+s*m[10];\n\n m[2] = c*m[2]-s*mv0;\n m[6] = c*m[6]-s*mv4;\n m[10] = c*m[10]-s*mv8;\n }\n\n /*================= Drawing ===========================*/\n var time_old = 0;\n\n var animate = function(time) {\n\n var dt = time-time_old;\n rotateZ(mov_matrix, dt*0.005);//time\n rotateY(mov_matrix, dt*0.002);\n rotateX(mov_matrix, dt*0.003);\n time_old = time;\n\n gl.enable(gl.DEPTH_TEST);\n gl.depthFunc(gl.LEQUAL);\n gl.clearColor(0.5, 0.5, 0.5, 0.9);\n gl.clearDepth(1.0);\n\n gl.viewport(0.0, 0.0, canvas.width, canvas.height);\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n gl.uniformMatrix4fv(Pmatrix, false, proj_matrix);\n gl.uniformMatrix4fv(Vmatrix, false, view_matrix);\n gl.uniformMatrix4fv(Mmatrix, false, mov_matrix);\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer);\n gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT, 0);\n\n window.requestAnimationFrame(animate);\n }\n animate(0);\n </script>\n </body>\n</html>" } ]
C library function - calloc()
The C library function void *calloc(size_t nitems, size_t size) allocates the requested memory and returns a pointer to it. The difference in malloc and calloc is that malloc does not set the memory to zero where as calloc sets allocated memory to zero. Following is the declaration for calloc() function. void *calloc(size_t nitems, size_t size) nitems − This is the number of elements to be allocated. nitems − This is the number of elements to be allocated. size − This is the size of elements. size − This is the size of elements. This function returns a pointer to the allocated memory, or NULL if the request fails. The following example shows the usage of calloc() function. #include <stdio.h> #include <stdlib.h> int main () { int i, n; int *a; printf("Number of elements to be entered:"); scanf("%d",&n); a = (int*)calloc(n, sizeof(int)); printf("Enter %d numbers:\n",n); for( i=0 ; i < n ; i++ ) { scanf("%d",&a[i]); } printf("The numbers entered are: "); for( i=0 ; i < n ; i++ ) { printf("%d ",a[i]); } free( a ); return(0); } Let us compile and run the above program that will produce the following result − Number of elements to be entered:3 Enter 3 numbers: 22 55 14 The numbers entered are: 22 55 14 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2261, "s": 2007, "text": "The C library function void *calloc(size_t nitems, size_t size) allocates the requested memory and returns a pointer to it. The difference in malloc and calloc is that malloc does not set the memory to zero where as calloc sets allocated memory to zero." }, { "code": null, "e": 2313, "s": 2261, "text": "Following is the declaration for calloc() function." }, { "code": null, "e": 2354, "s": 2313, "text": "void *calloc(size_t nitems, size_t size)" }, { "code": null, "e": 2411, "s": 2354, "text": "nitems − This is the number of elements to be allocated." }, { "code": null, "e": 2468, "s": 2411, "text": "nitems − This is the number of elements to be allocated." }, { "code": null, "e": 2505, "s": 2468, "text": "size − This is the size of elements." }, { "code": null, "e": 2542, "s": 2505, "text": "size − This is the size of elements." }, { "code": null, "e": 2629, "s": 2542, "text": "This function returns a pointer to the allocated memory, or NULL if the request fails." }, { "code": null, "e": 2689, "s": 2629, "text": "The following example shows the usage of calloc() function." }, { "code": null, "e": 3105, "s": 2689, "text": "#include <stdio.h>\n#include <stdlib.h>\n\nint main () {\n int i, n;\n int *a;\n\n printf(\"Number of elements to be entered:\");\n scanf(\"%d\",&n);\n\n a = (int*)calloc(n, sizeof(int));\n printf(\"Enter %d numbers:\\n\",n);\n for( i=0 ; i < n ; i++ ) {\n scanf(\"%d\",&a[i]);\n }\n\n printf(\"The numbers entered are: \");\n for( i=0 ; i < n ; i++ ) {\n printf(\"%d \",a[i]);\n }\n free( a );\n \n return(0);\n}" }, { "code": null, "e": 3187, "s": 3105, "text": "Let us compile and run the above program that will produce the following result −" }, { "code": null, "e": 3283, "s": 3187, "text": "Number of elements to be entered:3\nEnter 3 numbers:\n22\n55\n14\nThe numbers entered are: 22 55 14\n" }, { "code": null, "e": 3316, "s": 3283, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3331, "s": 3316, "text": " Nishant Malik" }, { "code": null, "e": 3366, "s": 3331, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3381, "s": 3366, "text": " Nishant Malik" }, { "code": null, "e": 3416, "s": 3381, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3430, "s": 3416, "text": " Asif Hussain" }, { "code": null, "e": 3463, "s": 3430, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3481, "s": 3463, "text": " Richa Maheshwari" }, { "code": null, "e": 3516, "s": 3481, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3535, "s": 3516, "text": " Vandana Annavaram" }, { "code": null, "e": 3568, "s": 3535, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 3580, "s": 3568, "text": " Amit Diwan" }, { "code": null, "e": 3587, "s": 3580, "text": " Print" }, { "code": null, "e": 3598, "s": 3587, "text": " Add Notes" } ]
C++ Program for Products of ranges in an array - GeeksforGeeks
20 Jan, 2022 Given an array A[] of size N. Solve Q queries. Find the product in the range [L, R] under modulo P ( P is Prime). Examples: Input : A[] = {1, 2, 3, 4, 5, 6} L = 2, R = 5, P = 229 Output : 120 Input : A[] = {1, 2, 3, 4, 5, 6}, L = 2, R = 5, P = 113 Output : 7 Brute ForceFor each of the queries, traverse each element in the range [L, R] and calculate the product under modulo P. This will answer each query in O(N). C++ // Product in range// Queries in O(N)#include <bits/stdc++.h>using namespace std; // Function to calculate// Product in the given range.int calculateProduct(int A[], int L, int R, int P){ // As our array is 0 based // as and L and R are given // as 1 based index. L = L - 1; R = R - 1; int ans = 1; for (int i = L; i <= R; i++) { ans = ans * A[i]; ans = ans % P; } return ans;} // Driver codeint main(){ int A[] = { 1, 2, 3, 4, 5, 6 }; int P = 229; int L = 2, R = 5; cout << calculateProduct(A, L, R, P) << endl; L = 1, R = 3; cout << calculateProduct(A, L, R, P) << endl; return 0;} Output : 120 6 Efficient Using Modular Multiplicative Inverse:As P is prime, we can use Modular Multiplicative Inverse. Using dynamic programming, we can calculate a pre-product array under modulo P such that the value at index i contains the product in the range [0, i]. Similarly, we can calculate the pre-inverse product under modulo P. Now each query can be answered in O(1). The inverse product array contains the inverse product in the range [0, i] at index i. So, for the query [L, R], the answer will be Product[R]*InverseProduct[L-1]Note: We can not calculate the answer as Product[R]/Product[L-1] because the product is calculated under modulo P. If we do not calculate the product under modulo P there is always a possibility of overflow. C++ // Product in range Queries in O(1)#include <bits/stdc++.h>using namespace std;#define MAX 100 int pre_product[MAX];int inverse_product[MAX]; // Returns modulo inverse of a// with respect to m using// extended Euclid Algorithm// Assumption: a and m are// coprimes, i.e., gcd(a, m) = 1int modInverse(int a, int m){ int m0 = m, t, q; int x0 = 0, x1 = 1; if (m == 1) return 0; while (a > 1) { // q is quotient q = a / m; t = m; // m is remainder now, // process same as // Euclid's algo m = a % m, a = t; t = x0; x0 = x1 - q * x0; x1 = t; } // Make x1 positive if (x1 < 0) x1 += m0; return x1;} // calculating pre_product// arrayvoid calculate_Pre_Product(int A[], int N, int P){ pre_product[0] = A[0]; for (int i = 1; i < N; i++) { pre_product[i] = pre_product[i - 1] * A[i]; pre_product[i] = pre_product[i] % P; }} // Calculating inverse_product// array.void calculate_inverse_product(int A[], int N, int P){ inverse_product[0] = modInverse(pre_product[0], P); for (int i = 1; i < N; i++) inverse_product[i] = modInverse(pre_product[i], P);} // Function to calculate// Product in the given range.int calculateProduct(int A[], int L, int R, int P){ // As our array is 0 based as // and L and R are given as 1 // based index. L = L - 1; R = R - 1; int ans; if (L == 0) ans = pre_product[R]; else ans = pre_product[R] * inverse_product[L - 1]; return ans;} // Driver Codeint main(){ // Array int A[] = { 1, 2, 3, 4, 5, 6 }; int N = sizeof(A) / sizeof(A[0]); // Prime P int P = 113; // Calculating PreProduct // and InverseProduct calculate_Pre_Product(A, N, P); calculate_inverse_product(A, N, P); // Range [L, R] in 1 base index int L = 2, R = 5; cout << calculateProduct(A, L, R, P) << endl; L = 1, R = 3; cout << calculateProduct(A, L, R, P) << endl; return 0;} Output : 7 6 Please refer complete article on Products of ranges in an array for more details! simmytarika5 array-range-queries Modular Arithmetic Arrays C++ C++ Programs Arrays Modular Arithmetic CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Reversal algorithm for array rotation Window Sliding Technique Next Greater Element Find duplicates in O(n) time and O(1) extra space | Set 1 Vector in C++ STL Inheritance in C++ Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL) std::sort() in C++ STL
[ { "code": null, "e": 26041, "s": 26013, "text": "\n20 Jan, 2022" }, { "code": null, "e": 26156, "s": 26041, "text": "Given an array A[] of size N. Solve Q queries. Find the product in the range [L, R] under modulo P ( P is Prime). " }, { "code": null, "e": 26168, "s": 26156, "text": "Examples: " }, { "code": null, "e": 26325, "s": 26168, "text": "Input : A[] = {1, 2, 3, 4, 5, 6} \n L = 2, R = 5, P = 229\nOutput : 120\n\nInput : A[] = {1, 2, 3, 4, 5, 6},\n L = 2, R = 5, P = 113\nOutput : 7 " }, { "code": null, "e": 26484, "s": 26325, "text": "Brute ForceFor each of the queries, traverse each element in the range [L, R] and calculate the product under modulo P. This will answer each query in O(N). " }, { "code": null, "e": 26488, "s": 26484, "text": "C++" }, { "code": "// Product in range// Queries in O(N)#include <bits/stdc++.h>using namespace std; // Function to calculate// Product in the given range.int calculateProduct(int A[], int L, int R, int P){ // As our array is 0 based // as and L and R are given // as 1 based index. L = L - 1; R = R - 1; int ans = 1; for (int i = L; i <= R; i++) { ans = ans * A[i]; ans = ans % P; } return ans;} // Driver codeint main(){ int A[] = { 1, 2, 3, 4, 5, 6 }; int P = 229; int L = 2, R = 5; cout << calculateProduct(A, L, R, P) << endl; L = 1, R = 3; cout << calculateProduct(A, L, R, P) << endl; return 0;}", "e": 27177, "s": 26488, "text": null }, { "code": null, "e": 27188, "s": 27177, "text": "Output : " }, { "code": null, "e": 27194, "s": 27188, "text": "120\n6" }, { "code": null, "e": 27933, "s": 27196, "text": "Efficient Using Modular Multiplicative Inverse:As P is prime, we can use Modular Multiplicative Inverse. Using dynamic programming, we can calculate a pre-product array under modulo P such that the value at index i contains the product in the range [0, i]. Similarly, we can calculate the pre-inverse product under modulo P. Now each query can be answered in O(1). The inverse product array contains the inverse product in the range [0, i] at index i. So, for the query [L, R], the answer will be Product[R]*InverseProduct[L-1]Note: We can not calculate the answer as Product[R]/Product[L-1] because the product is calculated under modulo P. If we do not calculate the product under modulo P there is always a possibility of overflow. " }, { "code": null, "e": 27937, "s": 27933, "text": "C++" }, { "code": "// Product in range Queries in O(1)#include <bits/stdc++.h>using namespace std;#define MAX 100 int pre_product[MAX];int inverse_product[MAX]; // Returns modulo inverse of a// with respect to m using// extended Euclid Algorithm// Assumption: a and m are// coprimes, i.e., gcd(a, m) = 1int modInverse(int a, int m){ int m0 = m, t, q; int x0 = 0, x1 = 1; if (m == 1) return 0; while (a > 1) { // q is quotient q = a / m; t = m; // m is remainder now, // process same as // Euclid's algo m = a % m, a = t; t = x0; x0 = x1 - q * x0; x1 = t; } // Make x1 positive if (x1 < 0) x1 += m0; return x1;} // calculating pre_product// arrayvoid calculate_Pre_Product(int A[], int N, int P){ pre_product[0] = A[0]; for (int i = 1; i < N; i++) { pre_product[i] = pre_product[i - 1] * A[i]; pre_product[i] = pre_product[i] % P; }} // Calculating inverse_product// array.void calculate_inverse_product(int A[], int N, int P){ inverse_product[0] = modInverse(pre_product[0], P); for (int i = 1; i < N; i++) inverse_product[i] = modInverse(pre_product[i], P);} // Function to calculate// Product in the given range.int calculateProduct(int A[], int L, int R, int P){ // As our array is 0 based as // and L and R are given as 1 // based index. L = L - 1; R = R - 1; int ans; if (L == 0) ans = pre_product[R]; else ans = pre_product[R] * inverse_product[L - 1]; return ans;} // Driver Codeint main(){ // Array int A[] = { 1, 2, 3, 4, 5, 6 }; int N = sizeof(A) / sizeof(A[0]); // Prime P int P = 113; // Calculating PreProduct // and InverseProduct calculate_Pre_Product(A, N, P); calculate_inverse_product(A, N, P); // Range [L, R] in 1 base index int L = 2, R = 5; cout << calculateProduct(A, L, R, P) << endl; L = 1, R = 3; cout << calculateProduct(A, L, R, P) << endl; return 0;}", "e": 30097, "s": 27937, "text": null }, { "code": null, "e": 30108, "s": 30097, "text": "Output : " }, { "code": null, "e": 30112, "s": 30108, "text": "7\n6" }, { "code": null, "e": 30195, "s": 30112, "text": "Please refer complete article on Products of ranges in an array for more details! " }, { "code": null, "e": 30208, "s": 30195, "text": "simmytarika5" }, { "code": null, "e": 30228, "s": 30208, "text": "array-range-queries" }, { "code": null, "e": 30247, "s": 30228, "text": "Modular Arithmetic" }, { "code": null, "e": 30254, "s": 30247, "text": "Arrays" }, { "code": null, "e": 30258, "s": 30254, "text": "C++" }, { "code": null, "e": 30271, "s": 30258, "text": "C++ Programs" }, { "code": null, "e": 30278, "s": 30271, "text": "Arrays" }, { "code": null, "e": 30297, "s": 30278, "text": "Modular Arithmetic" }, { "code": null, "e": 30301, "s": 30297, "text": "CPP" }, { "code": null, "e": 30399, "s": 30301, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30430, "s": 30399, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 30468, "s": 30430, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 30493, "s": 30468, "text": "Window Sliding Technique" }, { "code": null, "e": 30514, "s": 30493, "text": "Next Greater Element" }, { "code": null, "e": 30572, "s": 30514, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 30590, "s": 30572, "text": "Vector in C++ STL" }, { "code": null, "e": 30609, "s": 30590, "text": "Inheritance in C++" }, { "code": null, "e": 30655, "s": 30609, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 30698, "s": 30655, "text": "Map in C++ Standard Template Library (STL)" } ]
How to apply manually created x-axis labels in a histogram created by hist function in R?
When we generate a histogram in R using hist function, the x-axis labels are automatically generated but we might want to change them to values defined by researchers or by any other authority. Therefore, firstly we need to create the histogram by ignoring the labels and then axis function can be used for new values. Consider the below vector x and create a histogram of x by ignoring x-axis labels − set.seed(1999) x<-rnorm(5000,9,1) hist(x,xaxt='n') Now adding new values for x-axis labels − axis(side=1,at=seq(6,12,1),labels=seq(6,12,1))
[ { "code": null, "e": 1381, "s": 1062, "text": "When we generate a histogram in R using hist function, the x-axis labels are automatically generated but we might want to change them to values defined by researchers or by any other authority. Therefore, firstly we need to create the histogram by ignoring the labels and then axis function can be used for new values." }, { "code": null, "e": 1465, "s": 1381, "text": "Consider the below vector x and create a histogram of x by ignoring x-axis labels −" }, { "code": null, "e": 1516, "s": 1465, "text": "set.seed(1999)\nx<-rnorm(5000,9,1)\nhist(x,xaxt='n')" }, { "code": null, "e": 1558, "s": 1516, "text": "Now adding new values for x-axis labels −" }, { "code": null, "e": 1605, "s": 1558, "text": "axis(side=1,at=seq(6,12,1),labels=seq(6,12,1))" } ]
Java Program For Finding Intersection Point Of Two Linked Lists
11 Dec, 2021 There are two singly linked lists in a system. By some programming error, the end node of one of the linked lists got linked to the second list, forming an inverted Y-shaped list. Write a program to get the point where two linked lists merge. Above diagram shows an example with two linked lists having 15 as intersection points. Method 1(Simply use two loops): Use 2 nested for loops. The outer loop will be for each node of the 1st list and the inner loop will be for the 2nd list. In the inner loop, check if any of the nodes of the 2nd list is the same as the current node of the first linked list. The time complexity of this method will be O(M * N) where m and n are the numbers of nodes in two lists. Method 2 (Mark Visited Nodes): This solution requires modifications to basic linked list data structure. Have a visited flag with each node. Traverse the first linked list and keep marking visited nodes. Now traverse the second linked list, If you see a visited node again then there is an intersection point, return the intersecting node. This solution works in O(m+n) but requires additional information with each node. A variation of this solution that doesn’t require modification to the basic data structure can be implemented using a hash. Traverse the first linked list and store the addresses of visited nodes in a hash. Now traverse the second linked list and if you see an address that already exists in the hash then return the intersecting node. Method 3(Using difference of node counts): Get count of the nodes in the first list, let count be c1. Get count of the nodes in the second list, let count be c2. Get the difference of counts d = abs(c1 – c2) Now traverse the bigger list from the first node till d nodes so that from here onwards both the lists have equal no of nodes Then we can traverse both the lists in parallel till we come across a common node. (Note that getting a common node is done by comparing the address of the nodes) Below image is a dry run of the above approach: Below is the implementation of the above approach : Java // Java program to get intersection point// of two linked listclass LinkedList { static Node head1, head2; static class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Function to get the intersection point of two linked lists head1 and head2 */ int getNode() { int c1 = getCount(head1); int c2 = getCount(head2); int d; if (c1 > c2) { d = c1 - c2; return _getIntesectionNode(d, head1, head2); } else { d = c2 - c1; return _getIntesectionNode(d, head2, head1); } } /* Function to get the intersection point of two linked lists head1 and head2 where head1 has d more nodes than head2 */ int _getIntesectionNode(int d, Node node1, Node node2) { int i; Node current1 = node1; Node current2 = node2; for (i = 0; i < d; i++) { if (current1 == null) { return -1; } current1 = current1.next; } while (current1 != null && current2 != null) { if (current1.data == current2.data) { return current1.data; } current1 = current2; current2 = current2.next; } return -1; } /* Takes head pointer of the linked list and returns the count of nodes in the list */ int getCount(Node node) { Node current = node; int count = 0; while (current != null) { count++; current = current.next; } return count; } // Driver code public static void main(String[] args) { LinkedList list = new LinkedList(); // Creating first linked list list.head1 = new Node(3); list.head1.next = new Node(6); list.head1.next.next = new Node(9); list.head1.next.next.next = new Node(15); list.head1.next.next.next.next = new Node(30); // Creating second linked list list.head2 = new Node(10); list.head2.next = new Node(15); list.head2.next.next = new Node(30); System.out.println("The node of intersection is " + list.getNode()); }}// This code is contributed by Mayank Jaiswal Output: The node of intersection is 15 Time Complexity: O(m+n) Auxiliary Space: O(1) Method 4(Make circle in first list): Thanks to Saravanan Man for providing below solution. 1. Traverse the first linked list(count the elements) and make a circular linked list. (Remember the last node so that we can break the circle later on). 2. Now view the problem as finding the loop in the second linked list. So the problem is solved. 3. Since we already know the length of the loop(size of the first linked list) we can traverse those many numbers of nodes in the second list, and then start another pointer from the beginning of the second list. we have to traverse until they are equal, and that is the required intersection point. 4. remove the circle from the linked list. Time Complexity: O(m+n) Auxiliary Space: O(1) Method 5 (Reverse the first list and make equations): Thanks to Saravanan Mani for providing this method. 1) Let X be the length of the first linked list until the intersection point. Let Y be the length of the second linked list until the intersection point. Let Z be the length of the linked list from the intersection point to End of the linked list including the intersection node. We Have X + Z = C1; Y + Z = C2; 2) Reverse first linked list. 3) Traverse Second linked list. Let C3 be the length of second list - 1. Now we have X + Y = C3 We have 3 linear equations. By solving them, we get X = (C1 + C3 – C2)/2; Y = (C2 + C3 – C1)/2; Z = (C1 + C2 – C3)/2; WE GOT THE INTERSECTION POINT. 4) Reverse the first linked list. Advantage: No Comparison of pointers. Disadvantage: Modifying linked list(Reversing list). Time complexity: O(m+n) Auxiliary Space: O(1) Method 6 (Traverse both lists and compare addresses of last nodes): This method is only to detect if there is an intersection point or not. (Thanks to NeoTheSaviour for suggesting this) 1) Traverse list 1, store the last node address 2) Traverse list 2, store the last node address. 3) If nodes stored in 1 and 2 are same then they are intersecting. The time complexity of this method is O(m+n) and used Auxiliary space is O(1) Method 7 (Use Hashing): Basically, we need to find a common node of two linked lists. So we hash all nodes of the first list and then check the second list. 1) Create an empty hash set. 2) Traverse the first linked list and insert all nodes’ addresses in the hash set. 3) Traverse the second list. For every node check if it is present in the hash set. If we find a node in the hash set, return the node. Java // Java program to get intersection point // of two linked listimport java.util.*;class Node { int data; Node next; Node(int d) { data = d; next = null; }}class LinkedListIntersect { public static void main(String[] args) { // list 1 Node n1 = new Node(1); n1.next = new Node(2); n1.next.next = new Node(3); n1.next.next.next = new Node(4); n1.next.next.next.next = new Node(5); n1.next.next.next.next.next = new Node(6); n1.next.next.next.next.next.next = new Node(7); // list 2 Node n2 = new Node(10); n2.next = new Node(9); n2.next.next = new Node(8); n2.next.next.next = n1.next.next.next; Print(n1); Print(n2); System.out.println(MegeNode(n1, n2).data); } // Function to print the list public static void Print(Node n) { Node cur = n; while (cur != null) { System.out.print(cur.data + " "); cur = cur.next; } System.out.println(); } // Function to find the intersection // of two node public static Node MegeNode(Node n1, Node n2) { // define hashset HashSet<Node> hs = new HashSet<Node>(); while (n1 != null) { hs.add(n1); n1 = n1.next; } while (n2 != null) { if (hs.contains(n2)) { return n2; } n2 = n2.next; } return null; }} Output: 1 2 3 4 5 6 7 10 9 8 4 5 6 7 4 This method required O(n) additional space and not very efficient if one list is large. Please refer complete article on Write a function to get the intersection point of two Linked Lists for more details! Accolite Amazon D-E-Shaw FactSet Goldman Sachs Linked Lists MakeMyTrip MAQ Software Microsoft Qualcomm Snapdeal Visa Zopper Java Java Programs Linked List Accolite Amazon Microsoft Snapdeal D-E-Shaw FactSet MakeMyTrip Visa Goldman Sachs MAQ Software Qualcomm Zopper Linked List Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Dec, 2021" }, { "code": null, "e": 272, "s": 28, "text": "There are two singly linked lists in a system. By some programming error, the end node of one of the linked lists got linked to the second list, forming an inverted Y-shaped list. Write a program to get the point where two linked lists merge. " }, { "code": null, "e": 359, "s": 272, "text": "Above diagram shows an example with two linked lists having 15 as intersection points." }, { "code": null, "e": 737, "s": 359, "text": "Method 1(Simply use two loops): Use 2 nested for loops. The outer loop will be for each node of the 1st list and the inner loop will be for the 2nd list. In the inner loop, check if any of the nodes of the 2nd list is the same as the current node of the first linked list. The time complexity of this method will be O(M * N) where m and n are the numbers of nodes in two lists." }, { "code": null, "e": 1495, "s": 737, "text": "Method 2 (Mark Visited Nodes): This solution requires modifications to basic linked list data structure. Have a visited flag with each node. Traverse the first linked list and keep marking visited nodes. Now traverse the second linked list, If you see a visited node again then there is an intersection point, return the intersecting node. This solution works in O(m+n) but requires additional information with each node. A variation of this solution that doesn’t require modification to the basic data structure can be implemented using a hash. Traverse the first linked list and store the addresses of visited nodes in a hash. Now traverse the second linked list and if you see an address that already exists in the hash then return the intersecting node." }, { "code": null, "e": 1539, "s": 1495, "text": "Method 3(Using difference of node counts): " }, { "code": null, "e": 1598, "s": 1539, "text": "Get count of the nodes in the first list, let count be c1." }, { "code": null, "e": 1658, "s": 1598, "text": "Get count of the nodes in the second list, let count be c2." }, { "code": null, "e": 1704, "s": 1658, "text": "Get the difference of counts d = abs(c1 – c2)" }, { "code": null, "e": 1830, "s": 1704, "text": "Now traverse the bigger list from the first node till d nodes so that from here onwards both the lists have equal no of nodes" }, { "code": null, "e": 1993, "s": 1830, "text": "Then we can traverse both the lists in parallel till we come across a common node. (Note that getting a common node is done by comparing the address of the nodes)" }, { "code": null, "e": 2041, "s": 1993, "text": "Below image is a dry run of the above approach:" }, { "code": null, "e": 2093, "s": 2041, "text": "Below is the implementation of the above approach :" }, { "code": null, "e": 2098, "s": 2093, "text": "Java" }, { "code": "// Java program to get intersection point// of two linked listclass LinkedList { static Node head1, head2; static class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Function to get the intersection point of two linked lists head1 and head2 */ int getNode() { int c1 = getCount(head1); int c2 = getCount(head2); int d; if (c1 > c2) { d = c1 - c2; return _getIntesectionNode(d, head1, head2); } else { d = c2 - c1; return _getIntesectionNode(d, head2, head1); } } /* Function to get the intersection point of two linked lists head1 and head2 where head1 has d more nodes than head2 */ int _getIntesectionNode(int d, Node node1, Node node2) { int i; Node current1 = node1; Node current2 = node2; for (i = 0; i < d; i++) { if (current1 == null) { return -1; } current1 = current1.next; } while (current1 != null && current2 != null) { if (current1.data == current2.data) { return current1.data; } current1 = current2; current2 = current2.next; } return -1; } /* Takes head pointer of the linked list and returns the count of nodes in the list */ int getCount(Node node) { Node current = node; int count = 0; while (current != null) { count++; current = current.next; } return count; } // Driver code public static void main(String[] args) { LinkedList list = new LinkedList(); // Creating first linked list list.head1 = new Node(3); list.head1.next = new Node(6); list.head1.next.next = new Node(9); list.head1.next.next.next = new Node(15); list.head1.next.next.next.next = new Node(30); // Creating second linked list list.head2 = new Node(10); list.head2.next = new Node(15); list.head2.next.next = new Node(30); System.out.println(\"The node of intersection is \" + list.getNode()); }}// This code is contributed by Mayank Jaiswal", "e": 4642, "s": 2098, "text": null }, { "code": null, "e": 4650, "s": 4642, "text": "Output:" }, { "code": null, "e": 4681, "s": 4650, "text": "The node of intersection is 15" }, { "code": null, "e": 4727, "s": 4681, "text": "Time Complexity: O(m+n) Auxiliary Space: O(1)" }, { "code": null, "e": 5413, "s": 4727, "text": "Method 4(Make circle in first list): Thanks to Saravanan Man for providing below solution. 1. Traverse the first linked list(count the elements) and make a circular linked list. (Remember the last node so that we can break the circle later on). 2. Now view the problem as finding the loop in the second linked list. So the problem is solved. 3. Since we already know the length of the loop(size of the first linked list) we can traverse those many numbers of nodes in the second list, and then start another pointer from the beginning of the second list. we have to traverse until they are equal, and that is the required intersection point. 4. remove the circle from the linked list. " }, { "code": null, "e": 5459, "s": 5413, "text": "Time Complexity: O(m+n) Auxiliary Space: O(1)" }, { "code": null, "e": 5567, "s": 5459, "text": "Method 5 (Reverse the first list and make equations): Thanks to Saravanan Mani for providing this method. " }, { "code": null, "e": 6269, "s": 5567, "text": "1) Let X be the length of the first linked list until the intersection point.\n Let Y be the length of the second linked list until the intersection point.\n Let Z be the length of the linked list from the intersection point to End of\n the linked list including the intersection node.\n We Have\n X + Z = C1;\n Y + Z = C2;\n2) Reverse first linked list.\n3) Traverse Second linked list. Let C3 be the length of second list - 1. \n Now we have\n X + Y = C3\n We have 3 linear equations. By solving them, we get\n X = (C1 + C3 – C2)/2;\n Y = (C2 + C3 – C1)/2;\n Z = (C1 + C2 – C3)/2;\n WE GOT THE INTERSECTION POINT.\n4) Reverse the first linked list." }, { "code": null, "e": 6406, "s": 6269, "text": "Advantage: No Comparison of pointers. Disadvantage: Modifying linked list(Reversing list). Time complexity: O(m+n) Auxiliary Space: O(1)" }, { "code": null, "e": 6594, "s": 6406, "text": "Method 6 (Traverse both lists and compare addresses of last nodes): This method is only to detect if there is an intersection point or not. (Thanks to NeoTheSaviour for suggesting this) " }, { "code": null, "e": 6758, "s": 6594, "text": "1) Traverse list 1, store the last node address\n2) Traverse list 2, store the last node address.\n3) If nodes stored in 1 and 2 are same then they are intersecting." }, { "code": null, "e": 6836, "s": 6758, "text": "The time complexity of this method is O(m+n) and used Auxiliary space is O(1)" }, { "code": null, "e": 7241, "s": 6836, "text": "Method 7 (Use Hashing): Basically, we need to find a common node of two linked lists. So we hash all nodes of the first list and then check the second list. 1) Create an empty hash set. 2) Traverse the first linked list and insert all nodes’ addresses in the hash set. 3) Traverse the second list. For every node check if it is present in the hash set. If we find a node in the hash set, return the node." }, { "code": null, "e": 7246, "s": 7241, "text": "Java" }, { "code": "// Java program to get intersection point // of two linked listimport java.util.*;class Node { int data; Node next; Node(int d) { data = d; next = null; }}class LinkedListIntersect { public static void main(String[] args) { // list 1 Node n1 = new Node(1); n1.next = new Node(2); n1.next.next = new Node(3); n1.next.next.next = new Node(4); n1.next.next.next.next = new Node(5); n1.next.next.next.next.next = new Node(6); n1.next.next.next.next.next.next = new Node(7); // list 2 Node n2 = new Node(10); n2.next = new Node(9); n2.next.next = new Node(8); n2.next.next.next = n1.next.next.next; Print(n1); Print(n2); System.out.println(MegeNode(n1, n2).data); } // Function to print the list public static void Print(Node n) { Node cur = n; while (cur != null) { System.out.print(cur.data + \" \"); cur = cur.next; } System.out.println(); } // Function to find the intersection // of two node public static Node MegeNode(Node n1, Node n2) { // define hashset HashSet<Node> hs = new HashSet<Node>(); while (n1 != null) { hs.add(n1); n1 = n1.next; } while (n2 != null) { if (hs.contains(n2)) { return n2; } n2 = n2.next; } return null; }}", "e": 8769, "s": 7246, "text": null }, { "code": null, "e": 8777, "s": 8769, "text": "Output:" }, { "code": null, "e": 8824, "s": 8777, "text": "1 2 3 4 5 6 7 \n10 9 8 4 5 6 7 \n4" }, { "code": null, "e": 8913, "s": 8824, "text": "This method required O(n) additional space and not very efficient if one list is large. " }, { "code": null, "e": 9031, "s": 8913, "text": "Please refer complete article on Write a function to get the intersection point of two Linked Lists for more details!" }, { "code": null, "e": 9040, "s": 9031, "text": "Accolite" }, { "code": null, "e": 9047, "s": 9040, "text": "Amazon" }, { "code": null, "e": 9056, "s": 9047, "text": "D-E-Shaw" }, { "code": null, "e": 9064, "s": 9056, "text": "FactSet" }, { "code": null, "e": 9078, "s": 9064, "text": "Goldman Sachs" }, { "code": null, "e": 9091, "s": 9078, "text": "Linked Lists" }, { "code": null, "e": 9102, "s": 9091, "text": "MakeMyTrip" }, { "code": null, "e": 9115, "s": 9102, "text": "MAQ Software" }, { "code": null, "e": 9125, "s": 9115, "text": "Microsoft" }, { "code": null, "e": 9134, "s": 9125, "text": "Qualcomm" }, { "code": null, "e": 9143, "s": 9134, "text": "Snapdeal" }, { "code": null, "e": 9148, "s": 9143, "text": "Visa" }, { "code": null, "e": 9155, "s": 9148, "text": "Zopper" }, { "code": null, "e": 9160, "s": 9155, "text": "Java" }, { "code": null, "e": 9174, "s": 9160, "text": "Java Programs" }, { "code": null, "e": 9186, "s": 9174, "text": "Linked List" }, { "code": null, "e": 9195, "s": 9186, "text": "Accolite" }, { "code": null, "e": 9202, "s": 9195, "text": "Amazon" }, { "code": null, "e": 9212, "s": 9202, "text": "Microsoft" }, { "code": null, "e": 9221, "s": 9212, "text": "Snapdeal" }, { "code": null, "e": 9230, "s": 9221, "text": "D-E-Shaw" }, { "code": null, "e": 9238, "s": 9230, "text": "FactSet" }, { "code": null, "e": 9249, "s": 9238, "text": "MakeMyTrip" }, { "code": null, "e": 9254, "s": 9249, "text": "Visa" }, { "code": null, "e": 9268, "s": 9254, "text": "Goldman Sachs" }, { "code": null, "e": 9281, "s": 9268, "text": "MAQ Software" }, { "code": null, "e": 9290, "s": 9281, "text": "Qualcomm" }, { "code": null, "e": 9297, "s": 9290, "text": "Zopper" }, { "code": null, "e": 9309, "s": 9297, "text": "Linked List" }, { "code": null, "e": 9314, "s": 9309, "text": "Java" } ]
How to use unordered_map efficiently in C++
22 May, 2021 Pre-requisite: unordered_set, unordered_map C++ provides std::unordered_set and std::unordered_map to be used as a hash set and hash map respectively. They perform insertion/deletion/access in constant average time. However, the worst-case complexity is O(n2).The reason is that the unordered_map store’s key-value pair by taking the modulo of input value by a prime number and then stores it in a hash table.When the input data is big and input values are multiples of this prime number a lot of collisions take place and may cause the complexity of O(n2).Depending on the compiler the prime number maybe 107897 or 126271. However, the worst-case complexity is O(n2). The reason is that the unordered_map store’s key-value pair by taking the modulo of input value by a prime number and then stores it in a hash table. When the input data is big and input values are multiples of this prime number a lot of collisions take place and may cause the complexity of O(n2). Depending on the compiler the prime number maybe 107897 or 126271. Example 1: If we insert multiples of the above two prime numbers and compute execution time. One of the prime numbers takes a much longer time than the other. C++ // C++ program to determine worst case// time complexity of an unordered_map #include <bits/stdc++.h>using namespace std;using namespace std::chrono;int N = 55000;int prime1 = 107897;int prime2 = 126271; void insert(int prime){ // Starting the clock auto start = high_resolution_clock::now(); unordered_map<int, int> umap; // Inserting multiples of prime // number as key in the map for (int i = 1; i <= N; i++) umap[i * prime] = i; // Stopping the clock auto stop = high_resolution_clock::now(); // Typecasting the time to // milliseconds auto duration = duration_cast<milliseconds>( stop - start); // Time in seconds cout << "for " << prime << " : " << duration.count() / 1000.0 << " seconds " << endl;} // Driver codeint main(){ // Function call for prime 1 insert(prime1); // Function call for prime 2 insert(prime2);} for 107897 : 2.261 seconds for 126271 : 0.024 seconds Clearly, for one of the prime numbers, the time complexity is O(n2). The standard inbuilt hash function on which unordered_map works is similar to this: C++ struct hash { size_t operator()(uint64_t x) const { return x; }}; The above function can produce numerous collisions. The keys inserted in HashMap are not evenly distributed, and after inserting numerous prime multiples, further insertion causes the hash function to reallocate all previous keys to new slots hence making it slow. So, the idea is that we have to randomize the hash function.The idea is to use a method so that the keys in our hashmap are evenly distributed. This will prevent collisions to take place. For this, we use Fibonacci numbers. The golden ratio related to the Fibonacci sequence (Phi = 1.618) has a property that it can subdivide any range evenly without looping back to the starting position. We can create our own simple hash function. Below is the hash function: C++ struct modified_hash { static uint64_t splitmix64(uint64_t x) { // 0x9e3779b97f4a7c15, // 0xbf58476d1ce4e5b9, // 0x94d049bb133111eb are numbers // that are obtained by dividing // high powers of two with Phi // (1.6180..) In this way the // value of x is modified // to evenly distribute // keys in hash table x += 0x9e3779b97f4a7c15; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9; x = (x ^ (x >> 27)) * 0x94d049bb133111eb; return x ^ (x >> 31); } int operator()(uint64_t x) const { static const uint64_t random = steady_clock::now() .time_since_epoch() .count(); // The above line generates a // random number using // high precision clock return splitmix64( // It returns final hash value x + random); }}; Basically, the above hashing function generates random hash values to store keys. To know more about this please refer to this article Fibonacci hashing. Example 2: Using the above hashing function, the program runs very quickly. C++ // C++ program to determine worst case// time complexity of an unordered_map// using modified hash function #include <bits/stdc++.h>using namespace std;using namespace std::chrono; struct modified_hash { static uint64_t splitmix64(uint64_t x) { x += 0x9e3779b97f4a7c15; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9; x = (x ^ (x >> 27)) * 0x94d049bb133111eb; return x ^ (x >> 31); } int operator()(uint64_t x) const { static const uint64_t random = steady_clock::now() .time_since_epoch() .count(); return splitmix64(x + random); }}; int N = 55000;int prime1 = 107897;int prime2 = 126271; // Function to insert in the hashMapvoid insert(int prime){ auto start = high_resolution_clock::now(); // Third argument in initialisation // of unordered_map ensures that // the map uses the hash function unordered_map<int, int, modified_hash> umap; // Inserting multiples of prime // number as key in the map for (int i = 1; i <= N; i++) umap[i * prime] = i; auto stop = high_resolution_clock::now(); auto duration = duration_cast<milliseconds>( stop - start); cout << "for " << prime << " : " << duration.count() / 1000.0 << " seconds " << endl;} // Driver Codeint main(){ // Function call for prime 1 insert(prime1); // Function call for prime 2 insert(prime2);} for 107897 : 0.025 seconds for 126271 : 0.024 seconds Reserving space before hand By default, the capacity of unordered_map is 16 and a hash table is created for this. But every time, when threshold is reached, the capacity of the unordered_map is doubled and all the values are rehashed according to new hash table. So, we can reserve the capacity beforehand according to our input size by using .reserve() method. umap.reserve(1024); 1024 can be replaced by any int value according to input size. This prevents rehashing and dynamic allocation which makes program more efficient. Setting max_load_factor max_load_factor of unordered_map determines the probability of collision. Default value is set to 1. By setting it to a lower value like 0.25 can decrease the probability of collisions by great extent. umap.max_load_factor(0.25); Example : Using above two method can make umap faster : C++ #include <bits/stdc++.h>using namespace std;using namespace std::chrono;int N = 55000;int prime1 = 107897;int prime2 = 126271; void insert(int prime){ // Starting the clock auto start = high_resolution_clock::now(); unordered_map<int, int> umap; umap.reserve(1024); // RESERVING SPACE BEFOREHAND umap.max_load_factor(0.25); // DECREASING MAX_LOAD_FACTOR // Inserting multiples of prime // number as key in the map for (int i = 1; i <= N; i++) umap[i * prime] = i; // Stopping the clock auto stop = high_resolution_clock::now(); // Typecasting the time to // milliseconds auto duration = duration_cast<milliseconds>( stop - start); // Time in seconds cout << "for " << prime << " : " << duration.count() / 1000.0 << " seconds " << endl;} // Driver codeint main(){ // Function call for prime 1 insert(prime1); // Function call for prime 2 insert(prime2);} Output : for 107897 : 0.029 seconds for 126271 : 0.026 seconds himankgoel12 cpp-unordered_map C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n22 May, 2021" }, { "code": null, "e": 98, "s": 52, "text": "Pre-requisite: unordered_set, unordered_map " }, { "code": null, "e": 271, "s": 98, "text": "C++ provides std::unordered_set and std::unordered_map to be used as a hash set and hash map respectively. They perform insertion/deletion/access in constant average time. " }, { "code": null, "e": 679, "s": 271, "text": "However, the worst-case complexity is O(n2).The reason is that the unordered_map store’s key-value pair by taking the modulo of input value by a prime number and then stores it in a hash table.When the input data is big and input values are multiples of this prime number a lot of collisions take place and may cause the complexity of O(n2).Depending on the compiler the prime number maybe 107897 or 126271." }, { "code": null, "e": 724, "s": 679, "text": "However, the worst-case complexity is O(n2)." }, { "code": null, "e": 874, "s": 724, "text": "The reason is that the unordered_map store’s key-value pair by taking the modulo of input value by a prime number and then stores it in a hash table." }, { "code": null, "e": 1023, "s": 874, "text": "When the input data is big and input values are multiples of this prime number a lot of collisions take place and may cause the complexity of O(n2)." }, { "code": null, "e": 1090, "s": 1023, "text": "Depending on the compiler the prime number maybe 107897 or 126271." }, { "code": null, "e": 1249, "s": 1090, "text": "Example 1: If we insert multiples of the above two prime numbers and compute execution time. One of the prime numbers takes a much longer time than the other." }, { "code": null, "e": 1253, "s": 1249, "text": "C++" }, { "code": "// C++ program to determine worst case// time complexity of an unordered_map #include <bits/stdc++.h>using namespace std;using namespace std::chrono;int N = 55000;int prime1 = 107897;int prime2 = 126271; void insert(int prime){ // Starting the clock auto start = high_resolution_clock::now(); unordered_map<int, int> umap; // Inserting multiples of prime // number as key in the map for (int i = 1; i <= N; i++) umap[i * prime] = i; // Stopping the clock auto stop = high_resolution_clock::now(); // Typecasting the time to // milliseconds auto duration = duration_cast<milliseconds>( stop - start); // Time in seconds cout << \"for \" << prime << \" : \" << duration.count() / 1000.0 << \" seconds \" << endl;} // Driver codeint main(){ // Function call for prime 1 insert(prime1); // Function call for prime 2 insert(prime2);}", "e": 2197, "s": 1253, "text": null }, { "code": null, "e": 2255, "s": 2200, "text": "for 107897 : 2.261 seconds \nfor 126271 : 0.024 seconds" }, { "code": null, "e": 2328, "s": 2259, "text": "Clearly, for one of the prime numbers, the time complexity is O(n2)." }, { "code": null, "e": 2414, "s": 2330, "text": "The standard inbuilt hash function on which unordered_map works is similar to this:" }, { "code": null, "e": 2420, "s": 2416, "text": "C++" }, { "code": "struct hash { size_t operator()(uint64_t x) const { return x; }};", "e": 2496, "s": 2420, "text": null }, { "code": null, "e": 3151, "s": 2496, "text": "The above function can produce numerous collisions. The keys inserted in HashMap are not evenly distributed, and after inserting numerous prime multiples, further insertion causes the hash function to reallocate all previous keys to new slots hence making it slow. So, the idea is that we have to randomize the hash function.The idea is to use a method so that the keys in our hashmap are evenly distributed. This will prevent collisions to take place. For this, we use Fibonacci numbers. The golden ratio related to the Fibonacci sequence (Phi = 1.618) has a property that it can subdivide any range evenly without looping back to the starting position." }, { "code": null, "e": 3223, "s": 3151, "text": "We can create our own simple hash function. Below is the hash function:" }, { "code": null, "e": 3227, "s": 3223, "text": "C++" }, { "code": "struct modified_hash { static uint64_t splitmix64(uint64_t x) { // 0x9e3779b97f4a7c15, // 0xbf58476d1ce4e5b9, // 0x94d049bb133111eb are numbers // that are obtained by dividing // high powers of two with Phi // (1.6180..) In this way the // value of x is modified // to evenly distribute // keys in hash table x += 0x9e3779b97f4a7c15; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9; x = (x ^ (x >> 27)) * 0x94d049bb133111eb; return x ^ (x >> 31); } int operator()(uint64_t x) const { static const uint64_t random = steady_clock::now() .time_since_epoch() .count(); // The above line generates a // random number using // high precision clock return splitmix64( // It returns final hash value x + random); }};", "e": 4145, "s": 3227, "text": null }, { "code": null, "e": 4299, "s": 4145, "text": "Basically, the above hashing function generates random hash values to store keys. To know more about this please refer to this article Fibonacci hashing." }, { "code": null, "e": 4375, "s": 4299, "text": "Example 2: Using the above hashing function, the program runs very quickly." }, { "code": null, "e": 4379, "s": 4375, "text": "C++" }, { "code": "// C++ program to determine worst case// time complexity of an unordered_map// using modified hash function #include <bits/stdc++.h>using namespace std;using namespace std::chrono; struct modified_hash { static uint64_t splitmix64(uint64_t x) { x += 0x9e3779b97f4a7c15; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9; x = (x ^ (x >> 27)) * 0x94d049bb133111eb; return x ^ (x >> 31); } int operator()(uint64_t x) const { static const uint64_t random = steady_clock::now() .time_since_epoch() .count(); return splitmix64(x + random); }}; int N = 55000;int prime1 = 107897;int prime2 = 126271; // Function to insert in the hashMapvoid insert(int prime){ auto start = high_resolution_clock::now(); // Third argument in initialisation // of unordered_map ensures that // the map uses the hash function unordered_map<int, int, modified_hash> umap; // Inserting multiples of prime // number as key in the map for (int i = 1; i <= N; i++) umap[i * prime] = i; auto stop = high_resolution_clock::now(); auto duration = duration_cast<milliseconds>( stop - start); cout << \"for \" << prime << \" : \" << duration.count() / 1000.0 << \" seconds \" << endl;} // Driver Codeint main(){ // Function call for prime 1 insert(prime1); // Function call for prime 2 insert(prime2);}", "e": 5873, "s": 4379, "text": null }, { "code": null, "e": 5931, "s": 5876, "text": "for 107897 : 0.025 seconds \nfor 126271 : 0.024 seconds" }, { "code": null, "e": 5963, "s": 5933, "text": "Reserving space before hand " }, { "code": null, "e": 6198, "s": 5963, "text": "By default, the capacity of unordered_map is 16 and a hash table is created for this. But every time, when threshold is reached, the capacity of the unordered_map is doubled and all the values are rehashed according to new hash table." }, { "code": null, "e": 6297, "s": 6198, "text": "So, we can reserve the capacity beforehand according to our input size by using .reserve() method." }, { "code": null, "e": 6317, "s": 6297, "text": "umap.reserve(1024);" }, { "code": null, "e": 6463, "s": 6317, "text": "1024 can be replaced by any int value according to input size. This prevents rehashing and dynamic allocation which makes program more efficient." }, { "code": null, "e": 6487, "s": 6463, "text": "Setting max_load_factor" }, { "code": null, "e": 6588, "s": 6487, "text": "max_load_factor of unordered_map determines the probability of collision. Default value is set to 1." }, { "code": null, "e": 6689, "s": 6588, "text": "By setting it to a lower value like 0.25 can decrease the probability of collisions by great extent." }, { "code": null, "e": 6717, "s": 6689, "text": "umap.max_load_factor(0.25);" }, { "code": null, "e": 6774, "s": 6717, "text": "Example : Using above two method can make umap faster : " }, { "code": null, "e": 6778, "s": 6774, "text": "C++" }, { "code": "#include <bits/stdc++.h>using namespace std;using namespace std::chrono;int N = 55000;int prime1 = 107897;int prime2 = 126271; void insert(int prime){ // Starting the clock auto start = high_resolution_clock::now(); unordered_map<int, int> umap; umap.reserve(1024); // RESERVING SPACE BEFOREHAND umap.max_load_factor(0.25); // DECREASING MAX_LOAD_FACTOR // Inserting multiples of prime // number as key in the map for (int i = 1; i <= N; i++) umap[i * prime] = i; // Stopping the clock auto stop = high_resolution_clock::now(); // Typecasting the time to // milliseconds auto duration = duration_cast<milliseconds>( stop - start); // Time in seconds cout << \"for \" << prime << \" : \" << duration.count() / 1000.0 << \" seconds \" << endl;} // Driver codeint main(){ // Function call for prime 1 insert(prime1); // Function call for prime 2 insert(prime2);}", "e": 7774, "s": 6778, "text": null }, { "code": null, "e": 7784, "s": 7774, "text": "Output : " }, { "code": null, "e": 7838, "s": 7784, "text": "for 107897 : 0.029 seconds\nfor 126271 : 0.026 seconds" }, { "code": null, "e": 7851, "s": 7838, "text": "himankgoel12" }, { "code": null, "e": 7869, "s": 7851, "text": "cpp-unordered_map" }, { "code": null, "e": 7873, "s": 7869, "text": "C++" }, { "code": null, "e": 7877, "s": 7873, "text": "CPP" } ]
Split the array and add the first part to the end
23 Jun, 2022 There is a given array and split it from a specified position, and move the first splitted part of the array and then add to the end of array Examples: Input : arr[] = {12, 10, 5, 6, 52, 36} k = 2 Output : arr[] = {5, 6, 52, 36, 12, 10} Explanation : here k is two so first two elements are splitted and they are added at the end of array Input : arr[] = {3, 1, 2} k = 1 Output : arr[] = {1, 2, 3} Explanation :here k is one so first one element are splitted and it is added at the end of array Simple Solution We will rotate the elements of the array one by one. C C++ Java Python3 C# PHP Javascript // CPP program to split array and move first// part to end.#include <stdio.h> void splitArr(int arr[], int n, int k){ for (int i = 0; i < k; i++) { // Rotate array by 1. int x = arr[0]; for (int j = 0; j < n - 1; ++j) arr[j] = arr[j + 1]; arr[n - 1] = x; }} // Driver codeint main(){ int arr[] = { 12, 10, 5, 6, 52, 36 }; int n = sizeof(arr) / sizeof(arr[0]); int position = 2; splitArr(arr, n, position); for (int i = 0; i < n; ++i) printf("%d ", arr[i]); return 0;} // CPP program to split array and move first// part to end.#include <iostream>using namespace std; void splitArr(int arr[], int n, int k){ for (int i = 0; i < k; i++) { // Rotate array by 1. int x = arr[0]; for (int j = 0; j < n - 1; ++j) arr[j] = arr[j + 1]; arr[n - 1] = x; }} // Driver codeint main(){ int arr[] = { 12, 10, 5, 6, 52, 36 }; int n = sizeof(arr) / sizeof(arr[0]); int position = 2; splitArr(arr, n, position); for (int i = 0; i < n; ++i) cout <<" "<< arr[i]; return 0;} // This code is contributed by shivanisinghss2110 // Java program to split array and move first// part to end. import java.util.*;import java.lang.*;class GFG { public static void splitArr(int arr[], int n, int k) { for (int i = 0; i < k; i++) { // Rotate array by 1. int x = arr[0]; for (int j = 0; j < n - 1; ++j) arr[j] = arr[j + 1]; arr[n - 1] = x; } } // Driver code public static void main(String[] args) { int arr[] = { 12, 10, 5, 6, 52, 36 }; int n = arr.length; int position = 2; splitArr(arr, n, position); for (int i = 0; i < n; ++i) System.out.print(arr[i] + " "); }} // Code Contributed by Mohit Gupta_OMG <(0_o)> # Python program to split array and move first# part to end. def splitArr(arr, n, k): for i in range(0, k): x = arr[0] for j in range(0, n-1): arr[j] = arr[j + 1] arr[n-1] = x # mainarr = [12, 10, 5, 6, 52, 36]n = len(arr)position = 2 splitArr(arr, n, position) for i in range(0, n): print(arr[i], end = ' ') # Code Contributed by Mohit Gupta_OMG <(0_o)> // C# program to split array// and move first part to end.using System; class GFG { // Function to split array and // move first part to end public static void splitArr(int[] arr, int n, int k) { for (int i = 0; i < k; i++) { // Rotate array by 1. int x = arr[0]; for (int j = 0; j < n - 1; ++j) arr[j] = arr[j + 1]; arr[n - 1] = x; } } // Driver code public static void Main() { int[] arr = {12, 10, 5, 6, 52, 36}; int n = arr.Length; int position = 2; splitArr(arr, n, position); for (int i = 0; i < n; ++i) Console.Write(arr[i] + " "); }} // This code is contributed by Shrikant13. <?php// PHP program to split array// and move first part to end. function splitArr(&$arr, $n, $k){ for ($i = 0; $i < $k; $i++) { // Rotate array by 1. $x = $arr[0]; for ($j = 0; $j < $n - 1; ++$j) $arr[$j] = $arr[$j + 1]; $arr[$n - 1] = $x; }} // Driver code$arr = array(12, 10, 5, 6, 52, 36);$n = sizeof($arr);$position = 2; splitArr($arr, n, $position); for ($i = 0; $i < $n; ++$i) echo $arr[$i]." "; // This code is contributed// by ChitraNayal?> <script> // JavaScript program to split// array and move first// part to end. function splitArr(arr, n, k){ for (let i = 0; i < k; i++) { // Rotate array by 1. let x = arr[0]; for (let j = 0; j < n - 1; ++j) arr[j] = arr[j + 1]; arr[n - 1] = x; }} // Driver code let arr = [ 12, 10, 5, 6, 52, 36 ];let n = arr.length;let position = 2;splitArr(arr, n, position);for (let i = 0; i < n; ++i) document.write(arr[i]+" "); </script> 5 6 52 36 12 10 Time complexity of the above solution is O(n). Space complexity: O(1) Another approach: Another approach is to make a temporary array with double the size and copy our array element into a new array twice .and then copy the element from the new array to our array by taking the rotation as starting index up to the length of our array.Below is the implementation of the above approach. C++ Java Python3 C# Javascript // CPP program to split array and move first// part to end.#include <bits/stdc++.h>using namespace std; // Function to split array and// move first part to endvoid splitArr(int arr[], int length, int rotation){ int tmp[length * 2] = {0}; for(int i = 0; i < length; i++) { tmp[i] = arr[i]; tmp[i + length] = arr[i]; } for(int i = rotation; i < rotation + length; i++) { arr[i - rotation] = tmp[i]; }} // Driver codeint main(){ int arr[] = { 12, 10, 5, 6, 52, 36 }; int n = sizeof(arr) / sizeof(arr[0]); int position = 2; splitArr(arr, n, position); for (int i = 0; i < n; ++i) printf("%d ", arr[i]); return 0;} // This code is contributed by YashKhandelwal8 // Java program to split array and move first// part to end.import java.util.*;import java.lang.*;class GFG { // Function to split array and // move first part to end public static void SplitAndAdd(int[] A,int length,int rotation){ //make a temporary array with double the size int[] tmp = new int[length*2]; // copy array element in to new array twice System.arraycopy(A, 0, tmp, 0, length); System.arraycopy(A, 0, tmp, length, length); for(int i=rotation;i<rotation+length;i++) A[i-rotation]=tmp[i]; } // Driver code public static void main(String[] args) { int arr[] = { 12, 10, 5, 6, 52, 36 }; int n = arr.length; int position = 2; SplitAndAdd(arr, n, position); for (int i = 0; i < n; ++i) System.out.print(arr[i] + " "); }} # Python3 program to split array and# move first part to end. # Function to split array and# move first part to enddef SplitAndAdd(A, length, rotation): # make a temporary array with double # the size and each index is initialized to 0 tmp = [ 0 for i in range(length * 2)] # copy array element in to new array twice for i in range(length): tmp[i] = A[i] tmp[i + length] = A[i] for i in range(rotation, rotation + length, 1): A[i - rotation] = tmp[i]; # Driver codearr = [12, 10, 5, 6, 52, 36]n = len(arr)position = 2SplitAndAdd(arr, n, position);for i in range(n): print(arr[i], end = " ")print() # This code is contributed by SOUMYA SEN // C# program to split array// and move first part to end.using System; class GFG{ // Function to split array and // move first part to end public static void SplitAndAdd(int[] A, int length, int rotation) { // make a temporary array with double the size int[] tmp = new int[length * 2]; // copy array element in to new array twice Array.Copy(A, 0, tmp, 0, length); Array.Copy(A, 0, tmp, length, length); for (int i = rotation; i < rotation + length; i++) { A[i - rotation] = tmp[i]; } } // Driver code public static void Main(string[] args) { int[] arr = new int[] {12, 10, 5, 6, 52, 36}; int n = arr.Length; int position = 2; SplitAndAdd(arr, n, position); for (int i = 0; i < n; ++i) { Console.Write(arr[i] + " "); } }} // This code is contributed by kumar65 <script>// Javascript program to split// array and move first// part to end. // Function to split array and // move first part to end function SplitAndAdd(A,Length,rotation) { // make a temporary array // with double the size let tmp = new Array(Length*2); for(let i=0;i<tmp.length;i++) { tmp[i]=0; } // copy array element in to new array twice for(let i=0;i<Length;i++) { tmp[i] = A[i] tmp[i + Length] = A[i] } for(let i=rotation;i<rotation+Length;i++) { A[i - rotation] = tmp[i]; } } // Driver code let arr=[12, 10, 5, 6, 52, 36]; let n = arr.length; let position = 2; SplitAndAdd(arr, n, position); for (let i = 0; i < n; ++i) document.write(arr[i] + " "); // This code is contributed by avanitrachhadiya2155 </script> 5 6 52 36 12 10 Time complexity: O(n) Space complexity: O(2n) An efficient O(n) solution is discussed in the following post: Split the array and add the first part to the end | Set 2This problem is noted but array rotation problem and we can apply the optimized O(n) array rotation methods here. Program for array rotation Block swap algorithm for array rotationReversal algorithm for array rotation Quickly find multiple left rotations of an array | Set 1 Print left rotation of array in O(n) time and O(1) spaceThis article is contributed by Aditya Ranjan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. shrikanth13 ukasp Rishabh Bhardwaj aslamkhan soumya7 kumar65 YashKhandelwal8 rohitsingh07052 avanitrachhadiya2155 akshaysingh98088 shivanisinghss2110 adi1212 shivamgupta2 triangleofcoding rajanit7112002 rotation Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Write a program to reverse an array or string Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Largest Sum Contiguous Subarray Arrays in C/C++ Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Subset Sum Problem | DP-25
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jun, 2022" }, { "code": null, "e": 195, "s": 52, "text": "There is a given array and split it from a specified position, and move the first splitted part of the array and then add to the end of array " }, { "code": null, "e": 207, "s": 195, "text": "Examples: " }, { "code": null, "e": 578, "s": 207, "text": "Input : arr[] = {12, 10, 5, 6, 52, 36}\n k = 2\nOutput : arr[] = {5, 6, 52, 36, 12, 10}\nExplanation : here k is two so first two elements are splitted and they are added at the end of array\n\nInput : arr[] = {3, 1, 2}\n k = 1\nOutput : arr[] = {1, 2, 3}\nExplanation :here k is one so first one element are splitted and it is added at the end of array" }, { "code": null, "e": 650, "s": 580, "text": "Simple Solution We will rotate the elements of the array one by one. " }, { "code": null, "e": 652, "s": 650, "text": "C" }, { "code": null, "e": 656, "s": 652, "text": "C++" }, { "code": null, "e": 661, "s": 656, "text": "Java" }, { "code": null, "e": 669, "s": 661, "text": "Python3" }, { "code": null, "e": 672, "s": 669, "text": "C#" }, { "code": null, "e": 676, "s": 672, "text": "PHP" }, { "code": null, "e": 687, "s": 676, "text": "Javascript" }, { "code": "// CPP program to split array and move first// part to end.#include <stdio.h> void splitArr(int arr[], int n, int k){ for (int i = 0; i < k; i++) { // Rotate array by 1. int x = arr[0]; for (int j = 0; j < n - 1; ++j) arr[j] = arr[j + 1]; arr[n - 1] = x; }} // Driver codeint main(){ int arr[] = { 12, 10, 5, 6, 52, 36 }; int n = sizeof(arr) / sizeof(arr[0]); int position = 2; splitArr(arr, n, position); for (int i = 0; i < n; ++i) printf(\"%d \", arr[i]); return 0;}", "e": 1229, "s": 687, "text": null }, { "code": "// CPP program to split array and move first// part to end.#include <iostream>using namespace std; void splitArr(int arr[], int n, int k){ for (int i = 0; i < k; i++) { // Rotate array by 1. int x = arr[0]; for (int j = 0; j < n - 1; ++j) arr[j] = arr[j + 1]; arr[n - 1] = x; }} // Driver codeint main(){ int arr[] = { 12, 10, 5, 6, 52, 36 }; int n = sizeof(arr) / sizeof(arr[0]); int position = 2; splitArr(arr, n, position); for (int i = 0; i < n; ++i) cout <<\" \"<< arr[i]; return 0;} // This code is contributed by shivanisinghss2110", "e": 1840, "s": 1229, "text": null }, { "code": "// Java program to split array and move first// part to end. import java.util.*;import java.lang.*;class GFG { public static void splitArr(int arr[], int n, int k) { for (int i = 0; i < k; i++) { // Rotate array by 1. int x = arr[0]; for (int j = 0; j < n - 1; ++j) arr[j] = arr[j + 1]; arr[n - 1] = x; } } // Driver code public static void main(String[] args) { int arr[] = { 12, 10, 5, 6, 52, 36 }; int n = arr.length; int position = 2; splitArr(arr, n, position); for (int i = 0; i < n; ++i) System.out.print(arr[i] + \" \"); }} // Code Contributed by Mohit Gupta_OMG <(0_o)>", "e": 2561, "s": 1840, "text": null }, { "code": "# Python program to split array and move first# part to end. def splitArr(arr, n, k): for i in range(0, k): x = arr[0] for j in range(0, n-1): arr[j] = arr[j + 1] arr[n-1] = x # mainarr = [12, 10, 5, 6, 52, 36]n = len(arr)position = 2 splitArr(arr, n, position) for i in range(0, n): print(arr[i], end = ' ') # Code Contributed by Mohit Gupta_OMG <(0_o)> ", "e": 2974, "s": 2561, "text": null }, { "code": "// C# program to split array// and move first part to end.using System; class GFG { // Function to split array and // move first part to end public static void splitArr(int[] arr, int n, int k) { for (int i = 0; i < k; i++) { // Rotate array by 1. int x = arr[0]; for (int j = 0; j < n - 1; ++j) arr[j] = arr[j + 1]; arr[n - 1] = x; } } // Driver code public static void Main() { int[] arr = {12, 10, 5, 6, 52, 36}; int n = arr.Length; int position = 2; splitArr(arr, n, position); for (int i = 0; i < n; ++i) Console.Write(arr[i] + \" \"); }} // This code is contributed by Shrikant13.", "e": 3751, "s": 2974, "text": null }, { "code": "<?php// PHP program to split array// and move first part to end. function splitArr(&$arr, $n, $k){ for ($i = 0; $i < $k; $i++) { // Rotate array by 1. $x = $arr[0]; for ($j = 0; $j < $n - 1; ++$j) $arr[$j] = $arr[$j + 1]; $arr[$n - 1] = $x; }} // Driver code$arr = array(12, 10, 5, 6, 52, 36);$n = sizeof($arr);$position = 2; splitArr($arr, n, $position); for ($i = 0; $i < $n; ++$i) echo $arr[$i].\" \"; // This code is contributed// by ChitraNayal?>", "e": 4253, "s": 3751, "text": null }, { "code": "<script> // JavaScript program to split// array and move first// part to end. function splitArr(arr, n, k){ for (let i = 0; i < k; i++) { // Rotate array by 1. let x = arr[0]; for (let j = 0; j < n - 1; ++j) arr[j] = arr[j + 1]; arr[n - 1] = x; }} // Driver code let arr = [ 12, 10, 5, 6, 52, 36 ];let n = arr.length;let position = 2;splitArr(arr, n, position);for (let i = 0; i < n; ++i) document.write(arr[i]+\" \"); </script>", "e": 4735, "s": 4253, "text": null }, { "code": null, "e": 4752, "s": 4735, "text": "5 6 52 36 12 10 " }, { "code": null, "e": 4800, "s": 4752, "text": "Time complexity of the above solution is O(n). " }, { "code": null, "e": 4823, "s": 4800, "text": "Space complexity: O(1)" }, { "code": null, "e": 5140, "s": 4823, "text": "Another approach: Another approach is to make a temporary array with double the size and copy our array element into a new array twice .and then copy the element from the new array to our array by taking the rotation as starting index up to the length of our array.Below is the implementation of the above approach. " }, { "code": null, "e": 5144, "s": 5140, "text": "C++" }, { "code": null, "e": 5149, "s": 5144, "text": "Java" }, { "code": null, "e": 5157, "s": 5149, "text": "Python3" }, { "code": null, "e": 5160, "s": 5157, "text": "C#" }, { "code": null, "e": 5171, "s": 5160, "text": "Javascript" }, { "code": "// CPP program to split array and move first// part to end.#include <bits/stdc++.h>using namespace std; // Function to split array and// move first part to endvoid splitArr(int arr[], int length, int rotation){ int tmp[length * 2] = {0}; for(int i = 0; i < length; i++) { tmp[i] = arr[i]; tmp[i + length] = arr[i]; } for(int i = rotation; i < rotation + length; i++) { arr[i - rotation] = tmp[i]; }} // Driver codeint main(){ int arr[] = { 12, 10, 5, 6, 52, 36 }; int n = sizeof(arr) / sizeof(arr[0]); int position = 2; splitArr(arr, n, position); for (int i = 0; i < n; ++i) printf(\"%d \", arr[i]); return 0;} // This code is contributed by YashKhandelwal8", "e": 5900, "s": 5171, "text": null }, { "code": "// Java program to split array and move first// part to end.import java.util.*;import java.lang.*;class GFG { // Function to split array and // move first part to end public static void SplitAndAdd(int[] A,int length,int rotation){ //make a temporary array with double the size int[] tmp = new int[length*2]; // copy array element in to new array twice System.arraycopy(A, 0, tmp, 0, length); System.arraycopy(A, 0, tmp, length, length); for(int i=rotation;i<rotation+length;i++) A[i-rotation]=tmp[i]; } // Driver code public static void main(String[] args) { int arr[] = { 12, 10, 5, 6, 52, 36 }; int n = arr.length; int position = 2; SplitAndAdd(arr, n, position); for (int i = 0; i < n; ++i) System.out.print(arr[i] + \" \"); }}", "e": 6780, "s": 5900, "text": null }, { "code": "# Python3 program to split array and# move first part to end. # Function to split array and# move first part to enddef SplitAndAdd(A, length, rotation): # make a temporary array with double # the size and each index is initialized to 0 tmp = [ 0 for i in range(length * 2)] # copy array element in to new array twice for i in range(length): tmp[i] = A[i] tmp[i + length] = A[i] for i in range(rotation, rotation + length, 1): A[i - rotation] = tmp[i]; # Driver codearr = [12, 10, 5, 6, 52, 36]n = len(arr)position = 2SplitAndAdd(arr, n, position);for i in range(n): print(arr[i], end = \" \")print() # This code is contributed by SOUMYA SEN", "e": 7487, "s": 6780, "text": null }, { "code": "// C# program to split array// and move first part to end.using System; class GFG{ // Function to split array and // move first part to end public static void SplitAndAdd(int[] A, int length, int rotation) { // make a temporary array with double the size int[] tmp = new int[length * 2]; // copy array element in to new array twice Array.Copy(A, 0, tmp, 0, length); Array.Copy(A, 0, tmp, length, length); for (int i = rotation; i < rotation + length; i++) { A[i - rotation] = tmp[i]; } } // Driver code public static void Main(string[] args) { int[] arr = new int[] {12, 10, 5, 6, 52, 36}; int n = arr.Length; int position = 2; SplitAndAdd(arr, n, position); for (int i = 0; i < n; ++i) { Console.Write(arr[i] + \" \"); } }} // This code is contributed by kumar65", "e": 8477, "s": 7487, "text": null }, { "code": "<script>// Javascript program to split// array and move first// part to end. // Function to split array and // move first part to end function SplitAndAdd(A,Length,rotation) { // make a temporary array // with double the size let tmp = new Array(Length*2); for(let i=0;i<tmp.length;i++) { tmp[i]=0; } // copy array element in to new array twice for(let i=0;i<Length;i++) { tmp[i] = A[i] tmp[i + Length] = A[i] } for(let i=rotation;i<rotation+Length;i++) { A[i - rotation] = tmp[i]; } } // Driver code let arr=[12, 10, 5, 6, 52, 36]; let n = arr.length; let position = 2; SplitAndAdd(arr, n, position); for (let i = 0; i < n; ++i) document.write(arr[i] + \" \"); // This code is contributed by avanitrachhadiya2155 </script>", "e": 9443, "s": 8477, "text": null }, { "code": null, "e": 9460, "s": 9443, "text": "5 6 52 36 12 10 " }, { "code": null, "e": 9482, "s": 9460, "text": "Time complexity: O(n)" }, { "code": null, "e": 9506, "s": 9482, "text": "Space complexity: O(2n)" }, { "code": null, "e": 10382, "s": 9506, "text": "An efficient O(n) solution is discussed in the following post: Split the array and add the first part to the end | Set 2This problem is noted but array rotation problem and we can apply the optimized O(n) array rotation methods here. Program for array rotation Block swap algorithm for array rotationReversal algorithm for array rotation Quickly find multiple left rotations of an array | Set 1 Print left rotation of array in O(n) time and O(1) spaceThis article is contributed by Aditya Ranjan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. " }, { "code": null, "e": 10394, "s": 10382, "text": "shrikanth13" }, { "code": null, "e": 10400, "s": 10394, "text": "ukasp" }, { "code": null, "e": 10417, "s": 10400, "text": "Rishabh Bhardwaj" }, { "code": null, "e": 10427, "s": 10417, "text": "aslamkhan" }, { "code": null, "e": 10435, "s": 10427, "text": "soumya7" }, { "code": null, "e": 10443, "s": 10435, "text": "kumar65" }, { "code": null, "e": 10459, "s": 10443, "text": "YashKhandelwal8" }, { "code": null, "e": 10475, "s": 10459, "text": "rohitsingh07052" }, { "code": null, "e": 10496, "s": 10475, "text": "avanitrachhadiya2155" }, { "code": null, "e": 10513, "s": 10496, "text": "akshaysingh98088" }, { "code": null, "e": 10532, "s": 10513, "text": "shivanisinghss2110" }, { "code": null, "e": 10540, "s": 10532, "text": "adi1212" }, { "code": null, "e": 10553, "s": 10540, "text": "shivamgupta2" }, { "code": null, "e": 10570, "s": 10553, "text": "triangleofcoding" }, { "code": null, "e": 10585, "s": 10570, "text": "rajanit7112002" }, { "code": null, "e": 10594, "s": 10585, "text": "rotation" }, { "code": null, "e": 10601, "s": 10594, "text": "Arrays" }, { "code": null, "e": 10608, "s": 10601, "text": "Arrays" }, { "code": null, "e": 10706, "s": 10608, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10721, "s": 10706, "text": "Arrays in Java" }, { "code": null, "e": 10767, "s": 10721, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 10835, "s": 10767, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 10879, "s": 10835, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 10911, "s": 10879, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 10927, "s": 10911, "text": "Arrays in C/C++" }, { "code": null, "e": 10959, "s": 10927, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 11007, "s": 10959, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 11021, "s": 11007, "text": "Linear Search" } ]
Ruby | Hash empty? function
15 Apr, 2021 Hash#empty?() is a Hash class method which checks whether the Hash array has any key-value pair. Syntax: Hash.empty?()Parameter: Hash valuesReturn: true – if no key value pair otherwise return false Example #1 : Ruby # Ruby code for Hash.empty?() method # declaring Hash valuea = {a:100, b:200} # declaring Hash valueb = {a:100, c:300, b:200} # declaring Hash valuec = {a:100} # empty? Valueputs "Hash a empty? form : #{a.empty?()}\n\n" puts "Hash b empty? form : #{b.empty?()}\n\n" puts "Hash c empty? form : #{c.empty?()}\n\n" Output : Hash a empty? form : false Hash b empty? form : false Hash c empty? form : false Example #2 : Ruby # Ruby code for Hash.empty?() method # declaring Hash valuea = { "a" => 100, "b" => 200 } # declaring Hash valueb = {} # declaring Hash valuec = {"a" => 100, "c" => 300, "b" => 200} # emoty? Valueputs "Hash a empty? form : #{a.empty?()}\n\n" puts "Hash b empty? form : #{b.empty?()}\n\n" puts "Hash c empty? form : #{c.empty?()}\n\n" Output : Hash a empty? form : false Hash b empty? form : true Hash c empty? form : false hritikbhatnagar2182 Ruby Hash-class Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Make a Custom Array of Hashes in Ruby? Ruby | Enumerator each_with_index function Ruby | unless Statement and unless Modifier Ruby | Array class find_index() operation Ruby For Beginners Ruby | String concat Method Ruby | Array shift() function Ruby on Rails Introduction Ruby | Types of Variables
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Apr, 2021" }, { "code": null, "e": 126, "s": 28, "text": "Hash#empty?() is a Hash class method which checks whether the Hash array has any key-value pair. " }, { "code": null, "e": 228, "s": 126, "text": "Syntax: Hash.empty?()Parameter: Hash valuesReturn: true – if no key value pair otherwise return false" }, { "code": null, "e": 243, "s": 228, "text": "Example #1 : " }, { "code": null, "e": 248, "s": 243, "text": "Ruby" }, { "code": "# Ruby code for Hash.empty?() method # declaring Hash valuea = {a:100, b:200} # declaring Hash valueb = {a:100, c:300, b:200} # declaring Hash valuec = {a:100} # empty? Valueputs \"Hash a empty? form : #{a.empty?()}\\n\\n\" puts \"Hash b empty? form : #{b.empty?()}\\n\\n\" puts \"Hash c empty? form : #{c.empty?()}\\n\\n\"", "e": 568, "s": 248, "text": null }, { "code": null, "e": 579, "s": 568, "text": "Output : " }, { "code": null, "e": 662, "s": 579, "text": "Hash a empty? form : false\n\nHash b empty? form : false\n\nHash c empty? form : false" }, { "code": null, "e": 676, "s": 662, "text": "Example #2 : " }, { "code": null, "e": 681, "s": 676, "text": "Ruby" }, { "code": "# Ruby code for Hash.empty?() method # declaring Hash valuea = { \"a\" => 100, \"b\" => 200 } # declaring Hash valueb = {} # declaring Hash valuec = {\"a\" => 100, \"c\" => 300, \"b\" => 200} # emoty? Valueputs \"Hash a empty? form : #{a.empty?()}\\n\\n\" puts \"Hash b empty? form : #{b.empty?()}\\n\\n\" puts \"Hash c empty? form : #{c.empty?()}\\n\\n\"", "e": 1021, "s": 681, "text": null }, { "code": null, "e": 1030, "s": 1021, "text": "Output :" }, { "code": null, "e": 1112, "s": 1030, "text": "Hash a empty? form : false\n\nHash b empty? form : true\n\nHash c empty? form : false" }, { "code": null, "e": 1134, "s": 1114, "text": "hritikbhatnagar2182" }, { "code": null, "e": 1150, "s": 1134, "text": "Ruby Hash-class" }, { "code": null, "e": 1163, "s": 1150, "text": "Ruby-Methods" }, { "code": null, "e": 1168, "s": 1163, "text": "Ruby" }, { "code": null, "e": 1266, "s": 1168, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1312, "s": 1266, "text": "How to Make a Custom Array of Hashes in Ruby?" }, { "code": null, "e": 1355, "s": 1312, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 1399, "s": 1355, "text": "Ruby | unless Statement and unless Modifier" }, { "code": null, "e": 1441, "s": 1399, "text": "Ruby | Array class find_index() operation" }, { "code": null, "e": 1460, "s": 1441, "text": "Ruby For Beginners" }, { "code": null, "e": 1488, "s": 1460, "text": "Ruby | String concat Method" }, { "code": null, "e": 1518, "s": 1488, "text": "Ruby | Array shift() function" }, { "code": null, "e": 1545, "s": 1518, "text": "Ruby on Rails Introduction" } ]
Java Relational Operators with Examples
02 Dec, 2021 Operators constitute the basic building block to any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide. Types of Operators: Arithmetic OperatorsUnary OperatorsAssignment OperatorRelational OperatorsLogical OperatorsTernary OperatorBitwise OperatorsShift Operators Arithmetic Operators Unary Operators Assignment Operator Relational Operators Logical Operators Ternary Operator Bitwise Operators Shift Operators Java Relational Operators are a bunch of binary operators used to check for relations between two operands, including equality, greater than, less than, etc. They return a boolean result after the comparison and are extensively used in looping statements as well as conditional if-else statements and so on. The general format of representing relational operator is: Syntax: variable1 relation_operator variable2 Let us look at each one of the relational operators in Java: Operator 1: ‘Equal to’ operator (==) This operator is used to check whether the two given operands are equal or not. The operator returns true if the operand at the left-hand side is equal to the right-hand side, else false. Syntax: var1 == var2 Illustration: var1 = "GeeksforGeeks" var2 = 20 var1 == var2 results in false Example: Java // Java Program to Illustrate equal to Operator // Importing I/O classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Initializing variables int var1 = 5, var2 = 10, var3 = 5; // Displaying var1, var2, var3 System.out.println("Var1 = " + var1); System.out.println("Var2 = " + var2); System.out.println("Var3 = " + var3); // Comparing var1 and var2 and // printing corresponding boolean value System.out.println("var1 == var2: " + (var1 == var2)); // Comparing var1 and var3 and // printing corresponding boolean value System.out.println("var1 == var3: " + (var1 == var3)); }} Var1 = 5 Var2 = 10 Var3 = 5 var1 == var2: false var1 == var3: true Operator 2: ‘Not equal to’ Operator(!=) This operator is used to check whether the two given operands are equal or not. It functions opposite to that of the equal-to-operator. It returns true if the operand at the left-hand side is not equal to the right-hand side, else false. Syntax: var1 != var2 Illustration: var1 = "GeeksforGeeks" var2 = 20 var1 != var2 results in true Example: Java // Java Program to Illustrate No- equal-to Operator // Importing I/O classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Initializing variables int var1 = 5, var2 = 10, var3 = 5; // Displaying var1, var2, var3 System.out.println("Var1 = " + var1); System.out.println("Var2 = " + var2); System.out.println("Var3 = " + var3); // Comparing var1 and var2 and // printing corresponding boolean value System.out.println("var1 == var2: " + (var1 != var2)); // Comparing var1 and var3 and // printing corresponding boolean value System.out.println("var1 == var3: " + (var1 != var3)); }} Var1 = 5 Var2 = 10 Var3 = 5 var1 == var2: true var1 == var3: false Operator 3: ‘Greater than’ operator(>) This checks whether the first operand is greater than the second operand or not. The operator returns true when the operand at the left-hand side is greater than the right-hand side. Syntax: var1 > var2 Illustration: var1 = 30 var2 = 20 var1 > var2 results in true Example: Java // Java code to Illustrate Greater than operator // Importing I/O classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Initializing variables int var1 = 30, var2 = 20, var3 = 5; // Displaying var1, var2, var3 System.out.println("Var1 = " + var1); System.out.println("Var2 = " + var2); System.out.println("Var3 = " + var3); // Comparing var1 and var2 and // printing corresponding boolean value System.out.println("var1 > var2: " + (var1 > var2)); // Comparing var1 and var3 and // printing corresponding boolean value System.out.println("var3 > var1: " + (var3 >= var1)); }} Var1 = 30 Var2 = 20 Var3 = 5 var1 > var2: true var3 > var1: false Operator 4: ‘Less than’ Operator(<) This checks whether the first operand is less than the second operand or not. The operator returns true when the operand at the left-hand side is less than the right-hand side. It functions opposite to that of the greater-than operator. Syntax: var1 < var2 Illustration: var1 = 10 var2 = 20 var1 < var2 results in true Example: Java // Java code to Illustrate Less than Operator // Importing I/O classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Initializing variables int var1 = 10, var2 = 20, var3 = 5; // Displaying var1, var2, var3 System.out.println("Var1 = " + var1); System.out.println("Var2 = " + var2); System.out.println("Var3 = " + var3); // Comparing var1 and var2 and // printing corresponding boolean value System.out.println("var1 < var2: " + (var1 < var2)); // Comparing var2 and var3 and // printing corresponding boolean value System.out.println("var2 < var3: " + (var2 < var3)); }} Var1 = 10 Var2 = 20 Var3 = 5 var1 < var2: true var2 < var3: false Operator 5: Greater than or equal to (>=) This checks whether the first operand is greater than or equal to the second operand or not. The operator returns true when the operand at the left-hand side is greater than or equal to the right-hand side. Syntax: var1 >= var2 Illustration: var1 = 20 var2 = 20 var3 = 10 var1 >= var2 results in true var2 >= var3 results in true Example: Java // Java Program to Illustrate Greater than or equal to// Operator // Importing I/O classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Initializing variables int var1 = 20, var2 = 20, var3 = 10; // Displaying var1, var2, var3 System.out.println("Var1 = " + var1); System.out.println("Var2 = " + var2); System.out.println("Var3 = " + var3); // Comparing var1 and var2 and // printing corresponding boolean value System.out.println("var1 >= var2: " + (var1 >= var2)); // Comparing var2 and var3 and // printing corresponding boolean value System.out.println("var2 >= var3: " + (var3 >= var1)); }} Var1 = 20 Var2 = 20 Var3 = 10 var1 >= var2: true var2 >= var3: false Operator 6: Less than or equal to (<=) This checks whether the first operand is less than or equal to the second operand or not. The operator returns true when the operand at the left-hand side is less than or equal to the right-hand side. Syntax: var1 <= var2 Illustration: var1 = 10 var2 = 10 var3 = 9 var1 <= var2 results in true var2 <= var3 results in false Example: Java // Java Program to Illustrate Less// than or equal to operator // Importing I/O classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Initializing variables int var1 = 10, var2 = 10, var3 = 9; // Displaying var1, var2, var3 System.out.println("Var1 = " + var1); System.out.println("Var2 = " + var2); System.out.println("Var3 = " + var3); // Comparing var1 and var2 and // printing corresponding boolean value System.out.println("var1 <= var2: " + (var1 <= var2)); // Comparing var2 and var3 and // printing corresponding boolean value System.out.println("var2 <= var3: " + (var2 <= var3)); }} Var1 = 10 Var2 = 10 Var3 = 9 var1 <= var2: true var2 <= var3: false arjunnrana singghakshay nishkarshgandhi Java-Operators Java Java-Operators Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Reverse a string in Java Split() String method in Java with examples Arrays.sort() in Java with examples How to iterate any Map in Java Stream In Java Singleton Class in Java Java Programming Examples Generics in Java Initialize an ArrayList in Java Initializing a List in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n02 Dec, 2021" }, { "code": null, "e": 361, "s": 52, "text": "Operators constitute the basic building block to any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide." }, { "code": null, "e": 382, "s": 361, "text": "Types of Operators: " }, { "code": null, "e": 522, "s": 382, "text": "Arithmetic OperatorsUnary OperatorsAssignment OperatorRelational OperatorsLogical OperatorsTernary OperatorBitwise OperatorsShift Operators" }, { "code": null, "e": 543, "s": 522, "text": "Arithmetic Operators" }, { "code": null, "e": 559, "s": 543, "text": "Unary Operators" }, { "code": null, "e": 579, "s": 559, "text": "Assignment Operator" }, { "code": null, "e": 600, "s": 579, "text": "Relational Operators" }, { "code": null, "e": 618, "s": 600, "text": "Logical Operators" }, { "code": null, "e": 635, "s": 618, "text": "Ternary Operator" }, { "code": null, "e": 653, "s": 635, "text": "Bitwise Operators" }, { "code": null, "e": 669, "s": 653, "text": "Shift Operators" }, { "code": null, "e": 1037, "s": 669, "text": "Java Relational Operators are a bunch of binary operators used to check for relations between two operands, including equality, greater than, less than, etc. They return a boolean result after the comparison and are extensively used in looping statements as well as conditional if-else statements and so on. The general format of representing relational operator is: " }, { "code": null, "e": 1045, "s": 1037, "text": "Syntax:" }, { "code": null, "e": 1083, "s": 1045, "text": "variable1 relation_operator variable2" }, { "code": null, "e": 1144, "s": 1083, "text": "Let us look at each one of the relational operators in Java:" }, { "code": null, "e": 1181, "s": 1144, "text": "Operator 1: ‘Equal to’ operator (==)" }, { "code": null, "e": 1370, "s": 1181, "text": "This operator is used to check whether the two given operands are equal or not. The operator returns true if the operand at the left-hand side is equal to the right-hand side, else false. " }, { "code": null, "e": 1379, "s": 1370, "text": "Syntax: " }, { "code": null, "e": 1392, "s": 1379, "text": "var1 == var2" }, { "code": null, "e": 1406, "s": 1392, "text": "Illustration:" }, { "code": null, "e": 1469, "s": 1406, "text": "var1 = \"GeeksforGeeks\"\nvar2 = 20\nvar1 == var2 results in false" }, { "code": null, "e": 1478, "s": 1469, "text": "Example:" }, { "code": null, "e": 1483, "s": 1478, "text": "Java" }, { "code": "// Java Program to Illustrate equal to Operator // Importing I/O classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Initializing variables int var1 = 5, var2 = 10, var3 = 5; // Displaying var1, var2, var3 System.out.println(\"Var1 = \" + var1); System.out.println(\"Var2 = \" + var2); System.out.println(\"Var3 = \" + var3); // Comparing var1 and var2 and // printing corresponding boolean value System.out.println(\"var1 == var2: \" + (var1 == var2)); // Comparing var1 and var3 and // printing corresponding boolean value System.out.println(\"var1 == var3: \" + (var1 == var3)); }}", "e": 2274, "s": 1483, "text": null }, { "code": null, "e": 2341, "s": 2274, "text": "Var1 = 5\nVar2 = 10\nVar3 = 5\nvar1 == var2: false\nvar1 == var3: true" }, { "code": null, "e": 2381, "s": 2341, "text": "Operator 2: ‘Not equal to’ Operator(!=)" }, { "code": null, "e": 2620, "s": 2381, "text": "This operator is used to check whether the two given operands are equal or not. It functions opposite to that of the equal-to-operator. It returns true if the operand at the left-hand side is not equal to the right-hand side, else false. " }, { "code": null, "e": 2629, "s": 2620, "text": "Syntax: " }, { "code": null, "e": 2642, "s": 2629, "text": "var1 != var2" }, { "code": null, "e": 2657, "s": 2642, "text": "Illustration: " }, { "code": null, "e": 2720, "s": 2657, "text": "var1 = \"GeeksforGeeks\"\nvar2 = 20\n\nvar1 != var2 results in true" }, { "code": null, "e": 2729, "s": 2720, "text": "Example:" }, { "code": null, "e": 2734, "s": 2729, "text": "Java" }, { "code": "// Java Program to Illustrate No- equal-to Operator // Importing I/O classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Initializing variables int var1 = 5, var2 = 10, var3 = 5; // Displaying var1, var2, var3 System.out.println(\"Var1 = \" + var1); System.out.println(\"Var2 = \" + var2); System.out.println(\"Var3 = \" + var3); // Comparing var1 and var2 and // printing corresponding boolean value System.out.println(\"var1 == var2: \" + (var1 != var2)); // Comparing var1 and var3 and // printing corresponding boolean value System.out.println(\"var1 == var3: \" + (var1 != var3)); }}", "e": 3529, "s": 2734, "text": null }, { "code": null, "e": 3596, "s": 3529, "text": "Var1 = 5\nVar2 = 10\nVar3 = 5\nvar1 == var2: true\nvar1 == var3: false" }, { "code": null, "e": 3635, "s": 3596, "text": "Operator 3: ‘Greater than’ operator(>)" }, { "code": null, "e": 3819, "s": 3635, "text": "This checks whether the first operand is greater than the second operand or not. The operator returns true when the operand at the left-hand side is greater than the right-hand side. " }, { "code": null, "e": 3828, "s": 3819, "text": "Syntax: " }, { "code": null, "e": 3840, "s": 3828, "text": "var1 > var2" }, { "code": null, "e": 3855, "s": 3840, "text": "Illustration: " }, { "code": null, "e": 3904, "s": 3855, "text": "var1 = 30\nvar2 = 20\n\nvar1 > var2 results in true" }, { "code": null, "e": 3913, "s": 3904, "text": "Example:" }, { "code": null, "e": 3918, "s": 3913, "text": "Java" }, { "code": "// Java code to Illustrate Greater than operator // Importing I/O classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Initializing variables int var1 = 30, var2 = 20, var3 = 5; // Displaying var1, var2, var3 System.out.println(\"Var1 = \" + var1); System.out.println(\"Var2 = \" + var2); System.out.println(\"Var3 = \" + var3); // Comparing var1 and var2 and // printing corresponding boolean value System.out.println(\"var1 > var2: \" + (var1 > var2)); // Comparing var1 and var3 and // printing corresponding boolean value System.out.println(\"var3 > var1: \" + (var3 >= var1)); }}", "e": 4682, "s": 3918, "text": null }, { "code": null, "e": 4748, "s": 4682, "text": "Var1 = 30\nVar2 = 20\nVar3 = 5\nvar1 > var2: true\nvar3 > var1: false" }, { "code": null, "e": 4784, "s": 4748, "text": "Operator 4: ‘Less than’ Operator(<)" }, { "code": null, "e": 5022, "s": 4784, "text": "This checks whether the first operand is less than the second operand or not. The operator returns true when the operand at the left-hand side is less than the right-hand side. It functions opposite to that of the greater-than operator. " }, { "code": null, "e": 5031, "s": 5022, "text": "Syntax: " }, { "code": null, "e": 5043, "s": 5031, "text": "var1 < var2" }, { "code": null, "e": 5058, "s": 5043, "text": "Illustration: " }, { "code": null, "e": 5107, "s": 5058, "text": "var1 = 10\nvar2 = 20\n\nvar1 < var2 results in true" }, { "code": null, "e": 5116, "s": 5107, "text": "Example:" }, { "code": null, "e": 5121, "s": 5116, "text": "Java" }, { "code": "// Java code to Illustrate Less than Operator // Importing I/O classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Initializing variables int var1 = 10, var2 = 20, var3 = 5; // Displaying var1, var2, var3 System.out.println(\"Var1 = \" + var1); System.out.println(\"Var2 = \" + var2); System.out.println(\"Var3 = \" + var3); // Comparing var1 and var2 and // printing corresponding boolean value System.out.println(\"var1 < var2: \" + (var1 < var2)); // Comparing var2 and var3 and // printing corresponding boolean value System.out.println(\"var2 < var3: \" + (var2 < var3)); }}", "e": 5855, "s": 5121, "text": null }, { "code": null, "e": 5921, "s": 5855, "text": "Var1 = 10\nVar2 = 20\nVar3 = 5\nvar1 < var2: true\nvar2 < var3: false" }, { "code": null, "e": 5963, "s": 5921, "text": "Operator 5: Greater than or equal to (>=)" }, { "code": null, "e": 6171, "s": 5963, "text": "This checks whether the first operand is greater than or equal to the second operand or not. The operator returns true when the operand at the left-hand side is greater than or equal to the right-hand side. " }, { "code": null, "e": 6180, "s": 6171, "text": "Syntax: " }, { "code": null, "e": 6193, "s": 6180, "text": "var1 >= var2" }, { "code": null, "e": 6207, "s": 6193, "text": "Illustration:" }, { "code": null, "e": 6296, "s": 6207, "text": "var1 = 20\nvar2 = 20\nvar3 = 10\n\nvar1 >= var2 results in true\nvar2 >= var3 results in true" }, { "code": null, "e": 6305, "s": 6296, "text": "Example:" }, { "code": null, "e": 6310, "s": 6305, "text": "Java" }, { "code": "// Java Program to Illustrate Greater than or equal to// Operator // Importing I/O classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Initializing variables int var1 = 20, var2 = 20, var3 = 10; // Displaying var1, var2, var3 System.out.println(\"Var1 = \" + var1); System.out.println(\"Var2 = \" + var2); System.out.println(\"Var3 = \" + var3); // Comparing var1 and var2 and // printing corresponding boolean value System.out.println(\"var1 >= var2: \" + (var1 >= var2)); // Comparing var2 and var3 and // printing corresponding boolean value System.out.println(\"var2 >= var3: \" + (var3 >= var1)); }}", "e": 7121, "s": 6310, "text": null }, { "code": null, "e": 7190, "s": 7121, "text": "Var1 = 20\nVar2 = 20\nVar3 = 10\nvar1 >= var2: true\nvar2 >= var3: false" }, { "code": null, "e": 7229, "s": 7190, "text": "Operator 6: Less than or equal to (<=)" }, { "code": null, "e": 7431, "s": 7229, "text": "This checks whether the first operand is less than or equal to the second operand or not. The operator returns true when the operand at the left-hand side is less than or equal to the right-hand side. " }, { "code": null, "e": 7440, "s": 7431, "text": "Syntax: " }, { "code": null, "e": 7453, "s": 7440, "text": "var1 <= var2" }, { "code": null, "e": 7468, "s": 7453, "text": "Illustration: " }, { "code": null, "e": 7557, "s": 7468, "text": "var1 = 10\nvar2 = 10\nvar3 = 9\n\nvar1 <= var2 results in true\nvar2 <= var3 results in false" }, { "code": null, "e": 7566, "s": 7557, "text": "Example:" }, { "code": null, "e": 7571, "s": 7566, "text": "Java" }, { "code": "// Java Program to Illustrate Less// than or equal to operator // Importing I/O classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Initializing variables int var1 = 10, var2 = 10, var3 = 9; // Displaying var1, var2, var3 System.out.println(\"Var1 = \" + var1); System.out.println(\"Var2 = \" + var2); System.out.println(\"Var3 = \" + var3); // Comparing var1 and var2 and // printing corresponding boolean value System.out.println(\"var1 <= var2: \" + (var1 <= var2)); // Comparing var2 and var3 and // printing corresponding boolean value System.out.println(\"var2 <= var3: \" + (var2 <= var3)); }}", "e": 8378, "s": 7571, "text": null }, { "code": null, "e": 8446, "s": 8378, "text": "Var1 = 10\nVar2 = 10\nVar3 = 9\nvar1 <= var2: true\nvar2 <= var3: false" }, { "code": null, "e": 8457, "s": 8446, "text": "arjunnrana" }, { "code": null, "e": 8470, "s": 8457, "text": "singghakshay" }, { "code": null, "e": 8486, "s": 8470, "text": "nishkarshgandhi" }, { "code": null, "e": 8501, "s": 8486, "text": "Java-Operators" }, { "code": null, "e": 8506, "s": 8501, "text": "Java" }, { "code": null, "e": 8521, "s": 8506, "text": "Java-Operators" }, { "code": null, "e": 8526, "s": 8521, "text": "Java" }, { "code": null, "e": 8624, "s": 8526, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8649, "s": 8624, "text": "Reverse a string in Java" }, { "code": null, "e": 8693, "s": 8649, "text": "Split() String method in Java with examples" }, { "code": null, "e": 8729, "s": 8693, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 8760, "s": 8729, "text": "How to iterate any Map in Java" }, { "code": null, "e": 8775, "s": 8760, "text": "Stream In Java" }, { "code": null, "e": 8799, "s": 8775, "text": "Singleton Class in Java" }, { "code": null, "e": 8825, "s": 8799, "text": "Java Programming Examples" }, { "code": null, "e": 8842, "s": 8825, "text": "Generics in Java" }, { "code": null, "e": 8874, "s": 8842, "text": "Initialize an ArrayList in Java" } ]
Bitwise right shift operator in Java
Java supports two types of right shift operators. The >> operator is a signed right shift operator and >>> is an unsigned right shift operator. The left operands value is moved right by the number of bits specified by the right operand. The signed right shift operator '>>' uses the sign bit to fill the trailing positions. For example, if the number is positive then 0 will be used to fill the trailing positions and if the number is negative then 1 will be used to fill the trailing positions. Assume if a = 60 and b = -60; now in binary format, they will be as follows − a = 0000 0000 0000 0000 0000 0000 0011 1100 b = 1111 1111 1111 1111 1111 1111 1100 0100 In Java, negative numbers are stored as 2's complement. Thus a >> 1 = 0000 0000 0000 0000 0000 0000 0001 1110 And b >> 1 = 1111 1111 1111 1111 1111 1111 1110 0010 The unsigned right shift operator '>>>' do not use the sign bit to fill the trailing positions. It always fills the trailing positions by 0s. Thus a >>> 1 = 0000 0000 0000 0000 0000 0000 0001 1110 And b >>> 1 = 0111 1111 1111 1111 1111 1111 1110 0010 Live Demo public class Tester { public static void main(String[] args) { int a = 60; int b = -60; int c = 0; System.out.println("60 = " + Integer.toBinaryString(a)); System.out.println("-60 = " + Integer.toBinaryString(b)); //signed shift c = a >> 1; System.out.println("60 >> 1 = " + Integer.toBinaryString(c)); //unsigned shift c = a >>> 1; System.out.println("60 >>> 1 = " + Integer.toBinaryString(c) ); c = b >> 1; System.out.println("-60 >> 1 = " + Integer.toBinaryString(c) ); c = b >>> 1; System.out.println("-60 >>> 1 = " + Integer.toBinaryString(c)); } } 60 = 111100 -60 = 11111111111111111111111111000100 60 >> 1 = 11110 60 >>> 1 = 11110 -60 >> 1 = 11111111111111111111111111100010 -60 >>> 1 = 1111111111111111111111111100010
[ { "code": null, "e": 1424, "s": 1187, "text": "Java supports two types of right shift operators. The >> operator is a signed right shift operator and >>> is an unsigned right shift operator. The left operands value is moved right by the number of bits specified by the right operand." }, { "code": null, "e": 1683, "s": 1424, "text": "The signed right shift operator '>>' uses the sign bit to fill the trailing positions. For example, if the number is positive then 0 will be used to fill the trailing positions and if the number is negative then 1 will be used to fill the trailing positions." }, { "code": null, "e": 1761, "s": 1683, "text": "Assume if a = 60 and b = -60; now in binary format, they will be as follows −" }, { "code": null, "e": 1849, "s": 1761, "text": "a = 0000 0000 0000 0000 0000 0000 0011 1100\nb = 1111 1111 1111 1111 1111 1111 1100 0100" }, { "code": null, "e": 1905, "s": 1849, "text": "In Java, negative numbers are stored as 2's complement." }, { "code": null, "e": 2012, "s": 1905, "text": "Thus a >> 1 = 0000 0000 0000 0000 0000 0000 0001 1110\nAnd b >> 1 = 1111 1111 1111 1111 1111 1111 1110 0010" }, { "code": null, "e": 2154, "s": 2012, "text": "The unsigned right shift operator '>>>' do not use the sign bit to fill the trailing positions. It always fills the trailing positions by 0s." }, { "code": null, "e": 2264, "s": 2154, "text": "Thus a >>> 1 = 0000 0000 0000 0000 0000 0000 0001 1110\nAnd b >>> 1 = 0111 1111 1111 1111 1111 1111 1110 0010" }, { "code": null, "e": 2274, "s": 2264, "text": "Live Demo" }, { "code": null, "e": 2987, "s": 2274, "text": "public class Tester {\n public static void main(String[] args) {\n int a = 60; int b = -60; int c = 0;\n System.out.println(\"60 = \" + Integer.toBinaryString(a));\n System.out.println(\"-60 = \" + Integer.toBinaryString(b));\n\n //signed shift\n c = a >> 1; \n System.out.println(\"60 >> 1 = \" + Integer.toBinaryString(c));\n\n //unsigned shift\n c = a >>> 1; \n System.out.println(\"60 >>> 1 = \" + Integer.toBinaryString(c) );\n\n c = b >> 1; \n System.out.println(\"-60 >> 1 = \" + Integer.toBinaryString(c) );\n\n c = b >>> 1; \n System.out.println(\"-60 >>> 1 = \" + Integer.toBinaryString(c));\n }\n}" }, { "code": null, "e": 3162, "s": 2987, "text": "60 = 111100\n-60 = 11111111111111111111111111000100\n60 >> 1 = 11110\n60 >>> 1 = 11110\n-60 >> 1 = 11111111111111111111111111100010\n-60 >>> 1 = 1111111111111111111111111100010" } ]
Java Program To Find Largest Between Three Numbers Using Ternary Operator
02 Nov, 2020 Java offers a lot of Operators and one such operator is the Ternary Operator. It is a linear replacement for an if-else statement. Thus, it is a very useful operator and it uses less space in comparison to an if-else statement. Ternary Operator Syntax : variable = condition ? expression1 : expression2 ; The same statement can be written in if-else statement as follows: if(condition){ variable = expression1 ; } else{ variable = expression2 ; } Given three numbers we have to find the maximum among them by just using the ternary operator. Example : Input : a = 15 , b = 10 , c = 45 Output : 45 Input : a = 31 , b = 67 , c = 23 Output : 67 Thus, we can make use of nested ternary operator to find the maximum of 3 number as shown below : Java // Java Program to Find Largest// Between Three Numbers Using// Ternary Operatorclass MaximumNumber { // Main function public static void main(String args[]) { // Variable Declaration int a = 10, b = 25, c = 15, max; // Maximum among a, b, c max = (a > b) ? (a > c ? a : c) : (b > c ? b : c); // Print the largest number System.out.println("Maximum number among " + a + ", " + b + " and " + c + " is " + max); }} Maximum number among 10, 25 and 15 is 25 Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java ArrayList in Java Collections in Java Multidimensional Arrays in Java Stream In Java Initializing a List in Java Java Programming Examples Convert a String to Character Array in Java Implementing a Linked List in Java using Class Factory method design pattern in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n02 Nov, 2020" }, { "code": null, "e": 282, "s": 54, "text": "Java offers a lot of Operators and one such operator is the Ternary Operator. It is a linear replacement for an if-else statement. Thus, it is a very useful operator and it uses less space in comparison to an if-else statement." }, { "code": null, "e": 308, "s": 282, "text": "Ternary Operator Syntax :" }, { "code": null, "e": 360, "s": 308, "text": "variable = condition ? expression1 : expression2 ;\n" }, { "code": null, "e": 427, "s": 360, "text": "The same statement can be written in if-else statement as follows:" }, { "code": null, "e": 515, "s": 427, "text": "if(condition){\n variable = expression1 ;\n}\nelse{\n variable = expression2 ;\n}\n" }, { "code": null, "e": 610, "s": 515, "text": "Given three numbers we have to find the maximum among them by just using the ternary operator." }, { "code": null, "e": 621, "s": 610, "text": "Example : " }, { "code": null, "e": 715, "s": 621, "text": "Input : a = 15 , b = 10 , c = 45\nOutput : 45\n\nInput : a = 31 , b = 67 , c = 23\nOutput : 67\n" }, { "code": null, "e": 813, "s": 715, "text": "Thus, we can make use of nested ternary operator to find the maximum of 3 number as shown below :" }, { "code": null, "e": 818, "s": 813, "text": "Java" }, { "code": "// Java Program to Find Largest// Between Three Numbers Using// Ternary Operatorclass MaximumNumber { // Main function public static void main(String args[]) { // Variable Declaration int a = 10, b = 25, c = 15, max; // Maximum among a, b, c max = (a > b) ? (a > c ? a : c) : (b > c ? b : c); // Print the largest number System.out.println(\"Maximum number among \" + a + \", \" + b + \" and \" + c + \" is \" + max); }}", "e": 1343, "s": 818, "text": null }, { "code": null, "e": 1384, "s": 1343, "text": "Maximum number among 10, 25 and 15 is 25" }, { "code": null, "e": 1389, "s": 1384, "text": "Java" }, { "code": null, "e": 1403, "s": 1389, "text": "Java Programs" }, { "code": null, "e": 1408, "s": 1403, "text": "Java" }, { "code": null, "e": 1506, "s": 1408, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1525, "s": 1506, "text": "Interfaces in Java" }, { "code": null, "e": 1543, "s": 1525, "text": "ArrayList in Java" }, { "code": null, "e": 1563, "s": 1543, "text": "Collections in Java" }, { "code": null, "e": 1595, "s": 1563, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 1610, "s": 1595, "text": "Stream In Java" }, { "code": null, "e": 1638, "s": 1610, "text": "Initializing a List in Java" }, { "code": null, "e": 1664, "s": 1638, "text": "Java Programming Examples" }, { "code": null, "e": 1708, "s": 1664, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 1755, "s": 1708, "text": "Implementing a Linked List in Java using Class" } ]
Python | TextBlob.noun_phrases() method
09 Sep, 2019 With the help of TextBlob.noun_phrases() method, we can get the noun phrases of the sentences by using TextBlob.noun_phrases() method. Syntax : TextBlob.noun_phrases()Return : Return list of noun values. Example #1 :In this example we can say that by using TextBlob.noun_phrases() method, we are able to get the list of noun words. # import TextBlobfrom textblob import TextBlob gfg = TextBlob("Python is a high-level language.") # using TextBlob.noun_phrases methodgfg = gfg.noun_phrases print(gfg) Output : [‘python’, ‘high-level language’] Example #2 : # import TextBlobfrom textblob import TextBlob gfg = TextBlob("Sandeep Jain An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways.") # using TextBlob.noun_phrases methodgfg = gfg.noun_phrases print(gfg) Output : [‘sandeep jain’, ‘iit roorkee’, ‘geeksforgeeks’, ‘efficient ways’] Python-Functions 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": "\n09 Sep, 2019" }, { "code": null, "e": 163, "s": 28, "text": "With the help of TextBlob.noun_phrases() method, we can get the noun phrases of the sentences by using TextBlob.noun_phrases() method." }, { "code": null, "e": 232, "s": 163, "text": "Syntax : TextBlob.noun_phrases()Return : Return list of noun values." }, { "code": null, "e": 360, "s": 232, "text": "Example #1 :In this example we can say that by using TextBlob.noun_phrases() method, we are able to get the list of noun words." }, { "code": "# import TextBlobfrom textblob import TextBlob gfg = TextBlob(\"Python is a high-level language.\") # using TextBlob.noun_phrases methodgfg = gfg.noun_phrases print(gfg)", "e": 531, "s": 360, "text": null }, { "code": null, "e": 540, "s": 531, "text": "Output :" }, { "code": null, "e": 574, "s": 540, "text": "[‘python’, ‘high-level language’]" }, { "code": null, "e": 587, "s": 574, "text": "Example #2 :" }, { "code": "# import TextBlobfrom textblob import TextBlob gfg = TextBlob(\"Sandeep Jain An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways.\") # using TextBlob.noun_phrases methodgfg = gfg.noun_phrases print(gfg)", "e": 854, "s": 587, "text": null }, { "code": null, "e": 863, "s": 854, "text": "Output :" }, { "code": null, "e": 930, "s": 863, "text": "[‘sandeep jain’, ‘iit roorkee’, ‘geeksforgeeks’, ‘efficient ways’]" }, { "code": null, "e": 947, "s": 930, "text": "Python-Functions" }, { "code": null, "e": 954, "s": 947, "text": "Python" }, { "code": null, "e": 1052, "s": 954, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1084, "s": 1052, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1111, "s": 1084, "text": "Python Classes and Objects" }, { "code": null, "e": 1132, "s": 1111, "text": "Python OOPs Concepts" }, { "code": null, "e": 1155, "s": 1132, "text": "Introduction To PYTHON" }, { "code": null, "e": 1211, "s": 1155, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1242, "s": 1211, "text": "Python | os.path.join() method" }, { "code": null, "e": 1284, "s": 1242, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1326, "s": 1284, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1365, "s": 1326, "text": "Python | Get unique values from a list" } ]
SQL Query to Add Unique key Constraints Using ALTER Command
29 Apr, 2021 Here we will see how to add unique key constraint to a column(s) of a MS SQL Server’s database with the help of a SQL query using ALTER clause. For the demonstration purpose, we will be creating a demo table in a database called “geeks”. Creating the Database : Use the below SQL statement to create a database called geeks: CREATE DATABASE geeks; Using the Database : Use the below SQL statement to switch the database context to geeks: USE geeks; Table Definition : We have the following demo table in our geeks database. CREATE TABLE demo( ID INT IDENTITY(1,1) PRIMARY KEY, --IDENTITY(1,1) is same as AUTO_INCREMENT in MySQL. --Starts from 1 and increases by 1 with each inserted row. NAME VARCHAR(30) NOT NULL, PHONE VARCHAR(10) NOT NULL ); You can use the below statement to query the description of the created table: EXEC SP_COLUMNS demo; Adding data to the table : Use the below statement to add data to the demo table: INSERT INTO demo --no need to mention columns explicitly as we are inserting into all columns and ID gets --automatically incremented. VALUES ('Yogesh Vaishnav', '000000001'), ('Ajit Yadav', '000000002'), ('Ashish Yadav', '000000003'), ('Vishal Vishwakarma', '000000004'), ('Suhana Shaikh', '000000005'); To verify the contents of the table use the below statement : SELECT * FROM demo; Now let’s add an unique key constraint to column phone as phone no. should be unique. NOTE: There can be multiple unique key columns but only one primary key column in a database table. Syntax for adding the unique key constraint to single as well as multiple columns is given below: Syntax : –Adding unique key constraint to a column. ALTER TABLE <table_name> ADD UNIQUE (<column_name>); –Adding unique key constraint to multiple columns ALTER TABLE <table_name> ADD CONSTRAINT <identifier_name> UNIQUE (<column_name1>, <column_name2>,...); Example : ALTER TABLE demo ADD UNIQUE (PHONE); --Let's insert a row into the table. INSERT INTO demo VALUES ('GeeksforGeeks','000000001'); --error As string ‘000000001’ already exist in the phone column which has an unique key constraint now, thus when executing the above query results into an error. Thus we can say that the unique key constraint has been successfully applied. DBMS-SQL Picked SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? Window functions in SQL SQL | Sub queries in From Clause What is Temporary Table in SQL? SQL using Python SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter RANK() Function in SQL Server SQL Query to Convert VARCHAR to INT SQL Query to Compare Two Dates SQL Query to Insert Multiple Rows
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Apr, 2021" }, { "code": null, "e": 172, "s": 28, "text": "Here we will see how to add unique key constraint to a column(s) of a MS SQL Server’s database with the help of a SQL query using ALTER clause." }, { "code": null, "e": 266, "s": 172, "text": "For the demonstration purpose, we will be creating a demo table in a database called “geeks”." }, { "code": null, "e": 290, "s": 266, "text": "Creating the Database :" }, { "code": null, "e": 353, "s": 290, "text": "Use the below SQL statement to create a database called geeks:" }, { "code": null, "e": 376, "s": 353, "text": "CREATE DATABASE geeks;" }, { "code": null, "e": 397, "s": 376, "text": "Using the Database :" }, { "code": null, "e": 466, "s": 397, "text": "Use the below SQL statement to switch the database context to geeks:" }, { "code": null, "e": 477, "s": 466, "text": "USE geeks;" }, { "code": null, "e": 496, "s": 477, "text": "Table Definition :" }, { "code": null, "e": 552, "s": 496, "text": "We have the following demo table in our geeks database." }, { "code": null, "e": 817, "s": 552, "text": "CREATE TABLE demo(\n ID INT IDENTITY(1,1) PRIMARY KEY, --IDENTITY(1,1) is same as AUTO_INCREMENT in MySQL.\n --Starts from 1 and increases by 1 with each inserted row.\n NAME VARCHAR(30) NOT NULL,\n PHONE VARCHAR(10) NOT NULL\n);" }, { "code": null, "e": 896, "s": 817, "text": "You can use the below statement to query the description of the created table:" }, { "code": null, "e": 918, "s": 896, "text": "EXEC SP_COLUMNS demo;" }, { "code": null, "e": 945, "s": 918, "text": "Adding data to the table :" }, { "code": null, "e": 1000, "s": 945, "text": "Use the below statement to add data to the demo table:" }, { "code": null, "e": 1323, "s": 1000, "text": "INSERT INTO demo --no need to mention columns explicitly as we are inserting into all columns and ID gets \n --automatically incremented.\nVALUES\n('Yogesh Vaishnav', '000000001'),\n('Ajit Yadav', '000000002'),\n('Ashish Yadav', '000000003'),\n('Vishal Vishwakarma', '000000004'),\n('Suhana Shaikh', '000000005');" }, { "code": null, "e": 1385, "s": 1323, "text": "To verify the contents of the table use the below statement :" }, { "code": null, "e": 1405, "s": 1385, "text": "SELECT * FROM demo;" }, { "code": null, "e": 1491, "s": 1405, "text": "Now let’s add an unique key constraint to column phone as phone no. should be unique." }, { "code": null, "e": 1591, "s": 1491, "text": "NOTE: There can be multiple unique key columns but only one primary key column in a database table." }, { "code": null, "e": 1689, "s": 1591, "text": "Syntax for adding the unique key constraint to single as well as multiple columns is given below:" }, { "code": null, "e": 1698, "s": 1689, "text": "Syntax :" }, { "code": null, "e": 1741, "s": 1698, "text": "–Adding unique key constraint to a column." }, { "code": null, "e": 1766, "s": 1741, "text": "ALTER TABLE <table_name>" }, { "code": null, "e": 1794, "s": 1766, "text": "ADD UNIQUE (<column_name>);" }, { "code": null, "e": 1844, "s": 1794, "text": "–Adding unique key constraint to multiple columns" }, { "code": null, "e": 1869, "s": 1844, "text": "ALTER TABLE <table_name>" }, { "code": null, "e": 1948, "s": 1869, "text": "ADD CONSTRAINT <identifier_name> UNIQUE (<column_name1>, <column_name2>,...);" }, { "code": null, "e": 1958, "s": 1948, "text": "Example :" }, { "code": null, "e": 2097, "s": 1958, "text": "ALTER TABLE demo\nADD UNIQUE (PHONE);\n\n--Let's insert a row into the table.\n\nINSERT INTO demo\nVALUES ('GeeksforGeeks','000000001'); --error" }, { "code": null, "e": 2252, "s": 2097, "text": "As string ‘000000001’ already exist in the phone column which has an unique key constraint now, thus when executing the above query results into an error." }, { "code": null, "e": 2330, "s": 2252, "text": "Thus we can say that the unique key constraint has been successfully applied." }, { "code": null, "e": 2339, "s": 2330, "text": "DBMS-SQL" }, { "code": null, "e": 2346, "s": 2339, "text": "Picked" }, { "code": null, "e": 2350, "s": 2346, "text": "SQL" }, { "code": null, "e": 2354, "s": 2350, "text": "SQL" }, { "code": null, "e": 2452, "s": 2354, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2518, "s": 2452, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 2542, "s": 2518, "text": "Window functions in SQL" }, { "code": null, "e": 2575, "s": 2542, "text": "SQL | Sub queries in From Clause" }, { "code": null, "e": 2607, "s": 2575, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 2624, "s": 2607, "text": "SQL using Python" }, { "code": null, "e": 2702, "s": 2624, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 2732, "s": 2702, "text": "RANK() Function in SQL Server" }, { "code": null, "e": 2768, "s": 2732, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 2799, "s": 2768, "text": "SQL Query to Compare Two Dates" } ]
HTML | Responsive full page image using CSS
08 Feb, 2022 Responsive Web design (RWD), a design strategy developed to cope with the amazing popularity of mobile devices for viewing the Web. Responsive images are an important component of responsive Web design (RWD), Responsive web design is a new approach to website design that ensures users have a good viewing experience no matter what type of device they’re using. Web designer Ethan Marcotte is credited with coining the term “responsive design.” In 2010, he published an article on A List Apart discussing the rapidly changing environment of devices, browsers, screen sizes, and orientations. Building separate sites for every type of device simply wouldn’t be sustainable. Instead, he proposed an alternative concept: responsive design, which calls for building flexible and fluid layouts that adapt to almost any screen. There are several frameworks used by developers to make a webpage responsive. Bootstrap Foundation Pure Skeleton Symantec A responsive Full page background image scales itself according to the user’s viewport. There are several websites that use this effect such as- sailingcollective.com sailingcollective.com Berlin Real Estate This full page background image effect can be easily added to a webpage using CSS. Example Implementation Input HTML HTML <!DOCTYPE html><head> <link rel="stylesheet" href="css/main.css"> <title>Responsive Background Example</title></head><body> <h1>Hi GFG</h1></body></html> CSS HTML body { /* Image Location */ background-image: url("../img/Fall-Nature-Background-Pictures.jpg"); /* Background image is centered vertically and horizontally at all times */ background-position: center center; background-repeat: no-repeat; background-attachment: fixed; background-size: cover; background-color: #464646; /* Font Colour */ color:white;} EXPLANATION background-size: cover; This property tells the browser to scale the background image proportionally so that its width and height are equal to, or greater than, the width/height of the element. background-position: center center; The above sets the scaling axis at the center of the viewport. background-attachment: fixed; The background is fixed with regard to the viewport OUTPUT The output shows the background image in different viewports. sagar0719kumar HTML and XML HTML-Misc Web technologies-HTML and XML 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) How to set the default value for an HTML <select> element ? 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": "\n08 Feb, 2022" }, { "code": null, "e": 877, "s": 53, "text": "Responsive Web design (RWD), a design strategy developed to cope with the amazing popularity of mobile devices for viewing the Web. Responsive images are an important component of responsive Web design (RWD), Responsive web design is a new approach to website design that ensures users have a good viewing experience no matter what type of device they’re using. Web designer Ethan Marcotte is credited with coining the term “responsive design.” In 2010, he published an article on A List Apart discussing the rapidly changing environment of devices, browsers, screen sizes, and orientations. Building separate sites for every type of device simply wouldn’t be sustainable. Instead, he proposed an alternative concept: responsive design, which calls for building flexible and fluid layouts that adapt to almost any screen. " }, { "code": null, "e": 957, "s": 877, "text": "There are several frameworks used by developers to make a webpage responsive. " }, { "code": null, "e": 967, "s": 957, "text": "Bootstrap" }, { "code": null, "e": 978, "s": 967, "text": "Foundation" }, { "code": null, "e": 983, "s": 978, "text": "Pure" }, { "code": null, "e": 992, "s": 983, "text": "Skeleton" }, { "code": null, "e": 1001, "s": 992, "text": "Symantec" }, { "code": null, "e": 1148, "s": 1001, "text": "A responsive Full page background image scales itself according to the user’s viewport. There are several websites that use this effect such as- " }, { "code": null, "e": 1170, "s": 1148, "text": "sailingcollective.com" }, { "code": null, "e": 1192, "s": 1170, "text": "sailingcollective.com" }, { "code": null, "e": 1211, "s": 1192, "text": "Berlin Real Estate" }, { "code": null, "e": 1330, "s": 1211, "text": "This full page background image effect can be easily added to a webpage using CSS. Example Implementation Input HTML " }, { "code": null, "e": 1335, "s": 1330, "text": "HTML" }, { "code": "<!DOCTYPE html><head> <link rel=\"stylesheet\" href=\"css/main.css\"> <title>Responsive Background Example</title></head><body> <h1>Hi GFG</h1></body></html>", "e": 1498, "s": 1335, "text": null }, { "code": null, "e": 1504, "s": 1498, "text": "CSS " }, { "code": null, "e": 1509, "s": 1504, "text": "HTML" }, { "code": "body { /* Image Location */ background-image: url(\"../img/Fall-Nature-Background-Pictures.jpg\"); /* Background image is centered vertically and horizontally at all times */ background-position: center center; background-repeat: no-repeat; background-attachment: fixed; background-size: cover; background-color: #464646; /* Font Colour */ color:white;}", "e": 1892, "s": 1509, "text": null }, { "code": null, "e": 2350, "s": 1892, "text": "EXPLANATION background-size: cover; This property tells the browser to scale the background image proportionally so that its width and height are equal to, or greater than, the width/height of the element. background-position: center center; The above sets the scaling axis at the center of the viewport. background-attachment: fixed; The background is fixed with regard to the viewport OUTPUT The output shows the background image in different viewports. " }, { "code": null, "e": 2371, "s": 2356, "text": "sagar0719kumar" }, { "code": null, "e": 2384, "s": 2371, "text": "HTML and XML" }, { "code": null, "e": 2394, "s": 2384, "text": "HTML-Misc" }, { "code": null, "e": 2424, "s": 2394, "text": "Web technologies-HTML and XML" }, { "code": null, "e": 2429, "s": 2424, "text": "HTML" }, { "code": null, "e": 2446, "s": 2429, "text": "Web Technologies" }, { "code": null, "e": 2451, "s": 2446, "text": "HTML" }, { "code": null, "e": 2549, "s": 2451, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2597, "s": 2549, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 2659, "s": 2597, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2709, "s": 2659, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2733, "s": 2709, "text": "REST API (Introduction)" }, { "code": null, "e": 2793, "s": 2733, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 2855, "s": 2793, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2888, "s": 2855, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2949, "s": 2888, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2999, "s": 2949, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
What is the best way to read an entire file into a std::string in C++?
This is an simple way to read an entire file into std::string in C++ Begin Take the filename as inputstream. Declare a string variable str. Read the file till the end by using rdbuf(). Put the data into st. Print the data. End. #include<iostream> #include<fstream> #include<sstream> #include<string> using namespace std; int main() { ifstream f("a.txt"); string str; if(f) { ostringstream ss; ss << f.rdbuf(); str = ss.str(); } cout<<str; } a.txt data file contains the string “hi” hi
[ { "code": null, "e": 1256, "s": 1187, "text": "This is an simple way to read an entire file into std::string in C++" }, { "code": null, "e": 1430, "s": 1256, "text": "Begin\n Take the filename as inputstream.\n Declare a string variable str.\n Read the file till the end by using rdbuf().\n Put the data into st.\n Print the data.\nEnd." }, { "code": null, "e": 1676, "s": 1430, "text": "#include<iostream>\n#include<fstream>\n#include<sstream>\n#include<string>\nusing namespace std;\nint main() {\n ifstream f(\"a.txt\");\n string str;\n if(f) {\n ostringstream ss;\n ss << f.rdbuf();\n str = ss.str();\n }\n cout<<str;\n}" }, { "code": null, "e": 1717, "s": 1676, "text": "a.txt data file contains the string “hi”" }, { "code": null, "e": 1720, "s": 1717, "text": "hi" } ]
Bootstrap Collapsible list group
To create a collapsible list group, use the panel-collapse property with list-group property. The list-group property lists items using the list-group-item property − Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet"> <script src = "/scripts/jquery.min.js"></script> <script src = "/bootstrap/js/bootstrap.min.js"></script> </head> <body> <div class = "container"> <h2>Questions/ Answers</h2> <p>Click below to learn about the technologies for which we provide Interview Questions.</p> <div class = "panel-group"> <div class = "panel panel-default"> <div class = "panel-heading"> <h4 class = "panel-title"> <a data-toggle = "collapse" href = "#test">Info</a> </h4> </div> <div id = "test" class="panel-collapse collapse"> <ul class = "list-group"> <li class = "list-group-item">Java</li> <li class = "list-group-item">PHP</li> <li class = "list-group-item">C++</li> <li class =" list-group-item">HTML5</li> <li class =" list-group-item">jQuery</li> </ul> </div> </div> </div> </div> </body> </html>
[ { "code": null, "e": 1281, "s": 1187, "text": "To create a collapsible list group, use the panel-collapse property with list-group property." }, { "code": null, "e": 1354, "s": 1281, "text": "The list-group property lists items using the list-group-item property −" }, { "code": null, "e": 1364, "s": 1354, "text": "Live Demo" }, { "code": null, "e": 2642, "s": 1364, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"container\">\n <h2>Questions/ Answers</h2>\n <p>Click below to learn about the technologies for which we provide Interview Questions.</p>\n <div class = \"panel-group\">\n <div class = \"panel panel-default\">\n <div class = \"panel-heading\">\n <h4 class = \"panel-title\">\n <a data-toggle = \"collapse\" href = \"#test\">Info</a>\n </h4>\n </div>\n <div id = \"test\" class=\"panel-collapse collapse\">\n <ul class = \"list-group\">\n <li class = \"list-group-item\">Java</li>\n <li class = \"list-group-item\">PHP</li>\n <li class = \"list-group-item\">C++</li>\n <li class =\" list-group-item\">HTML5</li>\n <li class =\" list-group-item\">jQuery</li>\n </ul>\n </div>\n </div>\n </div>\n </div>\n </body>\n</html>" } ]
Display Numpy array in Fortran order
01 Oct, 2020 Fortran order/ array is a special case in which all elements of an array are stored in column-major order. Sometimes we need to display array in fortran order, for this numpy has a function known as numpy.nditer(). Syntax: numpy.nditer(op, flags=None, op_flags=None, op_dtypes=None, order=’K’, casting=’safe’, op_axes=None, itershape=None, buffersize=0) Example 1: Python3 # importing Numpy packageimport numpy as np # creating a Numpy arraynum_array = np.arange(12).reshape(3, 4) print("Array:")print(num_array) # Display array in Fortran order# using numpy.nditer()print("\nElements of the array in Fortan array:")for num_array in np.nditer(num_array, order="F"): print(num_array, end=' ') Output: Array: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] Elements of the array in Fortan array: 0 4 8 1 5 9 2 6 10 3 7 11 Example 2: Python3 # importing Numpy package import numpy as np # creating a Numpy arraynum_array = np.arange(12).reshape(2, 6) print("Array:")print(num_array) # Display array in Fortran order # using numpy.nditer() print("\nElements of the array in Fortan array:")for num_array in np.nditer(num_array, order="F"): print(num_array,end=' ') Output: Array: [[ 0 1 2 3 4 5] [ 6 7 8 9 10 11]] Elements of the array in Fortan array: 0 6 1 7 2 8 3 9 4 10 5 11 Example 3: Python3 # importing Numpy package import numpy as np # creating a Numpy arraynum_array = np.arange(42).reshape(6, 7) print("Array:")print(num_array) # Display array in Fortran order # using numpy.nditer() print("\nElements of the array in Fortan array:")for num_array in np.nditer(num_array, order="F"): print(num_array,end=' ') Output: Array:[[ 0 1 2 3 4 5 6][ 7 8 9 10 11 12 13][14 15 16 17 18 19 20][21 22 23 24 25 26 27][28 29 30 31 32 33 34][35 36 37 38 39 40 41]] Elements of the array in Fortan array:0 7 14 21 28 35 1 8 15 22 29 36 2 9 16 23 30 37 3 10 17 24 31 38 4 11 18 25 32 39 5 12 19 26 33 40 6 13 20 27 34 41 Python numpy-arrayManipulation Python-numpy 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": "\n01 Oct, 2020" }, { "code": null, "e": 244, "s": 28, "text": "Fortran order/ array is a special case in which all elements of an array are stored in column-major order. Sometimes we need to display array in fortran order, for this numpy has a function known as numpy.nditer(). " }, { "code": null, "e": 383, "s": 244, "text": "Syntax: numpy.nditer(op, flags=None, op_flags=None, op_dtypes=None, order=’K’, casting=’safe’, op_axes=None, itershape=None, buffersize=0)" }, { "code": null, "e": 394, "s": 383, "text": "Example 1:" }, { "code": null, "e": 402, "s": 394, "text": "Python3" }, { "code": "# importing Numpy packageimport numpy as np # creating a Numpy arraynum_array = np.arange(12).reshape(3, 4) print(\"Array:\")print(num_array) # Display array in Fortran order# using numpy.nditer()print(\"\\nElements of the array in Fortan array:\")for num_array in np.nditer(num_array, order=\"F\"): print(num_array, end=' ')", "e": 727, "s": 402, "text": null }, { "code": null, "e": 735, "s": 727, "text": "Output:" }, { "code": null, "e": 853, "s": 735, "text": "Array:\n[[ 0 1 2 3]\n[ 4 5 6 7]\n[ 8 9 10 11]]\n\nElements of the array in Fortan array:\n0 4 8 1 5 9 2 6 10 3 7 11\n" }, { "code": null, "e": 864, "s": 853, "text": "Example 2:" }, { "code": null, "e": 872, "s": 864, "text": "Python3" }, { "code": "# importing Numpy package import numpy as np # creating a Numpy arraynum_array = np.arange(12).reshape(2, 6) print(\"Array:\")print(num_array) # Display array in Fortran order # using numpy.nditer() print(\"\\nElements of the array in Fortan array:\")for num_array in np.nditer(num_array, order=\"F\"): print(num_array,end=' ')", "e": 1203, "s": 872, "text": null }, { "code": null, "e": 1211, "s": 1203, "text": "Output:" }, { "code": null, "e": 1327, "s": 1211, "text": "Array:\n[[ 0 1 2 3 4 5]\n[ 6 7 8 9 10 11]]\n\nElements of the array in Fortan array:\n0 6 1 7 2 8 3 9 4 10 5 11\n" }, { "code": null, "e": 1338, "s": 1327, "text": "Example 3:" }, { "code": null, "e": 1346, "s": 1338, "text": "Python3" }, { "code": "# importing Numpy package import numpy as np # creating a Numpy arraynum_array = np.arange(42).reshape(6, 7) print(\"Array:\")print(num_array) # Display array in Fortran order # using numpy.nditer() print(\"\\nElements of the array in Fortan array:\")for num_array in np.nditer(num_array, order=\"F\"): print(num_array,end=' ')", "e": 1677, "s": 1346, "text": null }, { "code": null, "e": 1685, "s": 1677, "text": "Output:" }, { "code": null, "e": 1826, "s": 1685, "text": "Array:[[ 0 1 2 3 4 5 6][ 7 8 9 10 11 12 13][14 15 16 17 18 19 20][21 22 23 24 25 26 27][28 29 30 31 32 33 34][35 36 37 38 39 40 41]]" }, { "code": null, "e": 1980, "s": 1826, "text": "Elements of the array in Fortan array:0 7 14 21 28 35 1 8 15 22 29 36 2 9 16 23 30 37 3 10 17 24 31 38 4 11 18 25 32 39 5 12 19 26 33 40 6 13 20 27 34 41" }, { "code": null, "e": 2011, "s": 1980, "text": "Python numpy-arrayManipulation" }, { "code": null, "e": 2024, "s": 2011, "text": "Python-numpy" }, { "code": null, "e": 2031, "s": 2024, "text": "Python" }, { "code": null, "e": 2129, "s": 2031, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2161, "s": 2129, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2188, "s": 2161, "text": "Python Classes and Objects" }, { "code": null, "e": 2209, "s": 2188, "text": "Python OOPs Concepts" }, { "code": null, "e": 2232, "s": 2209, "text": "Introduction To PYTHON" }, { "code": null, "e": 2288, "s": 2232, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2319, "s": 2288, "text": "Python | os.path.join() method" }, { "code": null, "e": 2361, "s": 2319, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2403, "s": 2361, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2442, "s": 2403, "text": "Python | Get unique values from a list" } ]
MongoDB – db.collection.Find() Method
17 Feb, 2021 In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents. Cursor means a pointer that points to a document, when we use find() method it returns a pointer on the selected documents and returns one by one. If we want to return pointer on all documents then use empty() parameter that returns all documents one by one. It takes only some optional parameters. The first optional parameter is the selection criteria on which we want to return a cursor. To return all documents in a collection use empty document({}). Using this method you can also replace embedded documents. You can also use this method in multi-document transactions. If you use this method in the mongo shell, then the shell will automatically iterate the cursor to display up to 20 documents in the collection, if you want to continue then type it or you can manually iterate the result of the find() method by assigning the returned cursor to a variable with the var keyword. You can also modify the behavior of this method using cursor methods. Syntax: db.Collection_name.find(selection_criteria, projection) Optional parameters: selection_criteria: It specifies selection criteria. To return all documents in a collection use empty document({}). The type of this parameter is document. projection: It specifies the fields to return in the documents that match the selection criteria. To return all fields in the matching documents, remove this parameter. It is of the document type. This document takes: { field1: <value1>, field2: <value2> ... } Here if the value of the field is 1/true then it specifies the inclusion of the field, or if the value of the field is 0/false then it specifies the exclusion of the field. Return: It returns a cursor to the documents that match the selection criteria. When the find() method returns documents, the method is actually returning a cursor to the documents. Examples: In the following example, we are working with: Database: gfg Collections: student Document: Three documents contains the details of the students Find all the documents present in the collection: db.student.find() Find all the documents present in the collection by passing empty document: db.student.find({}) Find all the document that matches the given filter query(i.e., age:18): db.student.find({age:18}) Find the embedded document that matches the given filter query: db.student.find({score:{math: 230, science: 234}}) Display only the specified fields(Using Projection): db.student.find({},{name:1, _id:0}) Display only two documents using the limit() method: db.student.find().limit(2) MongoDB-method Picked MongoDB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Spring Boot JpaRepository with Example Mongoose Populate() Method Aggregation in MongoDB Upsert in MongoDB MongoDB - Check the existence of the fields in the specified collection How to connect MongoDB with ReactJS ? How to build a basic CRUD app with Node.js and ReactJS ? MongoDB - limit() Method Create user and add role in MongoDB MongoDB - sort() Method
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Feb, 2021" }, { "code": null, "e": 1101, "s": 28, "text": "In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents. Cursor means a pointer that points to a document, when we use find() method it returns a pointer on the selected documents and returns one by one. If we want to return pointer on all documents then use empty() parameter that returns all documents one by one. It takes only some optional parameters. The first optional parameter is the selection criteria on which we want to return a cursor. To return all documents in a collection use empty document({}). Using this method you can also replace embedded documents. You can also use this method in multi-document transactions. If you use this method in the mongo shell, then the shell will automatically iterate the cursor to display up to 20 documents in the collection, if you want to continue then type it or you can manually iterate the result of the find() method by assigning the returned cursor to a variable with the var keyword. You can also modify the behavior of this method using cursor methods." }, { "code": null, "e": 1109, "s": 1101, "text": "Syntax:" }, { "code": null, "e": 1165, "s": 1109, "text": "db.Collection_name.find(selection_criteria, projection)" }, { "code": null, "e": 1186, "s": 1165, "text": "Optional parameters:" }, { "code": null, "e": 1343, "s": 1186, "text": "selection_criteria: It specifies selection criteria. To return all documents in a collection use empty document({}). The type of this parameter is document." }, { "code": null, "e": 1540, "s": 1343, "text": "projection: It specifies the fields to return in the documents that match the selection criteria. To return all fields in the matching documents, remove this parameter. It is of the document type." }, { "code": null, "e": 1561, "s": 1540, "text": "This document takes:" }, { "code": null, "e": 1604, "s": 1561, "text": "{ field1: <value1>, field2: <value2> ... }" }, { "code": null, "e": 1777, "s": 1604, "text": "Here if the value of the field is 1/true then it specifies the inclusion of the field, or if the value of the field is 0/false then it specifies the exclusion of the field." }, { "code": null, "e": 1785, "s": 1777, "text": "Return:" }, { "code": null, "e": 1959, "s": 1785, "text": "It returns a cursor to the documents that match the selection criteria. When the find() method returns documents, the method is actually returning a cursor to the documents." }, { "code": null, "e": 1969, "s": 1959, "text": "Examples:" }, { "code": null, "e": 2016, "s": 1969, "text": "In the following example, we are working with:" }, { "code": null, "e": 2030, "s": 2016, "text": "Database: gfg" }, { "code": null, "e": 2051, "s": 2030, "text": "Collections: student" }, { "code": null, "e": 2114, "s": 2051, "text": "Document: Three documents contains the details of the students" }, { "code": null, "e": 2164, "s": 2114, "text": "Find all the documents present in the collection:" }, { "code": null, "e": 2182, "s": 2164, "text": "db.student.find()" }, { "code": null, "e": 2258, "s": 2182, "text": "Find all the documents present in the collection by passing empty document:" }, { "code": null, "e": 2278, "s": 2258, "text": "db.student.find({})" }, { "code": null, "e": 2351, "s": 2278, "text": "Find all the document that matches the given filter query(i.e., age:18):" }, { "code": null, "e": 2377, "s": 2351, "text": "db.student.find({age:18})" }, { "code": null, "e": 2441, "s": 2377, "text": "Find the embedded document that matches the given filter query:" }, { "code": null, "e": 2492, "s": 2441, "text": "db.student.find({score:{math: 230, science: 234}})" }, { "code": null, "e": 2545, "s": 2492, "text": "Display only the specified fields(Using Projection):" }, { "code": null, "e": 2581, "s": 2545, "text": "db.student.find({},{name:1, _id:0})" }, { "code": null, "e": 2634, "s": 2581, "text": "Display only two documents using the limit() method:" }, { "code": null, "e": 2661, "s": 2634, "text": "db.student.find().limit(2)" }, { "code": null, "e": 2676, "s": 2661, "text": "MongoDB-method" }, { "code": null, "e": 2683, "s": 2676, "text": "Picked" }, { "code": null, "e": 2691, "s": 2683, "text": "MongoDB" }, { "code": null, "e": 2789, "s": 2691, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2828, "s": 2789, "text": "Spring Boot JpaRepository with Example" }, { "code": null, "e": 2855, "s": 2828, "text": "Mongoose Populate() Method" }, { "code": null, "e": 2878, "s": 2855, "text": "Aggregation in MongoDB" }, { "code": null, "e": 2896, "s": 2878, "text": "Upsert in MongoDB" }, { "code": null, "e": 2968, "s": 2896, "text": "MongoDB - Check the existence of the fields in the specified collection" }, { "code": null, "e": 3006, "s": 2968, "text": "How to connect MongoDB with ReactJS ?" }, { "code": null, "e": 3063, "s": 3006, "text": "How to build a basic CRUD app with Node.js and ReactJS ?" }, { "code": null, "e": 3088, "s": 3063, "text": "MongoDB - limit() Method" }, { "code": null, "e": 3124, "s": 3088, "text": "Create user and add role in MongoDB" } ]
How to draw rectangle in Pygame?
01 Oct, 2020 Pygame is a Python library designed to develop video games. Pygame adds functionality on top of the excellent SDL library. This allows you to create fully featured games and multimedia programs in the python language. Functions Used: pygame.display.set_mode(): This function is used to initialize a surface for display. This function takes the size of the display as a parameter. pygame.display.flip(): This function is used to update the content of the entire display surface of the screen. pygame.draw.rect(): This function is used to draw a rectangle. It takes the surface, color, and pygame Rect object as an input parameter and draws a rectangle on the surface. Example 1: This example draws a rectangle that is filled with red color. Python3 # Importing the libraryimport pygame # Initializing Pygamepygame.init() # Initializing surfacesurface = pygame.display.set_mode((400,300)) # Initialing Colorcolor = (255,0,0) # Drawing Rectanglepygame.draw.rect(surface, color, pygame.Rect(30, 30, 60, 60))pygame.display.flip() Output: Example 2: This example draws a rectangle with a red border and no color-filled inside. Python3 # Importing the libraryimport pygame # Initializing Pygamepygame.init() # Initializing surfacesurface = pygame.display.set_mode((400,300)) # Initialing Colorcolor = (255,0,0) # Drawing Rectanglepygame.draw.rect(surface, color, pygame.Rect(30, 30, 60, 60), 2)pygame.display.flip() Output: Python-PyGame Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? Python Classes and Objects Iterate over a list in Python Python OOPs Concepts Convert integer to string in Python
[ { "code": null, "e": 53, "s": 25, "text": "\n01 Oct, 2020" }, { "code": null, "e": 271, "s": 53, "text": "Pygame is a Python library designed to develop video games. Pygame adds functionality on top of the excellent SDL library. This allows you to create fully featured games and multimedia programs in the python language." }, { "code": null, "e": 288, "s": 271, "text": "Functions Used:" }, { "code": null, "e": 434, "s": 288, "text": "pygame.display.set_mode(): This function is used to initialize a surface for display. This function takes the size of the display as a parameter." }, { "code": null, "e": 546, "s": 434, "text": "pygame.display.flip(): This function is used to update the content of the entire display surface of the screen." }, { "code": null, "e": 721, "s": 546, "text": "pygame.draw.rect(): This function is used to draw a rectangle. It takes the surface, color, and pygame Rect object as an input parameter and draws a rectangle on the surface." }, { "code": null, "e": 794, "s": 721, "text": "Example 1: This example draws a rectangle that is filled with red color." }, { "code": null, "e": 802, "s": 794, "text": "Python3" }, { "code": "# Importing the libraryimport pygame # Initializing Pygamepygame.init() # Initializing surfacesurface = pygame.display.set_mode((400,300)) # Initialing Colorcolor = (255,0,0) # Drawing Rectanglepygame.draw.rect(surface, color, pygame.Rect(30, 30, 60, 60))pygame.display.flip()", "e": 1083, "s": 802, "text": null }, { "code": null, "e": 1091, "s": 1083, "text": "Output:" }, { "code": null, "e": 1179, "s": 1091, "text": "Example 2: This example draws a rectangle with a red border and no color-filled inside." }, { "code": null, "e": 1187, "s": 1179, "text": "Python3" }, { "code": "# Importing the libraryimport pygame # Initializing Pygamepygame.init() # Initializing surfacesurface = pygame.display.set_mode((400,300)) # Initialing Colorcolor = (255,0,0) # Drawing Rectanglepygame.draw.rect(surface, color, pygame.Rect(30, 30, 60, 60), 2)pygame.display.flip()", "e": 1472, "s": 1187, "text": null }, { "code": null, "e": 1480, "s": 1472, "text": "Output:" }, { "code": null, "e": 1494, "s": 1480, "text": "Python-PyGame" }, { "code": null, "e": 1501, "s": 1494, "text": "Python" }, { "code": null, "e": 1599, "s": 1501, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1617, "s": 1599, "text": "Python Dictionary" }, { "code": null, "e": 1659, "s": 1617, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1681, "s": 1659, "text": "Enumerate() in Python" }, { "code": null, "e": 1716, "s": 1681, "text": "Read a file line by line in Python" }, { "code": null, "e": 1742, "s": 1716, "text": "Python String | replace()" }, { "code": null, "e": 1774, "s": 1742, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1801, "s": 1774, "text": "Python Classes and Objects" }, { "code": null, "e": 1831, "s": 1801, "text": "Iterate over a list in Python" }, { "code": null, "e": 1852, "s": 1831, "text": "Python OOPs Concepts" } ]
Ishaan and Sticks | Practice | GeeksforGeeks
Ishaan has a craving for sticks. He has N sticks. He observes that some of his sticks are of the same length, and thus he can make squares out of those. He wants to know how big a square he can make using those sticks as sides. Since the number of sticks is large, he can't do that manually. Can you tell him the maximum area of the biggest square that can be formed? Also, calculate how many such squares can be made using the sticks. Example 1: ​Input : arr[ ] = {2, 2, 2, 9, 2, 2, 2, 2, 2} Output : 4 2 Explanation: 2 squares of side 2 are formed. return maximum area and number of square. ​Example 2: Input : arr[ ] = {5, 3, 2, 3, 6, 3, 3} Output : 9 1 Your Task: This is a function problem. The input is already taken care of by the driver code. You only need to complete the function square() that takes an array (arr), sizeOfArray (n) and return the array of the maximum area of the largest square that can be formed and the number of squares that can be formed if there is no possible square return -1. The driver code takes care of the printing. Expected Time Complexity: O(N). Expected Auxiliary Space: O(M), where M is the maximum value of an array. Constraints : 1 ≤ N ≤ 105 1 ≤ arri ≤ 103 0 rohitsingh0000654 months ago JAVA SOLUTION USING HASHMAP EASY public static ArrayList<Integer> square (int arr[], int n) { HashMap<Integer,Integer> map = new HashMap<>(); for(int el : arr){ map.put(el , map.getOrDefault(el,0) + 1); } ArrayList<Integer> ans = new ArrayList<>(); int max = 0, side = 0; for(int key : map.keySet()){ if(map.get(key) >= 4){ int carea = key; if(max < carea * carea){ max = carea * carea; side = map.get(key)/4; } } } if(max==0){ ans.add(-1); return ans; } ans.add(max); ans.add(side); return ans; } 0 nmnishant5 months ago C++ Solution : Clean Codevector<int> square(int arr[], int n){ unordered_map<int, int> map; for(int i=0; i<n; i++){ map[arr[i]] += 1; } int squares = 0; int maxArea = -1; for(auto i : map){ int side = i.first; int count = i.second; if(count >=4 && side * side > maxArea) { squares = count/4; maxArea = side*side; } } vector<int> ans = {maxArea}; if(squares) ans.push_back(squares); return ans;} +1 rohanpandey7496 months ago C++ solution: vector<int> square(int arr[], int n) { // Complete the function map<int,int>mp; int fre=0; int ele=0; for(int i=0;i<n;i++){ mp[arr[i]]++; } for(auto it:mp){ if(it.second>=4){ fre=it.second/4; ele=it.first; } } vector<int>answer; if(fre==0 && ele==0){ answer.push_back(-1); } else{ answer.push_back((ele*ele)); answer.push_back((fre)); } return answer; } +1 hanumanmanyam8376 months ago vector<int> square(int arr[], int n){ // Complete the function vector<int>res; int max_len=0; int squares=0; unordered_map<int,int>map; for(int i=0;i<n;i++) { map[arr[i]]++; } for(int i=0;i<n;i++) { if(map[arr[i]]>=4) { if(arr[i]>max_len) { max_len=arr[i]; squares=map[arr[i]]/4; } } } if(squares==0) { res.push_back(-1); return res; } res.push_back(max_len*max_len); res.push_back(squares); return res;} 0 shreechandan_96 months ago vector<int> square(int arr[], int n) { // Complete the function sort(arr,arr+n); int area=0,count=0; for(int i=0;i<n;i++) { if(i+3<n&&arr[i]==arr[i+3]) { if(area==arr[i]*arr[i+3]) count++; else { area=arr[i]*arr[i+3]; count=1; } i=i+3; } } if(count==0) return {-1}; return {area,count}; } +1 badgujarsachin837 months ago vector<int> square(int arr[], int n) { vector<int> v; if(n<4){ v.push_back(-1); return v; } unordered_map<int,int> mp; for(int i=0;i<n;i++){ mp[arr[i]]++; } int count=0; int area=0; for(auto it:mp){ if(it.second/4>0 && it.first*it.first>area){ count=it.second/4; area=max(area,it.first*it.first); } } if(count==0){ v.push_back(-1); return v; }else{ v.push_back(area); v.push_back(count); } return v; } -1 HARSH MEGHANI11 months agohttps://uploads.disquscdn.c...Reply Open ExternallyShow 0 RepliesLoading... HARSH MEGHANI https://uploads.disquscdn.c... 0 Ashman Jagdev1 year agohttps://uploads.disquscdn.c...Reply Open ExternallyShow 0 RepliesLoading... Ashman Jagdev https://uploads.disquscdn.c... -1 Aniket patel1 year agohttps://practice.geeksforge...Reply Open ExternallyShow 0 RepliesLoading... Aniket patel https://practice.geeksforge... -1 Drigger1 year agosol in java: https://ide.geeksforgeeks.o...Reply Open ExternallyShow 0 RepliesLoading... Drigger sol in java: https://ide.geeksforgeeks.o... We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
[ { "code": null, "e": 662, "s": 226, "text": "Ishaan has a craving for sticks. He has N sticks. He observes that some of his sticks are of the same length, and thus he can make squares out of those.\nHe wants to know how big a square he can make using those sticks as sides. Since the number of sticks is large, he can't do that manually. Can you tell him the maximum area of the biggest square that can be formed?\nAlso, calculate how many such squares can be made using the sticks." }, { "code": null, "e": 675, "s": 664, "text": "Example 1:" }, { "code": null, "e": 825, "s": 675, "text": "​Input : arr[ ] = {2, 2, 2, 9, 2, 2, 2, 2, 2}\nOutput : 4 2\nExplanation:\n2 squares of side 2 are formed.\nreturn maximum area and number of square.\n" }, { "code": null, "e": 841, "s": 825, "text": "\n​Example 2:" }, { "code": null, "e": 895, "s": 841, "text": "Input : arr[ ] = {5, 3, 2, 3, 6, 3, 3} \nOutput : 9 1" }, { "code": null, "e": 1295, "s": 897, "text": "Your Task:\nThis is a function problem. The input is already taken care of by the driver code. You only need to complete the function square() that takes an array (arr), sizeOfArray (n) and return the array of the maximum area of the largest square that can be formed and the number of squares that can be formed if there is no possible square return -1. The driver code takes care of the printing." }, { "code": null, "e": 1404, "s": 1295, "text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(M), where M is the maximum value of an array.\n\n " }, { "code": null, "e": 1446, "s": 1404, "text": "Constraints : \n1 ≤ N ≤ 105\n1 ≤ arri ≤ 103" }, { "code": null, "e": 1448, "s": 1446, "text": "0" }, { "code": null, "e": 1477, "s": 1448, "text": "rohitsingh0000654 months ago" }, { "code": null, "e": 1510, "s": 1477, "text": "JAVA SOLUTION USING HASHMAP EASY" }, { "code": null, "e": 2182, "s": 1512, "text": " public static ArrayList<Integer> square (int arr[], int n) {\n HashMap<Integer,Integer> map = new HashMap<>();\n for(int el : arr){\n map.put(el , map.getOrDefault(el,0) + 1);\n }\n ArrayList<Integer> ans = new ArrayList<>();\n int max = 0, side = 0;\n for(int key : map.keySet()){\n if(map.get(key) >= 4){\n int carea = key;\n if(max < carea * carea){\n max = carea * carea;\n side = map.get(key)/4;\n }\n }\n }\n if(max==0){\n ans.add(-1);\n return ans;\n }\n ans.add(max);\n ans.add(side);\n return ans;\n }" }, { "code": null, "e": 2184, "s": 2182, "text": "0" }, { "code": null, "e": 2206, "s": 2184, "text": "nmnishant5 months ago" }, { "code": null, "e": 2687, "s": 2206, "text": "C++ Solution : Clean Codevector<int> square(int arr[], int n){ unordered_map<int, int> map; for(int i=0; i<n; i++){ map[arr[i]] += 1; } int squares = 0; int maxArea = -1; for(auto i : map){ int side = i.first; int count = i.second; if(count >=4 && side * side > maxArea) { squares = count/4; maxArea = side*side; } } vector<int> ans = {maxArea}; if(squares) ans.push_back(squares); return ans;} " }, { "code": null, "e": 2690, "s": 2687, "text": "+1" }, { "code": null, "e": 2717, "s": 2690, "text": "rohanpandey7496 months ago" }, { "code": null, "e": 2731, "s": 2717, "text": "C++ solution:" }, { "code": null, "e": 3214, "s": 2731, "text": "vector<int> square(int arr[], int n)\n{\n // Complete the function\n map<int,int>mp;\n int fre=0;\n int ele=0;\n for(int i=0;i<n;i++){\n mp[arr[i]]++;\n }\n for(auto it:mp){\n if(it.second>=4){\n fre=it.second/4;\n ele=it.first;\n }\n }\n vector<int>answer;\n if(fre==0 && ele==0){\n answer.push_back(-1);\n }\n else{\n answer.push_back((ele*ele));\n answer.push_back((fre));\n }\n return answer;\n}\n" }, { "code": null, "e": 3217, "s": 3214, "text": "+1" }, { "code": null, "e": 3246, "s": 3217, "text": "hanumanmanyam8376 months ago" }, { "code": null, "e": 3779, "s": 3246, "text": "vector<int> square(int arr[], int n){ // Complete the function vector<int>res; int max_len=0; int squares=0; unordered_map<int,int>map; for(int i=0;i<n;i++) { map[arr[i]]++; } for(int i=0;i<n;i++) { if(map[arr[i]]>=4) { if(arr[i]>max_len) { max_len=arr[i]; squares=map[arr[i]]/4; } } } if(squares==0) { res.push_back(-1); return res; } res.push_back(max_len*max_len); res.push_back(squares); return res;}" }, { "code": null, "e": 3781, "s": 3779, "text": "0" }, { "code": null, "e": 3808, "s": 3781, "text": "shreechandan_96 months ago" }, { "code": null, "e": 4269, "s": 3808, "text": "vector<int> square(int arr[], int n)\n{\n // Complete the function\n sort(arr,arr+n);\n int area=0,count=0;\n for(int i=0;i<n;i++)\n {\n if(i+3<n&&arr[i]==arr[i+3])\n {\n if(area==arr[i]*arr[i+3])\n count++;\n else\n {\n area=arr[i]*arr[i+3];\n count=1;\n }\n i=i+3;\n }\n }\n if(count==0)\n return {-1};\n return {area,count};\n}" }, { "code": null, "e": 4272, "s": 4269, "text": "+1" }, { "code": null, "e": 4301, "s": 4272, "text": "badgujarsachin837 months ago" }, { "code": null, "e": 4861, "s": 4301, "text": "vector<int> square(int arr[], int n)\n{\n vector<int> v;\n if(n<4){\n v.push_back(-1);\n return v;\n }\n unordered_map<int,int> mp;\n for(int i=0;i<n;i++){\n mp[arr[i]]++;\n }\n int count=0;\n int area=0;\n for(auto it:mp){\n if(it.second/4>0 && it.first*it.first>area){\n count=it.second/4;\n area=max(area,it.first*it.first);\n }\n }\n \n if(count==0){\n v.push_back(-1);\n return v;\n }else{\n v.push_back(area);\n v.push_back(count);\n }\n return v;\n}\n" }, { "code": null, "e": 4864, "s": 4861, "text": "-1" }, { "code": null, "e": 4966, "s": 4864, "text": "HARSH MEGHANI11 months agohttps://uploads.disquscdn.c...Reply Open ExternallyShow 0 RepliesLoading..." }, { "code": null, "e": 4980, "s": 4966, "text": "HARSH MEGHANI" }, { "code": null, "e": 5011, "s": 4980, "text": "https://uploads.disquscdn.c..." }, { "code": null, "e": 5013, "s": 5011, "text": "0" }, { "code": null, "e": 5112, "s": 5013, "text": "Ashman Jagdev1 year agohttps://uploads.disquscdn.c...Reply Open ExternallyShow 0 RepliesLoading..." }, { "code": null, "e": 5126, "s": 5112, "text": "Ashman Jagdev" }, { "code": null, "e": 5157, "s": 5126, "text": "https://uploads.disquscdn.c..." }, { "code": null, "e": 5160, "s": 5157, "text": "-1" }, { "code": null, "e": 5258, "s": 5160, "text": "Aniket patel1 year agohttps://practice.geeksforge...Reply Open ExternallyShow 0 RepliesLoading..." }, { "code": null, "e": 5271, "s": 5258, "text": "Aniket patel" }, { "code": null, "e": 5302, "s": 5271, "text": "https://practice.geeksforge..." }, { "code": null, "e": 5305, "s": 5302, "text": "-1" }, { "code": null, "e": 5411, "s": 5305, "text": "Drigger1 year agosol in java: https://ide.geeksforgeeks.o...Reply Open ExternallyShow 0 RepliesLoading..." }, { "code": null, "e": 5419, "s": 5411, "text": "Drigger" }, { "code": null, "e": 5463, "s": 5419, "text": "sol in java: https://ide.geeksforgeeks.o..." }, { "code": null, "e": 5609, "s": 5463, "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": 5645, "s": 5609, "text": " Login to access your submissions. " }, { "code": null, "e": 5655, "s": 5645, "text": "\nProblem\n" }, { "code": null, "e": 5665, "s": 5655, "text": "\nContest\n" }, { "code": null, "e": 5728, "s": 5665, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5913, "s": 5728, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 6197, "s": 5913, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 6343, "s": 6197, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 6420, "s": 6343, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 6461, "s": 6420, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 6489, "s": 6461, "text": "Disable browser extensions." }, { "code": null, "e": 6560, "s": 6489, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 6747, "s": 6560, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
How to generate XML documents with namespaces in Python?
Currently you cannot add namespaces to XML documents directly as it is not yet supported in the in built Python xml package. So you will need to add namespace as a normal attribute to the tag. For example, import xml.dom.minidom doc = xml.dom.minidom.Document() element = doc.createElementNS('http://hello.world/ns', 'ex:el') element.setAttribute("xmlns:ex", "http://hello.world/ns") doc.appendChild(element) print(doc.toprettyxml()) This will give you the document, <?xml version="1.0" ?> <ex:el xmlns:ex="http://example.net/ns"/>
[ { "code": null, "e": 1268, "s": 1062, "text": "Currently you cannot add namespaces to XML documents directly as it is not yet supported in the in built Python xml package. So you will need to add namespace as a normal attribute to the tag. For example," }, { "code": null, "e": 1496, "s": 1268, "text": "import xml.dom.minidom\ndoc = xml.dom.minidom.Document()\nelement = doc.createElementNS('http://hello.world/ns', 'ex:el')\nelement.setAttribute(\"xmlns:ex\", \"http://hello.world/ns\")\ndoc.appendChild(element)\nprint(doc.toprettyxml())" }, { "code": null, "e": 1529, "s": 1496, "text": "This will give you the document," }, { "code": null, "e": 1594, "s": 1529, "text": "<?xml version=\"1.0\" ?>\n<ex:el xmlns:ex=\"http://example.net/ns\"/>" } ]
A/B Testing in R. What is A/B Testing? | by Sheenal Srivastava | Towards Data Science
A/B testing is a method used to test whether the response rate is different for two variants of the same feature. For instance, you may want to test whether a specific change to your website like moving the shopping cart button to the top right hand corner of your web page instead of on the right hand panel changes the number of people that click on the shopping cart and buy a product. A/B testing is also called split testing where two variants of the same web page are shown to different samples from your population of visitors to the website at the same time. Then, the number of conversions are compared for the two variants. Generally, the variant that gives a higher proportion of variants is the winning variant. However, as this is a data science blog, we want to ensure that the difference in proportion of conversions for the two variants is statistically significant. We may also want to understand what attributes of the visitors is driving those conversions. So, let’s move on to your data problem. An A/B test was recently run and the Product Manager of your company wants to know whether the new variant of the web page resulted in more conversions. Make a recommendation to your Product Manager based on your analysis The CRM Manager is interested in knowing how accurately we can predict whether users are likely to engage with our emails based on the attributes we collected about the users when they first visit the website. Report back to the CRM Manager on your findings. Four datasets are provided. Visits contains data from 10,000 unique users and has the following columns: user_id: unique identifier for the user visit_time: timestamp indicating date and time of visit to website channel: marketing channel that prompted the user to visit the website age: user’s age at time of visiting website gender: user’s gender Email engagement contains data on those users that engaged with a recent email campaign. The file contains the following columns: user_id: unique identifier for the user clicked_on_email: flag to indicate that the user engaged with the email where 1 indicates that the user clicked on the email Variations contains data indicating which of the variations each user saw of the A/B test. The file has the following columns: user_id: unique identifier for the user variation: variation (control or treatment) that the user saw Test conversions contains data on those users that converted as a result of the A/B test. The file contains the following columns: user_id: unique identifier for the user converted: flag to indicate that the user converted (1 for converted I always start by first combining the files using a primary key or a unique identifier. I then decide what to do with the data. I find this approach useful as I can get rid of what I don’t need later. It also helps me view the dataset on a holistic level. In this instance, our unique identifier is user_id. After merging the files using the following code, merge_1<-merge(variations_df,visits_df,by.x="user_id",by.y="user_id") merge_2<-merge(merge_1,test_conv_df,by.x="user_id",by.y="user_id",all.x=TRUE) merge_3<-merge(merge_2,eng_df,by.x="user_id",by.y="user_id",all.x=TRUE) I discovered that I had to create my own binary variable for whether or not a user converted and whether or not they had clicked on an email. This was based on their user ID not being found in the test_conversions.csv and email_engagement.csv files. I did this by replacing all “NA”s with 0's. merge_3$converted<-if_else(is.na(merge_3$converted),0,1) merge_3$clicked_on_email<-if_else(is.na(merge_3$clicked_on_email),0,1) merge_3$converted<-as.factor(merge_3$converted) merge_3$clicked_on_email<-as.factor(merge_3$clicked_on_email) The next task was to convert variables like visit time into information that would provide meaningful information on the users. merge_3$timeofday<- mapvalues(hour(merge_3$visit_time),from=c(0:23), to=c(rep("night",times=5), rep("morning",times=6),rep("afternoon",times=5),rep("night", times=8))) merge_3$timeofday<-as.factor(merge_3$timeofday) Now, that the data had been cleaned it was time to explore the data to understand whether there was an association between user conversion and the variation they visited on the website. The simplest aspect of the data to check for is to determine whether there is indeed a difference in the proportion of users that converted based on the type of variation they viewed. Running the code provided at the end of the blog post gives the following graph and proportions: control : 0.20 treatment : 0.24 To test whether the difference in proportions is statistically significant, we can either carry out a difference in proportions test or a chi-squared test of independence where the null hypothesis is that there is no association between whether or not a user converted and the type of variation they visited. For both tests, a p-value < 0.05 was observed indicating a statistically significant difference in proportions. I went a step further and ran logistic regression to understand how the other attributes of the users contributed to the difference in proportions. Only the type of variation and income (p-values less than 0.05) appeared to contribute to the difference in conversion proportions. A calculation of McFadden’s R-squared tells us that only 12.94% of the variation in proportions can be explained by the variation type and user attributes provided within our dataset. Hence, my response to the Product Manager would be as follows: There is a statistically significant difference in conversion rates for those that visited the treatment variation vs the control variation. However, it is difficult to understand why this is the case. It would be best to repeat this test 2–3 more times to cross-validate results. Barplots were produced to check for a visual relationship between user attributes and whether or not they clicked on an email. While running the exploratory data analysis, I noticed that the age was missing for 1,243 users. These users were omitted from analysis as I cannot impute their ages without any knowledge. Boxplots and numerical summaries were produced to understand any difference in average age of users that clicked on emails. It was found that those that clicked on emails (“1”) on average had higher income than those that didn’t. However, both groups have very high standard deviations, thus income does not appear to be a useful indicator. The dataset was randomly split into training (70%) and test (30%) sets for modelling. Logistic regression was run to determine which attributes had a statistically significant contribution in explaining whether users clicked or did not click on an email. The model was trained on the training set and predictions were carried out on the test set for accuracy. An ROC curve was generated by plotting the true positive rate (TPR) against the false positive rate (FPR) at various threshold settings. The AUC is the area under the ROC curve. As a rule of thumb, a model with good predictive ability should have an AUC closer to 1 (1 is ideal) than to 0.5. In our example, we have an AUC of 0.84, showing pretty good accuracy. Though the score is good, it would be good to carry out some form of cross-validation to validate the results further and ensure reproducibility. A summary of the logistic regression model confirms what we saw visually that the top predictors of the likelihood of a user clicking on an email are: - channel - age - gender My response to the CRM Manager would be that the top predictors of email conversion are age (older users are more likely to click), channel (PPC being popular amongst users that click) and gender (males are more likely to click than females). However, I would like to validate these results via a larger sample to allow for cross-validation. Hopefully, this blog post has demystified A/B testing to some extent, given you some ways to test for statistical significance and shown you how exploratory data analysis and statistical testing work together to validate results. Please note that a very small sample size was used in this example (around 4000 users) and as such it did not make sense to run and train a complex machine learning algorithm. I would love your feedback and suggestions and all useful code is provided below and on github for download. :)
[ { "code": null, "e": 560, "s": 171, "text": "A/B testing is a method used to test whether the response rate is different for two variants of the same feature. For instance, you may want to test whether a specific change to your website like moving the shopping cart button to the top right hand corner of your web page instead of on the right hand panel changes the number of people that click on the shopping cart and buy a product." }, { "code": null, "e": 895, "s": 560, "text": "A/B testing is also called split testing where two variants of the same web page are shown to different samples from your population of visitors to the website at the same time. Then, the number of conversions are compared for the two variants. Generally, the variant that gives a higher proportion of variants is the winning variant." }, { "code": null, "e": 1187, "s": 895, "text": "However, as this is a data science blog, we want to ensure that the difference in proportion of conversions for the two variants is statistically significant. We may also want to understand what attributes of the visitors is driving those conversions. So, let’s move on to your data problem." }, { "code": null, "e": 1409, "s": 1187, "text": "An A/B test was recently run and the Product Manager of your company wants to know whether the new variant of the web page resulted in more conversions. Make a recommendation to your Product Manager based on your analysis" }, { "code": null, "e": 1668, "s": 1409, "text": "The CRM Manager is interested in knowing how accurately we can predict whether users are likely to engage with our emails based on the attributes we collected about the users when they first visit the website. Report back to the CRM Manager on your findings." }, { "code": null, "e": 1696, "s": 1668, "text": "Four datasets are provided." }, { "code": null, "e": 1773, "s": 1696, "text": "Visits contains data from 10,000 unique users and has the following columns:" }, { "code": null, "e": 1813, "s": 1773, "text": "user_id: unique identifier for the user" }, { "code": null, "e": 1880, "s": 1813, "text": "visit_time: timestamp indicating date and time of visit to website" }, { "code": null, "e": 1951, "s": 1880, "text": "channel: marketing channel that prompted the user to visit the website" }, { "code": null, "e": 1995, "s": 1951, "text": "age: user’s age at time of visiting website" }, { "code": null, "e": 2017, "s": 1995, "text": "gender: user’s gender" }, { "code": null, "e": 2147, "s": 2017, "text": "Email engagement contains data on those users that engaged with a recent email campaign. The file contains the following columns:" }, { "code": null, "e": 2187, "s": 2147, "text": "user_id: unique identifier for the user" }, { "code": null, "e": 2312, "s": 2187, "text": "clicked_on_email: flag to indicate that the user engaged with the email where 1 indicates that the user clicked on the email" }, { "code": null, "e": 2439, "s": 2312, "text": "Variations contains data indicating which of the variations each user saw of the A/B test. The file has the following columns:" }, { "code": null, "e": 2479, "s": 2439, "text": "user_id: unique identifier for the user" }, { "code": null, "e": 2541, "s": 2479, "text": "variation: variation (control or treatment) that the user saw" }, { "code": null, "e": 2672, "s": 2541, "text": "Test conversions contains data on those users that converted as a result of the A/B test. The file contains the following columns:" }, { "code": null, "e": 2712, "s": 2672, "text": "user_id: unique identifier for the user" }, { "code": null, "e": 2781, "s": 2712, "text": "converted: flag to indicate that the user converted (1 for converted" }, { "code": null, "e": 3037, "s": 2781, "text": "I always start by first combining the files using a primary key or a unique identifier. I then decide what to do with the data. I find this approach useful as I can get rid of what I don’t need later. It also helps me view the dataset on a holistic level." }, { "code": null, "e": 3139, "s": 3037, "text": "In this instance, our unique identifier is user_id. After merging the files using the following code," }, { "code": null, "e": 3363, "s": 3139, "text": "merge_1<-merge(variations_df,visits_df,by.x=\"user_id\",by.y=\"user_id\") merge_2<-merge(merge_1,test_conv_df,by.x=\"user_id\",by.y=\"user_id\",all.x=TRUE) merge_3<-merge(merge_2,eng_df,by.x=\"user_id\",by.y=\"user_id\",all.x=TRUE)" }, { "code": null, "e": 3657, "s": 3363, "text": "I discovered that I had to create my own binary variable for whether or not a user converted and whether or not they had clicked on an email. This was based on their user ID not being found in the test_conversions.csv and email_engagement.csv files. I did this by replacing all “NA”s with 0's." }, { "code": null, "e": 3901, "s": 3657, "text": "merge_3$converted<-if_else(is.na(merge_3$converted),0,1) merge_3$clicked_on_email<-if_else(is.na(merge_3$clicked_on_email),0,1) merge_3$converted<-as.factor(merge_3$converted) merge_3$clicked_on_email<-as.factor(merge_3$clicked_on_email)" }, { "code": null, "e": 4029, "s": 3901, "text": "The next task was to convert variables like visit time into information that would provide meaningful information on the users." }, { "code": null, "e": 4264, "s": 4029, "text": "merge_3$timeofday<- mapvalues(hour(merge_3$visit_time),from=c(0:23), to=c(rep(\"night\",times=5), rep(\"morning\",times=6),rep(\"afternoon\",times=5),rep(\"night\", times=8))) merge_3$timeofday<-as.factor(merge_3$timeofday)" }, { "code": null, "e": 4450, "s": 4264, "text": "Now, that the data had been cleaned it was time to explore the data to understand whether there was an association between user conversion and the variation they visited on the website." }, { "code": null, "e": 4731, "s": 4450, "text": "The simplest aspect of the data to check for is to determine whether there is indeed a difference in the proportion of users that converted based on the type of variation they viewed. Running the code provided at the end of the blog post gives the following graph and proportions:" }, { "code": null, "e": 4763, "s": 4731, "text": "control : 0.20 treatment : 0.24" }, { "code": null, "e": 5072, "s": 4763, "text": "To test whether the difference in proportions is statistically significant, we can either carry out a difference in proportions test or a chi-squared test of independence where the null hypothesis is that there is no association between whether or not a user converted and the type of variation they visited." }, { "code": null, "e": 5184, "s": 5072, "text": "For both tests, a p-value < 0.05 was observed indicating a statistically significant difference in proportions." }, { "code": null, "e": 5711, "s": 5184, "text": "I went a step further and ran logistic regression to understand how the other attributes of the users contributed to the difference in proportions. Only the type of variation and income (p-values less than 0.05) appeared to contribute to the difference in conversion proportions. A calculation of McFadden’s R-squared tells us that only 12.94% of the variation in proportions can be explained by the variation type and user attributes provided within our dataset. Hence, my response to the Product Manager would be as follows:" }, { "code": null, "e": 5992, "s": 5711, "text": "There is a statistically significant difference in conversion rates for those that visited the treatment variation vs the control variation. However, it is difficult to understand why this is the case. It would be best to repeat this test 2–3 more times to cross-validate results." }, { "code": null, "e": 6119, "s": 5992, "text": "Barplots were produced to check for a visual relationship between user attributes and whether or not they clicked on an email." }, { "code": null, "e": 6432, "s": 6119, "text": "While running the exploratory data analysis, I noticed that the age was missing for 1,243 users. These users were omitted from analysis as I cannot impute their ages without any knowledge. Boxplots and numerical summaries were produced to understand any difference in average age of users that clicked on emails." }, { "code": null, "e": 6649, "s": 6432, "text": "It was found that those that clicked on emails (“1”) on average had higher income than those that didn’t. However, both groups have very high standard deviations, thus income does not appear to be a useful indicator." }, { "code": null, "e": 6904, "s": 6649, "text": "The dataset was randomly split into training (70%) and test (30%) sets for modelling. Logistic regression was run to determine which attributes had a statistically significant contribution in explaining whether users clicked or did not click on an email." }, { "code": null, "e": 7371, "s": 6904, "text": "The model was trained on the training set and predictions were carried out on the test set for accuracy. An ROC curve was generated by plotting the true positive rate (TPR) against the false positive rate (FPR) at various threshold settings. The AUC is the area under the ROC curve. As a rule of thumb, a model with good predictive ability should have an AUC closer to 1 (1 is ideal) than to 0.5. In our example, we have an AUC of 0.84, showing pretty good accuracy." }, { "code": null, "e": 7517, "s": 7371, "text": "Though the score is good, it would be good to carry out some form of cross-validation to validate the results further and ensure reproducibility." }, { "code": null, "e": 7668, "s": 7517, "text": "A summary of the logistic regression model confirms what we saw visually that the top predictors of the likelihood of a user clicking on an email are:" }, { "code": null, "e": 7678, "s": 7668, "text": "- channel" }, { "code": null, "e": 7684, "s": 7678, "text": "- age" }, { "code": null, "e": 7693, "s": 7684, "text": "- gender" }, { "code": null, "e": 8035, "s": 7693, "text": "My response to the CRM Manager would be that the top predictors of email conversion are age (older users are more likely to click), channel (PPC being popular amongst users that click) and gender (males are more likely to click than females). However, I would like to validate these results via a larger sample to allow for cross-validation." }, { "code": null, "e": 8265, "s": 8035, "text": "Hopefully, this blog post has demystified A/B testing to some extent, given you some ways to test for statistical significance and shown you how exploratory data analysis and statistical testing work together to validate results." }, { "code": null, "e": 8441, "s": 8265, "text": "Please note that a very small sample size was used in this example (around 4000 users) and as such it did not make sense to run and train a complex machine learning algorithm." } ]
DeepDiff — Recursively Find and Ignore Trivial Differences Using Python | by Khuyen Tran | Towards Data Science
When comparing two Python objects, you might not want the test to focus on some trivial differences such as the order of the values in a list. For example, you might want the test to consider[3, 2] to be the same as [2, 3] . However, you get an error when the order is different. Is there a way that you can ignore the order when comparing two Python objects? That is when DeepDiff comes in handy. In this article, you will learn how to use DeepDiff to prevent comparing certain parts of Python objects. DeepDiff is a Python library that recursively looks for all the changes in dictionaries, iterables, strings, and other objects. To install DeepDiff, type: pip install deepdiff When comparing between two different Python objects using assert , you might get an error similar to below: AssertionError: assert {'apple': 2, 'banana': [3, 2, 2], 'orange': 3} == {'apple': 2, 'banana': [3, 2], 'orange': 3} This assertion error is not very informative since we don’t know the exact elements that make these two dictionaries different. With DeepDiff, we can see a more descriptive error showing what the differences are and where the differences occur. From the error above, we know three things: One item in price1 is removed in price2 . The removed item is at price1['banana'][2]. The value of the removed item is 2 . The default view of DeepDiff is "text" . To change the view into a tree view, use view="tree" . In the tree view, you can traverse through the tree and see what items were compared to each other. As shown at the beginning of the article, you can ignore the order using ignore_order=True : The output {} shows that there is no difference between two Python objects. You can also use ignore_order=True to ignore duplicates: It can be annoying to see the assertion error when two numbers are very close to each other. If you want to ignore the difference between two numbers after a particular digit, use significant_digits . In the code below, we only compare the two numbers up to the second digit. Sometimes, two numbers are very close, but they don’t have similar digits. To ignore small differences between two numbers, use math_epsilon . In the code below, I use math_epsilon=0.001 to tell DeepDiff to ignore the difference that is smaller than 0.001. Since the difference between 1 and 0.9999 is 0.0001, the difference is ignored. If you want to ignore string case (.i.e, “Red” and “red”), use ignore_string_case=True . If you have worked with some NaNs, you might know that not every NaNs in Python are equal: Thus, it can be confusing to compare objects that contain different types of NaNs. (Isn’t [nan, 1, 2] equal to [nan, 1, 2] ?) To ignore different types of NaNs, use ignore_nan_inequality=True : Sometimes, you might not care if certain types change or not. To include certain data types, use exclude_types : 2 != 2.0 since 2 is an integer and 2.0 is a float. You can ignore variation in numeric type using ignore_numeric_type_changes=True . When comparing between two datetime objects, you might just want to make sure they are similar to a certain extent (have the same hour, not the same hour and minute). You can specify to how precise DeepDiff should compare between two datetime objects using truncate_datetime . If you want to exclude certain paths from the report, you exclude_paths : If you want to ignore multiple paths with a certain pattern, use exclude_regrex_paths . For example, to avoid comparing aldi[0]['color'] with walmart[0]['color']and aldi[1]['color'] with walmart[1]['color'] , we simply ignore the paths specified by the regular expression root[\d+\]\['color'\] , where \d+ stands for one or more digits. Check this cheatsheet if you are not familiar with regular expression. To use DeepDiff with pytest, write assert not DeepDiff(...) . This means that we want to assert that there is no difference between two Python objects. Congratulations! You have just learned how to ignore certain elements when comparing between two Python objects using DeepDiff. I hope this tool will make it easier for you to write tests and debug your code. Feel free to play and fork the source code of this article here: github.com I like to write about basic data science concepts and play with different data science tools. You could connect with me on LinkedIn and Twitter. Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:
[ { "code": null, "e": 314, "s": 171, "text": "When comparing two Python objects, you might not want the test to focus on some trivial differences such as the order of the values in a list." }, { "code": null, "e": 396, "s": 314, "text": "For example, you might want the test to consider[3, 2] to be the same as [2, 3] ." }, { "code": null, "e": 451, "s": 396, "text": "However, you get an error when the order is different." }, { "code": null, "e": 531, "s": 451, "text": "Is there a way that you can ignore the order when comparing two Python objects?" }, { "code": null, "e": 675, "s": 531, "text": "That is when DeepDiff comes in handy. In this article, you will learn how to use DeepDiff to prevent comparing certain parts of Python objects." }, { "code": null, "e": 803, "s": 675, "text": "DeepDiff is a Python library that recursively looks for all the changes in dictionaries, iterables, strings, and other objects." }, { "code": null, "e": 830, "s": 803, "text": "To install DeepDiff, type:" }, { "code": null, "e": 851, "s": 830, "text": "pip install deepdiff" }, { "code": null, "e": 959, "s": 851, "text": "When comparing between two different Python objects using assert , you might get an error similar to below:" }, { "code": null, "e": 1076, "s": 959, "text": "AssertionError: assert {'apple': 2, 'banana': [3, 2, 2], 'orange': 3} == {'apple': 2, 'banana': [3, 2], 'orange': 3}" }, { "code": null, "e": 1204, "s": 1076, "text": "This assertion error is not very informative since we don’t know the exact elements that make these two dictionaries different." }, { "code": null, "e": 1321, "s": 1204, "text": "With DeepDiff, we can see a more descriptive error showing what the differences are and where the differences occur." }, { "code": null, "e": 1365, "s": 1321, "text": "From the error above, we know three things:" }, { "code": null, "e": 1407, "s": 1365, "text": "One item in price1 is removed in price2 ." }, { "code": null, "e": 1451, "s": 1407, "text": "The removed item is at price1['banana'][2]." }, { "code": null, "e": 1488, "s": 1451, "text": "The value of the removed item is 2 ." }, { "code": null, "e": 1684, "s": 1488, "text": "The default view of DeepDiff is \"text\" . To change the view into a tree view, use view=\"tree\" . In the tree view, you can traverse through the tree and see what items were compared to each other." }, { "code": null, "e": 1777, "s": 1684, "text": "As shown at the beginning of the article, you can ignore the order using ignore_order=True :" }, { "code": null, "e": 1853, "s": 1777, "text": "The output {} shows that there is no difference between two Python objects." }, { "code": null, "e": 1910, "s": 1853, "text": "You can also use ignore_order=True to ignore duplicates:" }, { "code": null, "e": 2111, "s": 1910, "text": "It can be annoying to see the assertion error when two numbers are very close to each other. If you want to ignore the difference between two numbers after a particular digit, use significant_digits ." }, { "code": null, "e": 2186, "s": 2111, "text": "In the code below, we only compare the two numbers up to the second digit." }, { "code": null, "e": 2329, "s": 2186, "text": "Sometimes, two numbers are very close, but they don’t have similar digits. To ignore small differences between two numbers, use math_epsilon ." }, { "code": null, "e": 2523, "s": 2329, "text": "In the code below, I use math_epsilon=0.001 to tell DeepDiff to ignore the difference that is smaller than 0.001. Since the difference between 1 and 0.9999 is 0.0001, the difference is ignored." }, { "code": null, "e": 2612, "s": 2523, "text": "If you want to ignore string case (.i.e, “Red” and “red”), use ignore_string_case=True ." }, { "code": null, "e": 2703, "s": 2612, "text": "If you have worked with some NaNs, you might know that not every NaNs in Python are equal:" }, { "code": null, "e": 2829, "s": 2703, "text": "Thus, it can be confusing to compare objects that contain different types of NaNs. (Isn’t [nan, 1, 2] equal to [nan, 1, 2] ?)" }, { "code": null, "e": 2897, "s": 2829, "text": "To ignore different types of NaNs, use ignore_nan_inequality=True :" }, { "code": null, "e": 3010, "s": 2897, "text": "Sometimes, you might not care if certain types change or not. To include certain data types, use exclude_types :" }, { "code": null, "e": 3143, "s": 3010, "text": "2 != 2.0 since 2 is an integer and 2.0 is a float. You can ignore variation in numeric type using ignore_numeric_type_changes=True ." }, { "code": null, "e": 3310, "s": 3143, "text": "When comparing between two datetime objects, you might just want to make sure they are similar to a certain extent (have the same hour, not the same hour and minute)." }, { "code": null, "e": 3420, "s": 3310, "text": "You can specify to how precise DeepDiff should compare between two datetime objects using truncate_datetime ." }, { "code": null, "e": 3494, "s": 3420, "text": "If you want to exclude certain paths from the report, you exclude_paths :" }, { "code": null, "e": 3582, "s": 3494, "text": "If you want to ignore multiple paths with a certain pattern, use exclude_regrex_paths ." }, { "code": null, "e": 3831, "s": 3582, "text": "For example, to avoid comparing aldi[0]['color'] with walmart[0]['color']and aldi[1]['color'] with walmart[1]['color'] , we simply ignore the paths specified by the regular expression root[\\d+\\]\\['color'\\] , where \\d+ stands for one or more digits." }, { "code": null, "e": 3902, "s": 3831, "text": "Check this cheatsheet if you are not familiar with regular expression." }, { "code": null, "e": 4054, "s": 3902, "text": "To use DeepDiff with pytest, write assert not DeepDiff(...) . This means that we want to assert that there is no difference between two Python objects." }, { "code": null, "e": 4263, "s": 4054, "text": "Congratulations! You have just learned how to ignore certain elements when comparing between two Python objects using DeepDiff. I hope this tool will make it easier for you to write tests and debug your code." }, { "code": null, "e": 4328, "s": 4263, "text": "Feel free to play and fork the source code of this article here:" }, { "code": null, "e": 4339, "s": 4328, "text": "github.com" }, { "code": null, "e": 4484, "s": 4339, "text": "I like to write about basic data science concepts and play with different data science tools. You could connect with me on LinkedIn and Twitter." } ]
C# program to merge two Dictionaries
Set the two dictionaries − Dictionary < string, int > dict1 = new Dictionary < string, int > (); dict1.Add("laptop", 1); dict1.Add("desktop", 2); Dictionary < string, int > dict2 = new Dictionary < string, int > (); dict2.Add("desktop", 3); dict2.Add("tablet", 4); dict2.Add("mobile", 5); Now use HashSet and UnionWith() method to merge the two dictionaries − HashSet < string > hSet = new HashSet < string > (dict1.Keys); hSet.UnionWith(dict2.Keys); Here is the complete code − using System; using System.Collections.Generic; class Program { static void Main() { Dictionary < string, int > dict1 = new Dictionary < string, int > (); dict1.Add("laptop", 1); dict1.Add("desktop", 2); Dictionary < string, int > dict2 = new Dictionary < string, int > (); dict2.Add("desktop", 3); dict2.Add("tablet", 4); dict2.Add("mobile", 5); HashSet < string > hSet = new HashSet < string > (dict1.Keys); hSet.UnionWith(dict2.Keys); Console.WriteLine("Merged Dictionary..."); foreach(string val in hSet) { Console.WriteLine(val); } } }
[ { "code": null, "e": 1089, "s": 1062, "text": "Set the two dictionaries −" }, { "code": null, "e": 1351, "s": 1089, "text": "Dictionary < string, int > dict1 = new Dictionary < string, int > ();\ndict1.Add(\"laptop\", 1);\ndict1.Add(\"desktop\", 2);\nDictionary < string, int > dict2 = new Dictionary < string, int > ();\ndict2.Add(\"desktop\", 3);\ndict2.Add(\"tablet\", 4);\ndict2.Add(\"mobile\", 5);" }, { "code": null, "e": 1422, "s": 1351, "text": "Now use HashSet and UnionWith() method to merge the two dictionaries −" }, { "code": null, "e": 1513, "s": 1422, "text": "HashSet < string > hSet = new HashSet < string > (dict1.Keys);\nhSet.UnionWith(dict2.Keys);" }, { "code": null, "e": 1541, "s": 1513, "text": "Here is the complete code −" }, { "code": null, "e": 2172, "s": 1541, "text": "using System;\nusing System.Collections.Generic;\nclass Program {\n static void Main() {\n Dictionary < string, int > dict1 = new Dictionary < string, int > ();\n dict1.Add(\"laptop\", 1);\n dict1.Add(\"desktop\", 2);\n\n Dictionary < string, int > dict2 = new Dictionary < string, int > ();\n dict2.Add(\"desktop\", 3);\n dict2.Add(\"tablet\", 4);\n dict2.Add(\"mobile\", 5);\n\n HashSet < string > hSet = new HashSet < string > (dict1.Keys);\n hSet.UnionWith(dict2.Keys);\n Console.WriteLine(\"Merged Dictionary...\");\n\n foreach(string val in hSet) {\n Console.WriteLine(val);\n }\n }\n}" } ]
How to create a Sandbox in Lua?
In order to create a sandbox and to be able to use it we must first understand what a sandbox is and why we need it. A sandbox is term that is used in different fields of computer science, like in case we are talking about the software testing domain, then a sandbox is a testing environment that isolates untested code changes and outright experimentation from the production environment and if we talk about cybersecurity, then a sandbox is an environment that is an isolated virtual machine in which potentially unsafe software code can execute. Sandboxing is basically all about isolating a piece of software and that piece of software is isolated with the help of the sandbox. It should be noted that sandboxing is a bit tricky and generally difficult to get right. Lua provides different approaches to creating a sandbox and also it provides different keywords and functions that we can make use inside of a sandbox. Now, let’s create a simple sandbox in which we will store the untrusted code. Consider the example shown below − Live Demo function print_env() print(_ENV) end function sandbox() print(_ENV) -- need to keep access to a few globals: _ENV = { print = print, print_env = print_env, debug = debug, load = load } print(_ENV) print_env() local code1 = load('print(_ENV)') code1() debug.setupvalue(code1, 1, _ENV) -- set our modified env code1() local code2 = load('print(_ENV)', nil, nil, _ENV) -- pass 'env' arg code2() end sandbox() table: 0x1a409c0 table: 0x1a47790 table: 0x1a47790 table: 0x1a409c0 table: 0x1a47790 table: 0x1a47790
[ { "code": null, "e": 1611, "s": 1062, "text": "In order to create a sandbox and to be able to use it we must first understand what a sandbox is and why we need it. A sandbox is term that is used in different fields of computer science, like in case we are talking about the software testing domain, then a sandbox is a testing environment that isolates untested code changes and outright experimentation from the production environment and if we talk about cybersecurity, then a sandbox is an environment that is an isolated virtual machine in which potentially unsafe software code can execute." }, { "code": null, "e": 1833, "s": 1611, "text": "Sandboxing is basically all about isolating a piece of software and that piece of software is isolated with the help of the sandbox. It should be noted that sandboxing is a bit tricky and generally difficult to get right." }, { "code": null, "e": 1985, "s": 1833, "text": "Lua provides different approaches to creating a sandbox and also it provides different keywords and functions that we can make use inside of a sandbox." }, { "code": null, "e": 2063, "s": 1985, "text": "Now, let’s create a simple sandbox in which we will store the untrusted code." }, { "code": null, "e": 2098, "s": 2063, "text": "Consider the example shown below −" }, { "code": null, "e": 2109, "s": 2098, "text": " Live Demo" }, { "code": null, "e": 2545, "s": 2109, "text": "function print_env()\n print(_ENV)\nend\nfunction sandbox()\n print(_ENV)\n -- need to keep access to a few globals:\n _ENV = { print = print, print_env = print_env, debug = debug, load = load }\n print(_ENV)\n print_env()\n local code1 = load('print(_ENV)')\n code1()\n debug.setupvalue(code1, 1, _ENV) -- set our modified env code1()\n local code2 = load('print(_ENV)', nil, nil, _ENV) -- pass 'env' arg code2()\nend\nsandbox()" }, { "code": null, "e": 2647, "s": 2545, "text": "table: 0x1a409c0\ntable: 0x1a47790\ntable: 0x1a47790\ntable: 0x1a409c0\ntable: 0x1a47790\ntable: 0x1a47790" } ]
How to use PHP OPCache ? - GeeksforGeeks
31 Dec, 2021 The OPCache is used for improving the performance of PHP as it stores the precompiled bytecode, in result deleting the need for loading and parsing the PHP scripts upon each request. Requirements: Packages such as Zend OPCache are required for the purposeful use. The zendOPCache package contains PHP versions 5.2, 5.3 and 5.4. This package is used with the basic fulfillment of the need for opcode caching and hence optimization. It will improve the performance of PHP by storing the precompiled bytecode in the shared memory and eliminating the need of reading the code from the disk and compiling it for future access.For the Package download of Zend OPCache(Direct Download Links): Enabling OPCache extensions: For PHP Versions 5.2, 5.3 and 5.4Due to Unavailability of a DLL(Dynamic Link Library) for PECL(PHP Extension and Application Repository) installation of the PECL extensions can be found here. Due to Unavailability of a DLL(Dynamic Link Library) for PECL(PHP Extension and Application Repository) installation of the PECL extensions can be found here. For PHP Versions 5.5.0 or laterOPCache can only be compiled as a shared extension under this version. Firstly, you need to enable the building of default extension with –enable-opcache option to make it available.Afterwards, you can use the zend_extension configuration directive to lead the OP Cache extension into PHP. Use zend_extension=/full/path/to/opcache.so on non-Windows platforms, and zend_extension=C:\path\to\php_opcache.dll on Windows.To use OPCache with Xdebug, you need to load OPCache before Xdebug.Information regarding New Releases, Downloads, ChangeLog and additional information can be found here. To use OPCache with Xdebug, you need to load OPCache before Xdebug. Information regarding New Releases, Downloads, ChangeLog and additional information can be found here. Advised php.ini setting: Make the following changes in php.ini file for optimized performance.opcache.memory_consumption=128 opcache.interned_strings_buffer=8 opcache.max_accelerated_files=4000 opcache.revalidate_freq=60 opcache.fast_shutdown=1 opcache.enable_cli=1 opcache.memory_consumption=128 opcache.interned_strings_buffer=8 opcache.max_accelerated_files=4000 opcache.revalidate_freq=60 opcache.fast_shutdown=1 opcache.enable_cli=1 A full list of configuration directive supported by OPcache is also available. OPCache Functions: opcache_compile_file() Function: This function is used to compile and cache a PHP script without executing it.Syntax:bool opcache_compile_file( $file ) This function compiles a PHP script and adds that in the opcode cache without executing the file, this can be used to prime the cache after a Web server restart by pre-caching files that will be included later requests. The $file is used as a parameter. It is the path to the PHP script to be compiled. The above description returns true if the file was compiled successfully else false.Errors/Exceptions: For any errors (if occur), for example, in this case, an error of level E_Warning if generated, use as a @ as a prefix, as we prefix it, an error message that might be generated might get ignored.If any custom error Handler function with set_error_handler() is called, which in turn calls the error_reporting() which returns 0 when preceded by a @ which means, that error is ignored and the program proceeds further.If the track_errors feature is enabled, any error message generated by the expression will be saved in a variable namely $php_errormsg which overwrites any further errors if occur. Also, this variable can be checked early if you want to make use of it.phpphp<?php // Intentional file error$my_file = @file('non existent file') or die("Failed opening file, error was : '$php_errormsg'" ); // This works for any expression, not just functions$value = @$cache[$key];?>Note: This operator is known by the veteran PHPers as the STFU operator.opcache_get_configuration() Function: This function is used to get the configuration information about the cache.Syntax:array opcache_get_configuration( void )This function returns configuration data about the cache instance and also returns an array of information including the ini file.Errors/Exceptions: If opcache.restrict_api is in use and the current path is in violation of the rule then an E_WARNING will be raised, no status information will be returned.opcache_get_status() Function: This function is used to get the status information about the cache.Syntax:array opcache_get_status( $get_scripts = TRUE )This function returns the state information about the cache instance, $get_scripts is used as a parameter including script specific state information.Return Value: It returns an array of information, and it will optionally containing script specific state information, or FALSE on failure.Errors/Exceptions: If opcache.restrict_api is in use and the current path is in violation of the rule then an E_WARNING will be raised, no status information will be returned.opcache_invalidate() Function: This function is used to invalidate the cached script.Syntax:bool opcache_invalidate( $script, $force = FALSE )This function invalidates the particular script from the opcode cache. If force is unset or FALSE, the script will only be invalidated if the modification time of the script is new compared to the cached opcodes. The $script is used as a parameter denoting the path to the script being invalidated. The $force is used as a parameter if it set to TRUE, the script will be invalidated regardless of whether invalidation is necessary.Return value: TRUE if the opcode cache for the script was invalidated or if there was nothing to invalidate, or FALSE if the opcode cache is disabled.opcache_is_script_cached() Function: It will tell whether a script is cached in OPCache or not.Syntax:bool opcache_is_script_cached( $file )This function checks if a PHP script has been cached in OPCache. This could be used more easily to detect the “warning” of the cache for the particular script. The $file is used as a parameter describes the path to the PHP script being checked.Returns: It will returns TRUE if file is cached in OPCache, FALSE otherwise.opcache_reset() Function: This function resets the contents of the opcode cache.Syntax:bool opcache_reset( void ) This function resets the entire opcode cache. After calling opcache_reset(), all scripts will be reloaded and reparsed the next time they are hit.Return Value: It will return TRUE if the opcode cache was reset and FALSE if the opcode cache is disabled. opcache_compile_file() Function: This function is used to compile and cache a PHP script without executing it.Syntax:bool opcache_compile_file( $file ) This function compiles a PHP script and adds that in the opcode cache without executing the file, this can be used to prime the cache after a Web server restart by pre-caching files that will be included later requests. The $file is used as a parameter. It is the path to the PHP script to be compiled. The above description returns true if the file was compiled successfully else false.Errors/Exceptions: For any errors (if occur), for example, in this case, an error of level E_Warning if generated, use as a @ as a prefix, as we prefix it, an error message that might be generated might get ignored.If any custom error Handler function with set_error_handler() is called, which in turn calls the error_reporting() which returns 0 when preceded by a @ which means, that error is ignored and the program proceeds further.If the track_errors feature is enabled, any error message generated by the expression will be saved in a variable namely $php_errormsg which overwrites any further errors if occur. Also, this variable can be checked early if you want to make use of it.phpphp<?php // Intentional file error$my_file = @file('non existent file') or die("Failed opening file, error was : '$php_errormsg'" ); // This works for any expression, not just functions$value = @$cache[$key];?>Note: This operator is known by the veteran PHPers as the STFU operator. Syntax: bool opcache_compile_file( $file ) This function compiles a PHP script and adds that in the opcode cache without executing the file, this can be used to prime the cache after a Web server restart by pre-caching files that will be included later requests. The $file is used as a parameter. It is the path to the PHP script to be compiled. The above description returns true if the file was compiled successfully else false. Errors/Exceptions: For any errors (if occur), for example, in this case, an error of level E_Warning if generated, use as a @ as a prefix, as we prefix it, an error message that might be generated might get ignored.If any custom error Handler function with set_error_handler() is called, which in turn calls the error_reporting() which returns 0 when preceded by a @ which means, that error is ignored and the program proceeds further.If the track_errors feature is enabled, any error message generated by the expression will be saved in a variable namely $php_errormsg which overwrites any further errors if occur. Also, this variable can be checked early if you want to make use of it. php <?php // Intentional file error$my_file = @file('non existent file') or die("Failed opening file, error was : '$php_errormsg'" ); // This works for any expression, not just functions$value = @$cache[$key];?> Note: This operator is known by the veteran PHPers as the STFU operator. opcache_get_configuration() Function: This function is used to get the configuration information about the cache.Syntax:array opcache_get_configuration( void )This function returns configuration data about the cache instance and also returns an array of information including the ini file.Errors/Exceptions: If opcache.restrict_api is in use and the current path is in violation of the rule then an E_WARNING will be raised, no status information will be returned. Syntax: array opcache_get_configuration( void ) This function returns configuration data about the cache instance and also returns an array of information including the ini file. Errors/Exceptions: If opcache.restrict_api is in use and the current path is in violation of the rule then an E_WARNING will be raised, no status information will be returned. opcache_get_status() Function: This function is used to get the status information about the cache.Syntax:array opcache_get_status( $get_scripts = TRUE )This function returns the state information about the cache instance, $get_scripts is used as a parameter including script specific state information.Return Value: It returns an array of information, and it will optionally containing script specific state information, or FALSE on failure.Errors/Exceptions: If opcache.restrict_api is in use and the current path is in violation of the rule then an E_WARNING will be raised, no status information will be returned. Syntax: array opcache_get_status( $get_scripts = TRUE ) This function returns the state information about the cache instance, $get_scripts is used as a parameter including script specific state information. Return Value: It returns an array of information, and it will optionally containing script specific state information, or FALSE on failure. Errors/Exceptions: If opcache.restrict_api is in use and the current path is in violation of the rule then an E_WARNING will be raised, no status information will be returned. opcache_invalidate() Function: This function is used to invalidate the cached script.Syntax:bool opcache_invalidate( $script, $force = FALSE )This function invalidates the particular script from the opcode cache. If force is unset or FALSE, the script will only be invalidated if the modification time of the script is new compared to the cached opcodes. The $script is used as a parameter denoting the path to the script being invalidated. The $force is used as a parameter if it set to TRUE, the script will be invalidated regardless of whether invalidation is necessary.Return value: TRUE if the opcode cache for the script was invalidated or if there was nothing to invalidate, or FALSE if the opcode cache is disabled. Syntax: bool opcache_invalidate( $script, $force = FALSE ) This function invalidates the particular script from the opcode cache. If force is unset or FALSE, the script will only be invalidated if the modification time of the script is new compared to the cached opcodes. The $script is used as a parameter denoting the path to the script being invalidated. The $force is used as a parameter if it set to TRUE, the script will be invalidated regardless of whether invalidation is necessary. Return value: TRUE if the opcode cache for the script was invalidated or if there was nothing to invalidate, or FALSE if the opcode cache is disabled. opcache_is_script_cached() Function: It will tell whether a script is cached in OPCache or not.Syntax:bool opcache_is_script_cached( $file )This function checks if a PHP script has been cached in OPCache. This could be used more easily to detect the “warning” of the cache for the particular script. The $file is used as a parameter describes the path to the PHP script being checked.Returns: It will returns TRUE if file is cached in OPCache, FALSE otherwise. Syntax: bool opcache_is_script_cached( $file ) This function checks if a PHP script has been cached in OPCache. This could be used more easily to detect the “warning” of the cache for the particular script. The $file is used as a parameter describes the path to the PHP script being checked. Returns: It will returns TRUE if file is cached in OPCache, FALSE otherwise. opcache_reset() Function: This function resets the contents of the opcode cache.Syntax:bool opcache_reset( void ) This function resets the entire opcode cache. After calling opcache_reset(), all scripts will be reloaded and reparsed the next time they are hit.Return Value: It will return TRUE if the opcode cache was reset and FALSE if the opcode cache is disabled. Syntax: bool opcache_reset( void ) This function resets the entire opcode cache. After calling opcache_reset(), all scripts will be reloaded and reparsed the next time they are hit. Return Value: It will return TRUE if the opcode cache was reset and FALSE if the opcode cache is disabled. sagar0719kumar simmytarika5 arorakashish0911 Picked PHP PHP Programs Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to fetch data from localserver database and display on HTML table using PHP ? How to pass form variables from one page to other page in PHP ? Create a drop-down list that options fetched from a MySQL database in PHP How to create admin login page using PHP? Different ways for passing data to view in Laravel How to call PHP function on the click of a Button ? How to fetch data from localserver database and display on HTML table using PHP ? How to pass form variables from one page to other page in PHP ? How to create admin login page using PHP? How to Install php-curl in Ubuntu ?
[ { "code": null, "e": 24581, "s": 24553, "text": "\n31 Dec, 2021" }, { "code": null, "e": 24764, "s": 24581, "text": "The OPCache is used for improving the performance of PHP as it stores the precompiled bytecode, in result deleting the need for loading and parsing the PHP scripts upon each request." }, { "code": null, "e": 25267, "s": 24764, "text": "Requirements: Packages such as Zend OPCache are required for the purposeful use. The zendOPCache package contains PHP versions 5.2, 5.3 and 5.4. This package is used with the basic fulfillment of the need for opcode caching and hence optimization. It will improve the performance of PHP by storing the precompiled bytecode in the shared memory and eliminating the need of reading the code from the disk and compiling it for future access.For the Package download of Zend OPCache(Direct Download Links):" }, { "code": null, "e": 25296, "s": 25267, "text": "Enabling OPCache extensions:" }, { "code": null, "e": 25488, "s": 25296, "text": "For PHP Versions 5.2, 5.3 and 5.4Due to Unavailability of a DLL(Dynamic Link Library) for PECL(PHP Extension and Application Repository) installation of the PECL extensions can be found here." }, { "code": null, "e": 25647, "s": 25488, "text": "Due to Unavailability of a DLL(Dynamic Link Library) for PECL(PHP Extension and Application Repository) installation of the PECL extensions can be found here." }, { "code": null, "e": 26265, "s": 25647, "text": "For PHP Versions 5.5.0 or laterOPCache can only be compiled as a shared extension under this version. Firstly, you need to enable the building of default extension with –enable-opcache option to make it available.Afterwards, you can use the zend_extension configuration directive to lead the OP Cache extension into PHP. Use zend_extension=/full/path/to/opcache.so on non-Windows platforms, and zend_extension=C:\\path\\to\\php_opcache.dll on Windows.To use OPCache with Xdebug, you need to load OPCache before Xdebug.Information regarding New Releases, Downloads, ChangeLog and additional information can be found here." }, { "code": null, "e": 26333, "s": 26265, "text": "To use OPCache with Xdebug, you need to load OPCache before Xdebug." }, { "code": null, "e": 26436, "s": 26333, "text": "Information regarding New Releases, Downloads, ChangeLog and additional information can be found here." }, { "code": null, "e": 26461, "s": 26436, "text": "Advised php.ini setting:" }, { "code": null, "e": 26702, "s": 26461, "text": "Make the following changes in php.ini file for optimized performance.opcache.memory_consumption=128\nopcache.interned_strings_buffer=8\nopcache.max_accelerated_files=4000\nopcache.revalidate_freq=60\nopcache.fast_shutdown=1\nopcache.enable_cli=1" }, { "code": null, "e": 26874, "s": 26702, "text": "opcache.memory_consumption=128\nopcache.interned_strings_buffer=8\nopcache.max_accelerated_files=4000\nopcache.revalidate_freq=60\nopcache.fast_shutdown=1\nopcache.enable_cli=1" }, { "code": null, "e": 26953, "s": 26874, "text": "A full list of configuration directive supported by OPcache is also available." }, { "code": null, "e": 26972, "s": 26953, "text": "OPCache Functions:" }, { "code": null, "e": 31116, "s": 26972, "text": "opcache_compile_file() Function: This function is used to compile and cache a PHP script without executing it.Syntax:bool opcache_compile_file( $file ) This function compiles a PHP script and adds that in the opcode cache without executing the file, this can be used to prime the cache after a Web server restart by pre-caching files that will be included later requests. The $file is used as a parameter. It is the path to the PHP script to be compiled. The above description returns true if the file was compiled successfully else false.Errors/Exceptions: For any errors (if occur), for example, in this case, an error of level E_Warning if generated, use as a @ as a prefix, as we prefix it, an error message that might be generated might get ignored.If any custom error Handler function with set_error_handler() is called, which in turn calls the error_reporting() which returns 0 when preceded by a @ which means, that error is ignored and the program proceeds further.If the track_errors feature is enabled, any error message generated by the expression will be saved in a variable namely $php_errormsg which overwrites any further errors if occur. Also, this variable can be checked early if you want to make use of it.phpphp<?php // Intentional file error$my_file = @file('non existent file') or die(\"Failed opening file, error was : '$php_errormsg'\" ); // This works for any expression, not just functions$value = @$cache[$key];?>Note: This operator is known by the veteran PHPers as the STFU operator.opcache_get_configuration() Function: This function is used to get the configuration information about the cache.Syntax:array opcache_get_configuration( void )This function returns configuration data about the cache instance and also returns an array of information including the ini file.Errors/Exceptions: If opcache.restrict_api is in use and the current path is in violation of the rule then an E_WARNING will be raised, no status information will be returned.opcache_get_status() Function: This function is used to get the status information about the cache.Syntax:array opcache_get_status( $get_scripts = TRUE )This function returns the state information about the cache instance, $get_scripts is used as a parameter including script specific state information.Return Value: It returns an array of information, and it will optionally containing script specific state information, or FALSE on failure.Errors/Exceptions: If opcache.restrict_api is in use and the current path is in violation of the rule then an E_WARNING will be raised, no status information will be returned.opcache_invalidate() Function: This function is used to invalidate the cached script.Syntax:bool opcache_invalidate( $script, $force = FALSE )This function invalidates the particular script from the opcode cache. If force is unset or FALSE, the script will only be invalidated if the modification time of the script is new compared to the cached opcodes. The $script is used as a parameter denoting the path to the script being invalidated. The $force is used as a parameter if it set to TRUE, the script will be invalidated regardless of whether invalidation is necessary.Return value: TRUE if the opcode cache for the script was invalidated or if there was nothing to invalidate, or FALSE if the opcode cache is disabled.opcache_is_script_cached() Function: It will tell whether a script is cached in OPCache or not.Syntax:bool opcache_is_script_cached( $file )This function checks if a PHP script has been cached in OPCache. This could be used more easily to detect the “warning” of the cache for the particular script. The $file is used as a parameter describes the path to the PHP script being checked.Returns: It will returns TRUE if file is cached in OPCache, FALSE otherwise.opcache_reset() Function: This function resets the contents of the opcode cache.Syntax:bool opcache_reset( void ) This function resets the entire opcode cache. After calling opcache_reset(), all scripts will be reloaded and reparsed the next time they are hit.Return Value: It will return TRUE if the opcode cache was reset and FALSE if the opcode cache is disabled." }, { "code": null, "e": 32630, "s": 31116, "text": "opcache_compile_file() Function: This function is used to compile and cache a PHP script without executing it.Syntax:bool opcache_compile_file( $file ) This function compiles a PHP script and adds that in the opcode cache without executing the file, this can be used to prime the cache after a Web server restart by pre-caching files that will be included later requests. The $file is used as a parameter. It is the path to the PHP script to be compiled. The above description returns true if the file was compiled successfully else false.Errors/Exceptions: For any errors (if occur), for example, in this case, an error of level E_Warning if generated, use as a @ as a prefix, as we prefix it, an error message that might be generated might get ignored.If any custom error Handler function with set_error_handler() is called, which in turn calls the error_reporting() which returns 0 when preceded by a @ which means, that error is ignored and the program proceeds further.If the track_errors feature is enabled, any error message generated by the expression will be saved in a variable namely $php_errormsg which overwrites any further errors if occur. Also, this variable can be checked early if you want to make use of it.phpphp<?php // Intentional file error$my_file = @file('non existent file') or die(\"Failed opening file, error was : '$php_errormsg'\" ); // This works for any expression, not just functions$value = @$cache[$key];?>Note: This operator is known by the veteran PHPers as the STFU operator." }, { "code": null, "e": 32638, "s": 32630, "text": "Syntax:" }, { "code": null, "e": 32674, "s": 32638, "text": "bool opcache_compile_file( $file ) " }, { "code": null, "e": 33062, "s": 32674, "text": "This function compiles a PHP script and adds that in the opcode cache without executing the file, this can be used to prime the cache after a Web server restart by pre-caching files that will be included later requests. The $file is used as a parameter. It is the path to the PHP script to be compiled. The above description returns true if the file was compiled successfully else false." }, { "code": null, "e": 33750, "s": 33062, "text": "Errors/Exceptions: For any errors (if occur), for example, in this case, an error of level E_Warning if generated, use as a @ as a prefix, as we prefix it, an error message that might be generated might get ignored.If any custom error Handler function with set_error_handler() is called, which in turn calls the error_reporting() which returns 0 when preceded by a @ which means, that error is ignored and the program proceeds further.If the track_errors feature is enabled, any error message generated by the expression will be saved in a variable namely $php_errormsg which overwrites any further errors if occur. Also, this variable can be checked early if you want to make use of it." }, { "code": null, "e": 33754, "s": 33750, "text": "php" }, { "code": "<?php // Intentional file error$my_file = @file('non existent file') or die(\"Failed opening file, error was : '$php_errormsg'\" ); // This works for any expression, not just functions$value = @$cache[$key];?>", "e": 33964, "s": 33754, "text": null }, { "code": null, "e": 34037, "s": 33964, "text": "Note: This operator is known by the veteran PHPers as the STFU operator." }, { "code": null, "e": 34502, "s": 34037, "text": "opcache_get_configuration() Function: This function is used to get the configuration information about the cache.Syntax:array opcache_get_configuration( void )This function returns configuration data about the cache instance and also returns an array of information including the ini file.Errors/Exceptions: If opcache.restrict_api is in use and the current path is in violation of the rule then an E_WARNING will be raised, no status information will be returned." }, { "code": null, "e": 34510, "s": 34502, "text": "Syntax:" }, { "code": null, "e": 34550, "s": 34510, "text": "array opcache_get_configuration( void )" }, { "code": null, "e": 34681, "s": 34550, "text": "This function returns configuration data about the cache instance and also returns an array of information including the ini file." }, { "code": null, "e": 34857, "s": 34681, "text": "Errors/Exceptions: If opcache.restrict_api is in use and the current path is in violation of the rule then an E_WARNING will be raised, no status information will be returned." }, { "code": null, "e": 35475, "s": 34857, "text": "opcache_get_status() Function: This function is used to get the status information about the cache.Syntax:array opcache_get_status( $get_scripts = TRUE )This function returns the state information about the cache instance, $get_scripts is used as a parameter including script specific state information.Return Value: It returns an array of information, and it will optionally containing script specific state information, or FALSE on failure.Errors/Exceptions: If opcache.restrict_api is in use and the current path is in violation of the rule then an E_WARNING will be raised, no status information will be returned." }, { "code": null, "e": 35483, "s": 35475, "text": "Syntax:" }, { "code": null, "e": 35531, "s": 35483, "text": "array opcache_get_status( $get_scripts = TRUE )" }, { "code": null, "e": 35682, "s": 35531, "text": "This function returns the state information about the cache instance, $get_scripts is used as a parameter including script specific state information." }, { "code": null, "e": 35822, "s": 35682, "text": "Return Value: It returns an array of information, and it will optionally containing script specific state information, or FALSE on failure." }, { "code": null, "e": 35998, "s": 35822, "text": "Errors/Exceptions: If opcache.restrict_api is in use and the current path is in violation of the rule then an E_WARNING will be raised, no status information will be returned." }, { "code": null, "e": 36722, "s": 35998, "text": "opcache_invalidate() Function: This function is used to invalidate the cached script.Syntax:bool opcache_invalidate( $script, $force = FALSE )This function invalidates the particular script from the opcode cache. If force is unset or FALSE, the script will only be invalidated if the modification time of the script is new compared to the cached opcodes. The $script is used as a parameter denoting the path to the script being invalidated. The $force is used as a parameter if it set to TRUE, the script will be invalidated regardless of whether invalidation is necessary.Return value: TRUE if the opcode cache for the script was invalidated or if there was nothing to invalidate, or FALSE if the opcode cache is disabled." }, { "code": null, "e": 36730, "s": 36722, "text": "Syntax:" }, { "code": null, "e": 36781, "s": 36730, "text": "bool opcache_invalidate( $script, $force = FALSE )" }, { "code": null, "e": 37213, "s": 36781, "text": "This function invalidates the particular script from the opcode cache. If force is unset or FALSE, the script will only be invalidated if the modification time of the script is new compared to the cached opcodes. The $script is used as a parameter denoting the path to the script being invalidated. The $force is used as a parameter if it set to TRUE, the script will be invalidated regardless of whether invalidation is necessary." }, { "code": null, "e": 37364, "s": 37213, "text": "Return value: TRUE if the opcode cache for the script was invalidated or if there was nothing to invalidate, or FALSE if the opcode cache is disabled." }, { "code": null, "e": 37825, "s": 37364, "text": "opcache_is_script_cached() Function: It will tell whether a script is cached in OPCache or not.Syntax:bool opcache_is_script_cached( $file )This function checks if a PHP script has been cached in OPCache. This could be used more easily to detect the “warning” of the cache for the particular script. The $file is used as a parameter describes the path to the PHP script being checked.Returns: It will returns TRUE if file is cached in OPCache, FALSE otherwise." }, { "code": null, "e": 37833, "s": 37825, "text": "Syntax:" }, { "code": null, "e": 37872, "s": 37833, "text": "bool opcache_is_script_cached( $file )" }, { "code": null, "e": 38117, "s": 37872, "text": "This function checks if a PHP script has been cached in OPCache. This could be used more easily to detect the “warning” of the cache for the particular script. The $file is used as a parameter describes the path to the PHP script being checked." }, { "code": null, "e": 38194, "s": 38117, "text": "Returns: It will returns TRUE if file is cached in OPCache, FALSE otherwise." }, { "code": null, "e": 38561, "s": 38194, "text": "opcache_reset() Function: This function resets the contents of the opcode cache.Syntax:bool opcache_reset( void ) This function resets the entire opcode cache. After calling opcache_reset(), all scripts will be reloaded and reparsed the next time they are hit.Return Value: It will return TRUE if the opcode cache was reset and FALSE if the opcode cache is disabled." }, { "code": null, "e": 38569, "s": 38561, "text": "Syntax:" }, { "code": null, "e": 38597, "s": 38569, "text": "bool opcache_reset( void ) " }, { "code": null, "e": 38744, "s": 38597, "text": "This function resets the entire opcode cache. After calling opcache_reset(), all scripts will be reloaded and reparsed the next time they are hit." }, { "code": null, "e": 38851, "s": 38744, "text": "Return Value: It will return TRUE if the opcode cache was reset and FALSE if the opcode cache is disabled." }, { "code": null, "e": 38866, "s": 38851, "text": "sagar0719kumar" }, { "code": null, "e": 38879, "s": 38866, "text": "simmytarika5" }, { "code": null, "e": 38896, "s": 38879, "text": "arorakashish0911" }, { "code": null, "e": 38903, "s": 38896, "text": "Picked" }, { "code": null, "e": 38907, "s": 38903, "text": "PHP" }, { "code": null, "e": 38920, "s": 38907, "text": "PHP Programs" }, { "code": null, "e": 38937, "s": 38920, "text": "Web Technologies" }, { "code": null, "e": 38941, "s": 38937, "text": "PHP" }, { "code": null, "e": 39039, "s": 38941, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39048, "s": 39039, "text": "Comments" }, { "code": null, "e": 39061, "s": 39048, "text": "Old Comments" }, { "code": null, "e": 39143, "s": 39061, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 39207, "s": 39143, "text": "How to pass form variables from one page to other page in PHP ?" }, { "code": null, "e": 39281, "s": 39207, "text": "Create a drop-down list that options fetched from a MySQL database in PHP" }, { "code": null, "e": 39323, "s": 39281, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 39374, "s": 39323, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 39426, "s": 39374, "text": "How to call PHP function on the click of a Button ?" }, { "code": null, "e": 39508, "s": 39426, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 39572, "s": 39508, "text": "How to pass form variables from one page to other page in PHP ?" }, { "code": null, "e": 39614, "s": 39572, "text": "How to create admin login page using PHP?" } ]
Custom dataset in Pytorch —Part 1. Images | by Utkarsh Garg | Towards Data Science
Pytorch has a great ecosystem to load custom datasets for training machine learning models. This is the first part of the two-part series on loading Custom Datasets in Pytorch. In Part 2 we’ll explore loading a custom dataset for a Machine Translation task. In this walkthrough, we’ll learn how to load a custom image dataset for classification. The code for this walkthrough can also be found on Github. We’ll be using the landmark dataset available here. It is a subset of the Google Landmark Data v2. It has 50 classes and contains various landmarks from around the globe. For this exercise, we’ll keep the following folder structure: This is a straightforward folder structure with a root folder as the Train/Test folders containing classes with images inside them. As we’ll see, it doesn’t matter in what structure we get the data in. The data can all be in a single folder with class names in the image names (like “Cat_001.jpg”) or even in a CSV, we can process all this in our custom dataset class. Furthermore, we’ll be using Albumentations library for image augmentation. This library contains a huge number of available options for image augmentations. So, we’ll be learning about how to use it in our custom dataset pipeline. You can install it using : pip install -U albumentations Next, we define our augmentations using Albumentations. We define different augmentations for train and test. We apply transformations related to crop/rotation, colour/saturation, and brightness on training data. We also normalise both train and test data with image net mean and std deviation. Finally, we convert the data to PyTorch tensor using ToTensor(). Next, we create the Train, Valid, and Test sets. Here we create separate lists of image paths for Train, Valid, and Test sets. These will be used in our Dataset class which will be defined for a custom dataset. We get the following output: train_image_path example: images/train/15.Central_Park/462f876f97d424a2.jpgclass example: 42.Death_Valley_National_ParkTrain size: 3996Valid size: 1000Test size: 1250 We can’t use the class names directly for models. We create mappings of classes to index and index to classes. We get an output for idx_to_class like this: {0: '42.Death_Valley_National_Park', 1: '39.Gateway_of_India', 2: '13.Yellowstone_National_Park', 3: '44.Trevi_Fountain', 4: '32.Hanging_Temple'} This is the core of our custom dataset. The structure of the dataset class is something like this: We create our LandmarkDataset class by inheriting the Dataset class: from torch.utils.data import Dataset First, we define the __init__ function. As soon as we create an instance of our LandMarkDataset class, this function is called by default. This function should contain all operations that we want to run on the whole dataset (eg. train) once. The usage of this will be more clear in the next part of this series where we create a custom machine translation dataset. For now, we define the variables for image_paths and transforms for the corresponding Train, Valid, and Test sets. Then we have the __len__ function which just returns the length of the dataset. This is used afterward by the DataLoader to create batches. And finally, we have __getitem__. This processes and returns 1 datapoint at a time. As can be seen above, __getitem__ expects an index. This is handled automatically by the dataloader which for every image in the batch runs __getitem__. In the code for __getitem__, we load the image at index “idx”, extract the label from the file path and then run it through our defined transform. The function returns the Tensor of the image array and its corresponding label. After creating the train_dataset, we can access one example as follows: output:The shape of tensor for 50th image in train dataset: torch.Size([3, 256, 256])The label for 50th image in train dataset: 37 Let’s visualize some images after augmentation through the train_dataset. Some more, The final step. DataLoader class is used to load data in batches for the model. This helps us processing data in mini-batches that can fit within our GPU’s RAM. First, we import the DataLoader: from torch.utils.data import DataLoader Initiating the dataloader by sending in an object of the dataset and the batch size. Once we have the dataloader instance — train_loader, we can use an iterator to access the data like this: #batch of image tensornext(iter(train_loader))[0].shapeoutput:torch.Size([64, 3, 256, 256])#batch of the corresponding labelsnext(iter(train_loader))[1].shapeoutput: torch.Size([64]) This is what we use to batch out the data in our training loop. Every time we run the iterator, the dataloader selects the next 64 indexes and runs it through the __getitem__ in dataset class one by one and then returns it to the training loop. In part 1 of this 2 part series, we saw how we can write our own custom data pipeline. We also learned to use Albumentations for image augmentation. Further, we understood how Dataset and Dataloader classes work internally. In the next part, we’ll up the level by creating a custom dataset class for a Machine Translation task. See you in the next one! Part 2 can be found here.
[ { "code": null, "e": 577, "s": 172, "text": "Pytorch has a great ecosystem to load custom datasets for training machine learning models. This is the first part of the two-part series on loading Custom Datasets in Pytorch. In Part 2 we’ll explore loading a custom dataset for a Machine Translation task. In this walkthrough, we’ll learn how to load a custom image dataset for classification. The code for this walkthrough can also be found on Github." }, { "code": null, "e": 748, "s": 577, "text": "We’ll be using the landmark dataset available here. It is a subset of the Google Landmark Data v2. It has 50 classes and contains various landmarks from around the globe." }, { "code": null, "e": 810, "s": 748, "text": "For this exercise, we’ll keep the following folder structure:" }, { "code": null, "e": 1179, "s": 810, "text": "This is a straightforward folder structure with a root folder as the Train/Test folders containing classes with images inside them. As we’ll see, it doesn’t matter in what structure we get the data in. The data can all be in a single folder with class names in the image names (like “Cat_001.jpg”) or even in a CSV, we can process all this in our custom dataset class." }, { "code": null, "e": 1437, "s": 1179, "text": "Furthermore, we’ll be using Albumentations library for image augmentation. This library contains a huge number of available options for image augmentations. So, we’ll be learning about how to use it in our custom dataset pipeline. You can install it using :" }, { "code": null, "e": 1467, "s": 1437, "text": "pip install -U albumentations" }, { "code": null, "e": 1827, "s": 1467, "text": "Next, we define our augmentations using Albumentations. We define different augmentations for train and test. We apply transformations related to crop/rotation, colour/saturation, and brightness on training data. We also normalise both train and test data with image net mean and std deviation. Finally, we convert the data to PyTorch tensor using ToTensor()." }, { "code": null, "e": 2038, "s": 1827, "text": "Next, we create the Train, Valid, and Test sets. Here we create separate lists of image paths for Train, Valid, and Test sets. These will be used in our Dataset class which will be defined for a custom dataset." }, { "code": null, "e": 2067, "s": 2038, "text": "We get the following output:" }, { "code": null, "e": 2236, "s": 2067, "text": "train_image_path example: images/train/15.Central_Park/462f876f97d424a2.jpgclass example: 42.Death_Valley_National_ParkTrain size: 3996Valid size: 1000Test size: 1250" }, { "code": null, "e": 2347, "s": 2236, "text": "We can’t use the class names directly for models. We create mappings of classes to index and index to classes." }, { "code": null, "e": 2392, "s": 2347, "text": "We get an output for idx_to_class like this:" }, { "code": null, "e": 2538, "s": 2392, "text": "{0: '42.Death_Valley_National_Park', 1: '39.Gateway_of_India', 2: '13.Yellowstone_National_Park', 3: '44.Trevi_Fountain', 4: '32.Hanging_Temple'}" }, { "code": null, "e": 2637, "s": 2538, "text": "This is the core of our custom dataset. The structure of the dataset class is something like this:" }, { "code": null, "e": 2706, "s": 2637, "text": "We create our LandmarkDataset class by inheriting the Dataset class:" }, { "code": null, "e": 2743, "s": 2706, "text": "from torch.utils.data import Dataset" }, { "code": null, "e": 3223, "s": 2743, "text": "First, we define the __init__ function. As soon as we create an instance of our LandMarkDataset class, this function is called by default. This function should contain all operations that we want to run on the whole dataset (eg. train) once. The usage of this will be more clear in the next part of this series where we create a custom machine translation dataset. For now, we define the variables for image_paths and transforms for the corresponding Train, Valid, and Test sets." }, { "code": null, "e": 3363, "s": 3223, "text": "Then we have the __len__ function which just returns the length of the dataset. This is used afterward by the DataLoader to create batches." }, { "code": null, "e": 3447, "s": 3363, "text": "And finally, we have __getitem__. This processes and returns 1 datapoint at a time." }, { "code": null, "e": 3827, "s": 3447, "text": "As can be seen above, __getitem__ expects an index. This is handled automatically by the dataloader which for every image in the batch runs __getitem__. In the code for __getitem__, we load the image at index “idx”, extract the label from the file path and then run it through our defined transform. The function returns the Tensor of the image array and its corresponding label." }, { "code": null, "e": 3899, "s": 3827, "text": "After creating the train_dataset, we can access one example as follows:" }, { "code": null, "e": 4031, "s": 3899, "text": "output:The shape of tensor for 50th image in train dataset: torch.Size([3, 256, 256])The label for 50th image in train dataset: 37" }, { "code": null, "e": 4105, "s": 4031, "text": "Let’s visualize some images after augmentation through the train_dataset." }, { "code": null, "e": 4116, "s": 4105, "text": "Some more," }, { "code": null, "e": 4310, "s": 4116, "text": "The final step. DataLoader class is used to load data in batches for the model. This helps us processing data in mini-batches that can fit within our GPU’s RAM. First, we import the DataLoader:" }, { "code": null, "e": 4350, "s": 4310, "text": "from torch.utils.data import DataLoader" }, { "code": null, "e": 4435, "s": 4350, "text": "Initiating the dataloader by sending in an object of the dataset and the batch size." }, { "code": null, "e": 4541, "s": 4435, "text": "Once we have the dataloader instance — train_loader, we can use an iterator to access the data like this:" }, { "code": null, "e": 4724, "s": 4541, "text": "#batch of image tensornext(iter(train_loader))[0].shapeoutput:torch.Size([64, 3, 256, 256])#batch of the corresponding labelsnext(iter(train_loader))[1].shapeoutput: torch.Size([64])" }, { "code": null, "e": 4969, "s": 4724, "text": "This is what we use to batch out the data in our training loop. Every time we run the iterator, the dataloader selects the next 64 indexes and runs it through the __getitem__ in dataset class one by one and then returns it to the training loop." }, { "code": null, "e": 5297, "s": 4969, "text": "In part 1 of this 2 part series, we saw how we can write our own custom data pipeline. We also learned to use Albumentations for image augmentation. Further, we understood how Dataset and Dataloader classes work internally. In the next part, we’ll up the level by creating a custom dataset class for a Machine Translation task." }, { "code": null, "e": 5322, "s": 5297, "text": "See you in the next one!" } ]
HTML5 - range
The range type is used for input fields that should contain a value from a range of numbers. <!DOCTYPE HTML> <html> <body> <form action = "/cgi-bin/html5.cgi" method = "get"> Select Range : <input type = "range" min = "0" max = "10" step "1" value = "5" name = "newinput" /> <input type = "submit" value = "submit" /> </form> </body> </html> 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2701, "s": 2608, "text": "The range type is used for input fields that should contain a value from a range of numbers." }, { "code": null, "e": 3002, "s": 2701, "text": "<!DOCTYPE HTML>\n\n<html>\n <body>\n\n <form action = \"/cgi-bin/html5.cgi\" method = \"get\">\n Select Range : <input type = \"range\" min = \"0\" max = \"10\" step \"1\" \n value = \"5\" name = \"newinput\" />\n <input type = \"submit\" value = \"submit\" />\n </form>\n\n </body>\n</html>" }, { "code": null, "e": 3035, "s": 3002, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 3049, "s": 3035, "text": " Anadi Sharma" }, { "code": null, "e": 3084, "s": 3049, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3098, "s": 3084, "text": " Anadi Sharma" }, { "code": null, "e": 3133, "s": 3098, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3150, "s": 3133, "text": " Frahaan Hussain" }, { "code": null, "e": 3185, "s": 3150, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3216, "s": 3185, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3249, "s": 3216, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 3280, "s": 3249, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3315, "s": 3280, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3346, "s": 3315, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3353, "s": 3346, "text": " Print" }, { "code": null, "e": 3364, "s": 3353, "text": " Add Notes" } ]
How to Create Animated Plots in R | by Chanin Nantasenamat | Towards Data Science
A picture is worth a thousand words and so does the insights provided by graphs and plots. Data visualization is such an important part of any data science project as it allows effective data storytelling in the form of graphs and plots. Even static plots can convey important information and provide immense value, imagine what an animated plot can do to highlight particular aspects of a plot. Hans Rosling’s animated plot of the Gapminder data (for which he is the founder of) at his TED talks has captivated us all as it brings data to life. In this article, you will learn how to create a stunning animated plot in R using ggplot together with the gganimate R packages for a time series dataset. Watch the accompanying YouTube video: https://youtu.be/z9J78rxhcrQ Today, we’re going to build an animated scatter plot of the Gapminder dataset. Particularly, you will see that the plot is faceted (separated into distinct sub-plots) by the continents instead of having them all in the same plot (which can be quite messy). The animated plot will be build using ggplot2 and gganimate R packages. Shown below is the animated plot that we are building today (Source: gganimate). Now, fire up your IDE of choice whether it be RStudio, Kaggle Notebooks or a plain old R terminal. Within this coding environment you will be typing in the codes mentioned hereafter. My personal favorite for coding in R would have to be using the RStudio IDE, which is free and open source. In this tutorial, we’re using 4 R packages including gapminder, ggplot2, gganimate and gifski. To install these R packages, type the following into an R terminal (whether it be directly into an R terminal, in an R terminal from within the RStudio or in a code cell of a Kaggle Notebook. install.packages(c('gapminder','ggplot2','gganimate','gifski')) Let’s now take a look at why we’re using the above R packages. gapminder contains an excerpt of the Gapminder time series dataset that we are using in this tutorial. ggplot2 allows us to create awesome data visualizations namely the scatter plot gganimate allows us to add animation to the plots gifski allows us to render the animation as a GIF file format (GIF is a popular image format for animated images). Prior to our data visualization, let’s have a look at the Gapminder dataset. Here, we will start by loading the gapminder package and return the contents of the gapminder variable. Here, we can see that the data is a tibble (tidyverse’s implementation of a data frame) consisting of 1,704 rows and 6 columns. These 6 columns consists of: country — Names of the countries continent — Names of the continents year — Year of the data entry lifeExp — Life expectancy for the given year pop — Population count for the given year gdpPercap — Per capita GDP for the given year In this section, we will create a static version of the scatter plot that can be used as the baseline for comparison with the animated version. The code for creating the scatter plot is shown below: A screenshot of how I’m implementing the code in an RStudio: Line 1 — The ggplot() function is used for creating plots using the ggplot2 R package. The first input argument defines the input data that is stored in the gapminder variable. The aes() function allows aesthetic mapping of the input variables by defining the use of gdpPercap to be displayed on the X axis while defining lifeExp to be displayed on the Y axis. The size of each data point will now be dependent on the pop variable (the larger the pop value becomes the larger the data point also becomes). Finally, the color (particularly, the colour parameter) of the data points will be a function of the country for which it belongs to. Line 2 — geom_point() is used to define the alpha transparency (i.e. the data point will be translucent as defined by the alpha parameter of 0.7; the lower the value the more translucent they become) of each data point (i.e. the circles that we see on the plot). As implied, show.legend=FALSE will hide the legend. Line 3 — scale_colour_manual() function defines the color scheme stored in the country_colors variable that will be used for coloring data points according to the countries. Line 4 — scale_size() function defines the size range of the data points (i.e. recall that on Line 1 we defined in the aes() function that size=pop) to be in the range of 2 and 12 (i.e. 2 being small data points while 12 represents the largest data points). Line 5 — scale_x_log10() function logarithmically transforms the data in the X axis via log10. Line 6 — facet_wrap() function splits the plot to multiple sub-plots (i.e. this process is also known as facet) by using the continent variable. Line 7—labs() function defines the plot title, X axis title and Y axis title. From the above screenshot we can see that the plot is shown in the Plots panel (lower left panel) but is not saved to a file. To save the plot to a file, we will use the ggsave() function as follows: ggsave('plot_gdpPercap_lifeExp_static.png', width=8, height=8) This produces the resulting plot: Here comes the fun part, let’s now proceed to creating the animated scatter plot using the gganimate R package. The above code generates the following animated plot: Lines 1–6 — Explanation is the same as that of the static plot and thus please refer to the explanation in section 5.2. Line 7 — Commented text to hint that the lines that follows pertains to the animation component of the plot. Line 8 — labs() function defines the plot title, X axis title and Y axis title. {frame_time} will dynamically display the changing years as the data points move across the plot. Line 9 — transition_time() function takes in the year variable as an input and it allows the animated plot to transition frame by frame as a function of the year variable. Line 10 — ease_aes() function takes in linear as an input argument and it defines the transition of the frame to be in a linear fashion. As we can see Lines 1–10 are assigned to the p1 variable Line 12 — animate() function takes in the plot defined in the p1 variable as the input argument and performs rendering of the animation. Line 13 — anim_save() function allows saving the rendered animated plot to a .GIF file. So how do you customize this animated plot? In this section, we will explore which parameters we can adjust to further customize your animated plot. So instead of making a scatter plot for gdpPercap and lifeExp (in the X and Y axes), we can also consider other columns in the gapminder dataset. Let’s say that we would like to use these 2 variables: pop and lifeExp, we can define this within the ggplot() function. ggplot(gapminder, aes(pop, lifeExp, size = pop, colour = country)) Notice that in the above code we’re using pop and lifeExp as the first and second input arguments (as compared to using gdpPercap and lifeExp in the first plot). The resulting plot is as follows: By default, we can see that the animated plot is arranged as a 2 row × 3 columns layout. 7.2.1. Horizontal layout What if we want to change the layout to perhaps 1 row × 5 columns, how can we do that? Go to Section 6.1 to the line of code containing facet_wrap(~continent) (Hint: Line 6) and add ncol=5 as an additional input argument so that it becomes facet_wrap(~continent, ncol=5). Notice that the layout is updated as desired to be on 1 row and 5 columns. But a new problem emerges, the width of the sub-plot looks a bit too narrow. A solution to this is to make adjustments to the figure’s width and height. This can be done by adding 2 additional input arguments to the ggsave() function as follows: anim_save('plot_pop_lifeExp_wide.gif', width=1600, height=400) This should now give the following plot: 7.2.2. Vertical layout In a similar fashion, let’s now create a new plot having a vertical layout. We can do this by simply changing the assigned value of the ncol input argument of the facet_wrap() function. Earlier, the horizontal layout had: facet_wrap(~continent, ncol=5). Now, for the vertical layout we have: facet_wrap(~continent, ncol=1). You may notice that font sizes for the X/Y axes and tick labels may be small and you would like to adjust it. Let me show you how. Here’s an example code for adjusting the font properties mentioned above. You will notice that we have added Lines 7–13 which makes use of the theme() function to adjust the font sizes, faces and colors. Particularly, plot.title allows us to adjust the font for the plot’s title (which in our case is the Year label shown at the top left hand side of the plot. Here, we used a font size of 20, a font face of bold and a color of black. Similar adjustments also applies for the X and Y axes title (axis.title.x and axis.title.y, respectively), the X and Y tick labels (axis.text.x and axis.text.y, respectively), the facet sub-plot label (strip.text.x) and the white space around the plot image (plot.margin). The updated plot is shown (top image) while for comparative purpose we will show the original plot (bottom image) that we made earlier (using the default font size). The bigger font size does indeed help to provide better readability. In this summary, you have successfully created an animated scatter plot for a time series dataset (Gapminder) as well as learning how to make adjustments to the plot. What next? You can also experiment with making animated plots for other time series data such as visualizing price information of Cryptocurrencies, Air Quality indices, etc. Let me know in the comments, for which datasets are you creating animated plots for. Aside from the animated plot for time series data, you can also experiment with the gganimate R package to spice up other data visualization and add animation to it such as box plots I work full-time as an Associate Professor of Bioinformatics and Head of Data Mining and Biomedical Informatics at a Research University in Thailand. In my after work hours, I’m a YouTuber (AKA the Data Professor) making online videos about data science. In all tutorial videos that I make, I also share Jupyter notebooks on GitHub (Data Professor GitHub page). www.youtube.com ✅ YouTube: http://youtube.com/dataprofessor/✅ Website: http://dataprofessor.org/ (Under construction)✅ LinkedIn: https://www.linkedin.com/company/dataprofessor/✅ Twitter: https://twitter.com/thedataprof/✅ FaceBook: http://facebook.com/dataprofessor/✅ GitHub: https://github.com/dataprofessor/✅ Instagram: https://www.instagram.com/data.professor/
[ { "code": null, "e": 568, "s": 172, "text": "A picture is worth a thousand words and so does the insights provided by graphs and plots. Data visualization is such an important part of any data science project as it allows effective data storytelling in the form of graphs and plots. Even static plots can convey important information and provide immense value, imagine what an animated plot can do to highlight particular aspects of a plot." }, { "code": null, "e": 718, "s": 568, "text": "Hans Rosling’s animated plot of the Gapminder data (for which he is the founder of) at his TED talks has captivated us all as it brings data to life." }, { "code": null, "e": 873, "s": 718, "text": "In this article, you will learn how to create a stunning animated plot in R using ggplot together with the gganimate R packages for a time series dataset." }, { "code": null, "e": 940, "s": 873, "text": "Watch the accompanying YouTube video: https://youtu.be/z9J78rxhcrQ" }, { "code": null, "e": 1197, "s": 940, "text": "Today, we’re going to build an animated scatter plot of the Gapminder dataset. Particularly, you will see that the plot is faceted (separated into distinct sub-plots) by the continents instead of having them all in the same plot (which can be quite messy)." }, { "code": null, "e": 1269, "s": 1197, "text": "The animated plot will be build using ggplot2 and gganimate R packages." }, { "code": null, "e": 1350, "s": 1269, "text": "Shown below is the animated plot that we are building today (Source: gganimate)." }, { "code": null, "e": 1533, "s": 1350, "text": "Now, fire up your IDE of choice whether it be RStudio, Kaggle Notebooks or a plain old R terminal. Within this coding environment you will be typing in the codes mentioned hereafter." }, { "code": null, "e": 1641, "s": 1533, "text": "My personal favorite for coding in R would have to be using the RStudio IDE, which is free and open source." }, { "code": null, "e": 1736, "s": 1641, "text": "In this tutorial, we’re using 4 R packages including gapminder, ggplot2, gganimate and gifski." }, { "code": null, "e": 1928, "s": 1736, "text": "To install these R packages, type the following into an R terminal (whether it be directly into an R terminal, in an R terminal from within the RStudio or in a code cell of a Kaggle Notebook." }, { "code": null, "e": 1992, "s": 1928, "text": "install.packages(c('gapminder','ggplot2','gganimate','gifski'))" }, { "code": null, "e": 2055, "s": 1992, "text": "Let’s now take a look at why we’re using the above R packages." }, { "code": null, "e": 2158, "s": 2055, "text": "gapminder contains an excerpt of the Gapminder time series dataset that we are using in this tutorial." }, { "code": null, "e": 2238, "s": 2158, "text": "ggplot2 allows us to create awesome data visualizations namely the scatter plot" }, { "code": null, "e": 2288, "s": 2238, "text": "gganimate allows us to add animation to the plots" }, { "code": null, "e": 2403, "s": 2288, "text": "gifski allows us to render the animation as a GIF file format (GIF is a popular image format for animated images)." }, { "code": null, "e": 2480, "s": 2403, "text": "Prior to our data visualization, let’s have a look at the Gapminder dataset." }, { "code": null, "e": 2584, "s": 2480, "text": "Here, we will start by loading the gapminder package and return the contents of the gapminder variable." }, { "code": null, "e": 2712, "s": 2584, "text": "Here, we can see that the data is a tibble (tidyverse’s implementation of a data frame) consisting of 1,704 rows and 6 columns." }, { "code": null, "e": 2741, "s": 2712, "text": "These 6 columns consists of:" }, { "code": null, "e": 2774, "s": 2741, "text": "country — Names of the countries" }, { "code": null, "e": 2810, "s": 2774, "text": "continent — Names of the continents" }, { "code": null, "e": 2840, "s": 2810, "text": "year — Year of the data entry" }, { "code": null, "e": 2885, "s": 2840, "text": "lifeExp — Life expectancy for the given year" }, { "code": null, "e": 2927, "s": 2885, "text": "pop — Population count for the given year" }, { "code": null, "e": 2973, "s": 2927, "text": "gdpPercap — Per capita GDP for the given year" }, { "code": null, "e": 3117, "s": 2973, "text": "In this section, we will create a static version of the scatter plot that can be used as the baseline for comparison with the animated version." }, { "code": null, "e": 3172, "s": 3117, "text": "The code for creating the scatter plot is shown below:" }, { "code": null, "e": 3233, "s": 3172, "text": "A screenshot of how I’m implementing the code in an RStudio:" }, { "code": null, "e": 3873, "s": 3233, "text": "Line 1 — The ggplot() function is used for creating plots using the ggplot2 R package. The first input argument defines the input data that is stored in the gapminder variable. The aes() function allows aesthetic mapping of the input variables by defining the use of gdpPercap to be displayed on the X axis while defining lifeExp to be displayed on the Y axis. The size of each data point will now be dependent on the pop variable (the larger the pop value becomes the larger the data point also becomes). Finally, the color (particularly, the colour parameter) of the data points will be a function of the country for which it belongs to." }, { "code": null, "e": 4188, "s": 3873, "text": "Line 2 — geom_point() is used to define the alpha transparency (i.e. the data point will be translucent as defined by the alpha parameter of 0.7; the lower the value the more translucent they become) of each data point (i.e. the circles that we see on the plot). As implied, show.legend=FALSE will hide the legend." }, { "code": null, "e": 4362, "s": 4188, "text": "Line 3 — scale_colour_manual() function defines the color scheme stored in the country_colors variable that will be used for coloring data points according to the countries." }, { "code": null, "e": 4620, "s": 4362, "text": "Line 4 — scale_size() function defines the size range of the data points (i.e. recall that on Line 1 we defined in the aes() function that size=pop) to be in the range of 2 and 12 (i.e. 2 being small data points while 12 represents the largest data points)." }, { "code": null, "e": 4715, "s": 4620, "text": "Line 5 — scale_x_log10() function logarithmically transforms the data in the X axis via log10." }, { "code": null, "e": 4860, "s": 4715, "text": "Line 6 — facet_wrap() function splits the plot to multiple sub-plots (i.e. this process is also known as facet) by using the continent variable." }, { "code": null, "e": 4938, "s": 4860, "text": "Line 7—labs() function defines the plot title, X axis title and Y axis title." }, { "code": null, "e": 5064, "s": 4938, "text": "From the above screenshot we can see that the plot is shown in the Plots panel (lower left panel) but is not saved to a file." }, { "code": null, "e": 5138, "s": 5064, "text": "To save the plot to a file, we will use the ggsave() function as follows:" }, { "code": null, "e": 5201, "s": 5138, "text": "ggsave('plot_gdpPercap_lifeExp_static.png', width=8, height=8)" }, { "code": null, "e": 5235, "s": 5201, "text": "This produces the resulting plot:" }, { "code": null, "e": 5347, "s": 5235, "text": "Here comes the fun part, let’s now proceed to creating the animated scatter plot using the gganimate R package." }, { "code": null, "e": 5401, "s": 5347, "text": "The above code generates the following animated plot:" }, { "code": null, "e": 5521, "s": 5401, "text": "Lines 1–6 — Explanation is the same as that of the static plot and thus please refer to the explanation in section 5.2." }, { "code": null, "e": 5630, "s": 5521, "text": "Line 7 — Commented text to hint that the lines that follows pertains to the animation component of the plot." }, { "code": null, "e": 5808, "s": 5630, "text": "Line 8 — labs() function defines the plot title, X axis title and Y axis title. {frame_time} will dynamically display the changing years as the data points move across the plot." }, { "code": null, "e": 5980, "s": 5808, "text": "Line 9 — transition_time() function takes in the year variable as an input and it allows the animated plot to transition frame by frame as a function of the year variable." }, { "code": null, "e": 6117, "s": 5980, "text": "Line 10 — ease_aes() function takes in linear as an input argument and it defines the transition of the frame to be in a linear fashion." }, { "code": null, "e": 6174, "s": 6117, "text": "As we can see Lines 1–10 are assigned to the p1 variable" }, { "code": null, "e": 6311, "s": 6174, "text": "Line 12 — animate() function takes in the plot defined in the p1 variable as the input argument and performs rendering of the animation." }, { "code": null, "e": 6399, "s": 6311, "text": "Line 13 — anim_save() function allows saving the rendered animated plot to a .GIF file." }, { "code": null, "e": 6443, "s": 6399, "text": "So how do you customize this animated plot?" }, { "code": null, "e": 6548, "s": 6443, "text": "In this section, we will explore which parameters we can adjust to further customize your animated plot." }, { "code": null, "e": 6694, "s": 6548, "text": "So instead of making a scatter plot for gdpPercap and lifeExp (in the X and Y axes), we can also consider other columns in the gapminder dataset." }, { "code": null, "e": 6815, "s": 6694, "text": "Let’s say that we would like to use these 2 variables: pop and lifeExp, we can define this within the ggplot() function." }, { "code": null, "e": 6882, "s": 6815, "text": "ggplot(gapminder, aes(pop, lifeExp, size = pop, colour = country))" }, { "code": null, "e": 7044, "s": 6882, "text": "Notice that in the above code we’re using pop and lifeExp as the first and second input arguments (as compared to using gdpPercap and lifeExp in the first plot)." }, { "code": null, "e": 7078, "s": 7044, "text": "The resulting plot is as follows:" }, { "code": null, "e": 7167, "s": 7078, "text": "By default, we can see that the animated plot is arranged as a 2 row × 3 columns layout." }, { "code": null, "e": 7192, "s": 7167, "text": "7.2.1. Horizontal layout" }, { "code": null, "e": 7279, "s": 7192, "text": "What if we want to change the layout to perhaps 1 row × 5 columns, how can we do that?" }, { "code": null, "e": 7464, "s": 7279, "text": "Go to Section 6.1 to the line of code containing facet_wrap(~continent) (Hint: Line 6) and add ncol=5 as an additional input argument so that it becomes facet_wrap(~continent, ncol=5)." }, { "code": null, "e": 7616, "s": 7464, "text": "Notice that the layout is updated as desired to be on 1 row and 5 columns. But a new problem emerges, the width of the sub-plot looks a bit too narrow." }, { "code": null, "e": 7785, "s": 7616, "text": "A solution to this is to make adjustments to the figure’s width and height. This can be done by adding 2 additional input arguments to the ggsave() function as follows:" }, { "code": null, "e": 7848, "s": 7785, "text": "anim_save('plot_pop_lifeExp_wide.gif', width=1600, height=400)" }, { "code": null, "e": 7889, "s": 7848, "text": "This should now give the following plot:" }, { "code": null, "e": 7912, "s": 7889, "text": "7.2.2. Vertical layout" }, { "code": null, "e": 7988, "s": 7912, "text": "In a similar fashion, let’s now create a new plot having a vertical layout." }, { "code": null, "e": 8098, "s": 7988, "text": "We can do this by simply changing the assigned value of the ncol input argument of the facet_wrap() function." }, { "code": null, "e": 8134, "s": 8098, "text": "Earlier, the horizontal layout had:" }, { "code": null, "e": 8166, "s": 8134, "text": "facet_wrap(~continent, ncol=5)." }, { "code": null, "e": 8204, "s": 8166, "text": "Now, for the vertical layout we have:" }, { "code": null, "e": 8236, "s": 8204, "text": "facet_wrap(~continent, ncol=1)." }, { "code": null, "e": 8367, "s": 8236, "text": "You may notice that font sizes for the X/Y axes and tick labels may be small and you would like to adjust it. Let me show you how." }, { "code": null, "e": 8441, "s": 8367, "text": "Here’s an example code for adjusting the font properties mentioned above." }, { "code": null, "e": 8571, "s": 8441, "text": "You will notice that we have added Lines 7–13 which makes use of the theme() function to adjust the font sizes, faces and colors." }, { "code": null, "e": 9076, "s": 8571, "text": "Particularly, plot.title allows us to adjust the font for the plot’s title (which in our case is the Year label shown at the top left hand side of the plot. Here, we used a font size of 20, a font face of bold and a color of black. Similar adjustments also applies for the X and Y axes title (axis.title.x and axis.title.y, respectively), the X and Y tick labels (axis.text.x and axis.text.y, respectively), the facet sub-plot label (strip.text.x) and the white space around the plot image (plot.margin)." }, { "code": null, "e": 9311, "s": 9076, "text": "The updated plot is shown (top image) while for comparative purpose we will show the original plot (bottom image) that we made earlier (using the default font size). The bigger font size does indeed help to provide better readability." }, { "code": null, "e": 9478, "s": 9311, "text": "In this summary, you have successfully created an animated scatter plot for a time series dataset (Gapminder) as well as learning how to make adjustments to the plot." }, { "code": null, "e": 9737, "s": 9478, "text": "What next? You can also experiment with making animated plots for other time series data such as visualizing price information of Cryptocurrencies, Air Quality indices, etc. Let me know in the comments, for which datasets are you creating animated plots for." }, { "code": null, "e": 9920, "s": 9737, "text": "Aside from the animated plot for time series data, you can also experiment with the gganimate R package to spice up other data visualization and add animation to it such as box plots" }, { "code": null, "e": 10282, "s": 9920, "text": "I work full-time as an Associate Professor of Bioinformatics and Head of Data Mining and Biomedical Informatics at a Research University in Thailand. In my after work hours, I’m a YouTuber (AKA the Data Professor) making online videos about data science. In all tutorial videos that I make, I also share Jupyter notebooks on GitHub (Data Professor GitHub page)." }, { "code": null, "e": 10298, "s": 10282, "text": "www.youtube.com" } ]
How do you create a Button on a tkinter Canvas? - GeeksforGeeks
03 Jan, 2021 In this article, we will see how to create a button on a Tkinter Canvas. The Canvas widget display various graphics on the application. It can be used to draw simple shapes to complicated graphs. We can also display various kinds of custom widgets according to our needs. It is used trigger any function which is presented in the code Intro to code : In this we try to create button on canvas widget. Firstly make canvas then place the button on the canvas. Syntax: C = Canvas(root, height, width, bd, bg) Syntax: button = Button ( root,height,width,bg,command) Steps : Import tkinter fromThen define the window size and other requirements.First create canvas from the above give syntax.With the help of place function in tkinter place the button. Import tkinter from Then define the window size and other requirements. First create canvas from the above give syntax. With the help of place function in tkinter place the button. Python3 # import everything from tkinter modulefrom tkinter import * root = Tk() root.geometry('430x300') title = Label(root, text="Geeksforgeeks", bg="green", font=("bold", 30))title.pack()c = Canvas(root, width=330, height=200, bg="red")c.place(x=50, y=50)btn = Button(root, text='Welcome to Tkinter!', width=40, height=5, bd='10', command=root.destroy) btn.place(x=65, y=100) root.mainloop() OUTPUT: Picked Python-tkinter Technical Scripter 2020 Python Technical Scripter 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 ? 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 Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n03 Jan, 2021" }, { "code": null, "e": 23974, "s": 23901, "text": "In this article, we will see how to create a button on a Tkinter Canvas." }, { "code": null, "e": 24173, "s": 23974, "text": "The Canvas widget display various graphics on the application. It can be used to draw simple shapes to complicated graphs. We can also display various kinds of custom widgets according to our needs." }, { "code": null, "e": 24237, "s": 24173, "text": " It is used trigger any function which is presented in the code" }, { "code": null, "e": 24253, "s": 24237, "text": "Intro to code :" }, { "code": null, "e": 24360, "s": 24253, "text": "In this we try to create button on canvas widget. Firstly make canvas then place the button on the canvas." }, { "code": null, "e": 24368, "s": 24360, "text": "Syntax:" }, { "code": null, "e": 24408, "s": 24368, "text": "C = Canvas(root, height, width, bd, bg)" }, { "code": null, "e": 24416, "s": 24408, "text": "Syntax:" }, { "code": null, "e": 24464, "s": 24416, "text": "button = Button ( root,height,width,bg,command)" }, { "code": null, "e": 24472, "s": 24464, "text": "Steps :" }, { "code": null, "e": 24650, "s": 24472, "text": "Import tkinter fromThen define the window size and other requirements.First create canvas from the above give syntax.With the help of place function in tkinter place the button." }, { "code": null, "e": 24670, "s": 24650, "text": "Import tkinter from" }, { "code": null, "e": 24722, "s": 24670, "text": "Then define the window size and other requirements." }, { "code": null, "e": 24770, "s": 24722, "text": "First create canvas from the above give syntax." }, { "code": null, "e": 24831, "s": 24770, "text": "With the help of place function in tkinter place the button." }, { "code": null, "e": 24839, "s": 24831, "text": "Python3" }, { "code": "# import everything from tkinter modulefrom tkinter import * root = Tk() root.geometry('430x300') title = Label(root, text=\"Geeksforgeeks\", bg=\"green\", font=(\"bold\", 30))title.pack()c = Canvas(root, width=330, height=200, bg=\"red\")c.place(x=50, y=50)btn = Button(root, text='Welcome to Tkinter!', width=40, height=5, bd='10', command=root.destroy) btn.place(x=65, y=100) root.mainloop()", "e": 25243, "s": 24839, "text": null }, { "code": null, "e": 25251, "s": 25243, "text": "OUTPUT:" }, { "code": null, "e": 25258, "s": 25251, "text": "Picked" }, { "code": null, "e": 25273, "s": 25258, "text": "Python-tkinter" }, { "code": null, "e": 25297, "s": 25273, "text": "Technical Scripter 2020" }, { "code": null, "e": 25304, "s": 25297, "text": "Python" }, { "code": null, "e": 25323, "s": 25304, "text": "Technical Scripter" }, { "code": null, "e": 25421, "s": 25323, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25430, "s": 25421, "text": "Comments" }, { "code": null, "e": 25443, "s": 25430, "text": "Old Comments" }, { "code": null, "e": 25475, "s": 25443, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25531, "s": 25475, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25573, "s": 25531, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25615, "s": 25573, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25651, "s": 25615, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 25673, "s": 25651, "text": "Defaultdict in Python" }, { "code": null, "e": 25712, "s": 25673, "text": "Python | Get unique values from a list" }, { "code": null, "e": 25739, "s": 25712, "text": "Python Classes and Objects" }, { "code": null, "e": 25770, "s": 25739, "text": "Python | os.path.join() method" } ]
LSTM vs BERT — a step-by-step guide for tweet sentiment analysis | by Yuki Takahashi | Towards Data Science
Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details. After seeing the competitive result of BERT in the sentiment analysis on financial text, I performed another preliminary study on more informal text as the ultimate goal is to analyse traders’ voice over the phones and chat in addition to the news sentiment. In this post, I let LSTM and BERT analyse a number of tweets from Stocktwit. Unlike formal financial text, traders voice and chat contains by far informal languages. Traditional rule based models or simple vectorisation techniques such as BoW, Tfidf, word2vec saw poor performance in my past research because of the fact that a word is often used for different meanings in each context spelling and sentence is far from grammatically correct language the balance of grouping words by stemming, lemmatizing, stop words removal, etc. and keeping the original forms is difficult a dictionary has to be built specifically on this language for a rule based approach, where I failed to generalise enough LSTM, which has been one of the most famous RNN based model in NLP, performed well. It is largely thanks to the fact that sentence structure is fairly straightforward — simply process from left to right will suffice each input text is short and good size of history to remember the task is rather simple classification On the other hand, BERT I used here was pretrained on wikipedia, where the language is pretty different. Training BERT from scratch was not option due to the limitation of resources. In this situation, would it still be worth trying BERT for better performance than LSTM? The input text here is taken from Stocktwits as the similar language of traders’ voice here. There are around one million tweets that have been hand-labelled with 0 (negative) to 4 (positive), which have been loaded as messages and sentiments list respectively. Note that actual environments usually need a lot more work to do on preparing the inputs such as the sound recognition, data clean-up, streaming infra. This post skip those steps and start from the point where the data have been loaded. > ##### Sample input messages ######> print(messages)["$AMZN sick! they’re running a prime flash sale on shares too!", "$AAPL has a good Piotroski-F score of 7.00. This indicates a good health and profitability. https://www.chartmill.com/analyze.php?utm_source=stocktwits&amp;utm_medium=FA&amp;utm_content=PROFITABILITY&amp;utm_campaign=social_tracking#/AAPL?r=fa&amp;key=bb853040-a4ac-41c6-b549-d218d2f21b32", "$FB got rid of this trash today, i admit that bears were right", ...]> print(sentiments)[4, 2, 0, ...] Before the training, the input texts need preprocessing such as removing URL, ticker symbols, @mentions, symbols etc. Here I simply remove them as it will not be available in voices, but there’re also interesting researches on how to utilise such information such as emoticons and hashtags rather than removing them if the final goal is to analyse the tweet text. Now the input has been cleaned up as follows. > ###### Input messages after preprocessing ######> print(preprocessed)["sick they re running a prime flash sale on shares too", "has a good piotroski f score of this indicates a good health and profitability", "got rid of this trash today i admit that bears were right", ...] The next step is to tokenize the text. Here, I use python NLTK library but also give options to use different ways to see what works best for the input. After a few experiments, I decided to use nltk.word_tokenize() without the lemmatization and stopword removal. Once the input text is tokenized, we can create a corpus and vocab in the following manner. Word Cloud or bar chart is a good way to quickly view the frequent words in the input. The distribution shows the label is imbalanced having more neutral than other sentiments. It is possible to balance the data by resampling (under- or over-) but here take as they are because this ratio would represent actual occurrence of the sentiment in the tweet stream. Now that the input data are ready, create the neural network based model and tokenizer for the model. Use pytorch to create a LSTM based model. The class extends torch.nn.Module and define the layers as embedding → lstm → dropout → dense (fully-connected) → output (softmax). The tokenizer for LSTM is to pad the input to the right or to the left up to the specified maximum length and truncate if the input exceeds the maximum length, designed to be used during the training for each batch instead of preprocess all inputs. Here I use the Hugging Face implementation of BERT. Simply use their transformers and pre-trained model and tokenizer. Create a dataset class and data loader for batching. There are many different ways to define them and this is just a very simple solution to be used with the defined tokenizer which returns torch.tensor. The performance was measured in terms of accuracy, f1 and training time for different input sizes. Use Stratified Shuffle Split from scikit-learn that can perform under-sampling by preserving the label distrubtion, based on given train and test size. In each loop, measure the duration by perf_counter() for completing the training. Also, define a simple function to return Accuracy and F1 score. Note that model parameters are defined here when instantiating the model classes, which can be updated according to the input data. Define the training process as follows: Loop the training batchesRun the evaluation at every 1/5 of the entire dataOnce an epoch is complete, show the resultEnd if the score is not improved beyond the patience, or start the next epoch Loop the training batches Run the evaluation at every 1/5 of the entire data Once an epoch is complete, show the result End if the score is not improved beyond the patience, or start the next epoch AdamW Optimizer and Linear Schedule with Warmup for the learning rate are used but these can be swapped with other options as needed. In each training batch cycle, tokenize the input messages and move to torch.tensor, perform the feedforward prediction, calculate the loss and back propagate to update the weights. Clipping to avoid exploding gradient problem before the next batch step. At the end of each epoch shows Confusion Matrix and scores/loss for both training and validation data. Finally :) After the first epoch of the smallest samples (n=1,000), the model simply classify all data as ‘Neutral’, which is reasonable as the ‘Neutral’ is the majority class. Completing the five epochs, it looks to have classified the data almost at random. It starts overfitting to the training data from the third epoch (= validation cycle = 10). The largest dataset (n=500,000) contains 500 times more data than the first cycle. It performed much better and now classify most of labels correctly. Overfitting from the fourth cycle, so three epochs will be the best. Three epochs of training the pretrained BERT took almost the same time as the five epochs of the above LSTM model. BERT shows the similar result but it starts overfitting in third epoch for the largest dataset (n = 500,000). As shown below, it naturally performed better as the number of input data increases and reach 75%+ score at around 100k data. BERT performed a little better than LSTM but no significant difference when the models are trained for the same amount of time. In this post, tweets from stockswits are cleaned, tokenized and analyzed to predict the sentiment by a LSTM model as well as a pretrained BERT model. Given the same resource and time, the pretrained BERT perfomed slightly better than LSTM but no significant difference. Potentially, training the BERT model from scratch on similar tweets could produce much better result, while the required resources and cost is beyond this study. Here is a piece of code which handles tweet stream as input and output the sentiment with confidence level, using the trained model above. Sample output shown as follows.
[ { "code": null, "e": 471, "s": 171, "text": "Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details." }, { "code": null, "e": 807, "s": 471, "text": "After seeing the competitive result of BERT in the sentiment analysis on financial text, I performed another preliminary study on more informal text as the ultimate goal is to analyse traders’ voice over the phones and chat in addition to the news sentiment. In this post, I let LSTM and BERT analyse a number of tweets from Stocktwit." }, { "code": null, "e": 1056, "s": 807, "text": "Unlike formal financial text, traders voice and chat contains by far informal languages. Traditional rule based models or simple vectorisation techniques such as BoW, Tfidf, word2vec saw poor performance in my past research because of the fact that" }, { "code": null, "e": 1116, "s": 1056, "text": "a word is often used for different meanings in each context" }, { "code": null, "e": 1181, "s": 1116, "text": "spelling and sentence is far from grammatically correct language" }, { "code": null, "e": 1306, "s": 1181, "text": "the balance of grouping words by stemming, lemmatizing, stop words removal, etc. and keeping the original forms is difficult" }, { "code": null, "e": 1428, "s": 1306, "text": "a dictionary has to be built specifically on this language for a rule based approach, where I failed to generalise enough" }, { "code": null, "e": 1550, "s": 1428, "text": "LSTM, which has been one of the most famous RNN based model in NLP, performed well. It is largely thanks to the fact that" }, { "code": null, "e": 1644, "s": 1550, "text": "sentence structure is fairly straightforward — simply process from left to right will suffice" }, { "code": null, "e": 1706, "s": 1644, "text": "each input text is short and good size of history to remember" }, { "code": null, "e": 1747, "s": 1706, "text": "the task is rather simple classification" }, { "code": null, "e": 2019, "s": 1747, "text": "On the other hand, BERT I used here was pretrained on wikipedia, where the language is pretty different. Training BERT from scratch was not option due to the limitation of resources. In this situation, would it still be worth trying BERT for better performance than LSTM?" }, { "code": null, "e": 2518, "s": 2019, "text": "The input text here is taken from Stocktwits as the similar language of traders’ voice here. There are around one million tweets that have been hand-labelled with 0 (negative) to 4 (positive), which have been loaded as messages and sentiments list respectively. Note that actual environments usually need a lot more work to do on preparing the inputs such as the sound recognition, data clean-up, streaming infra. This post skip those steps and start from the point where the data have been loaded." }, { "code": null, "e": 3033, "s": 2518, "text": "> ##### Sample input messages ######> print(messages)[\"$AMZN sick! they’re running a prime flash sale on shares too!\", \"$AAPL has a good Piotroski-F score of 7.00. This indicates a good health and profitability. https://www.chartmill.com/analyze.php?utm_source=stocktwits&amp;utm_medium=FA&amp;utm_content=PROFITABILITY&amp;utm_campaign=social_tracking#/AAPL?r=fa&amp;key=bb853040-a4ac-41c6-b549-d218d2f21b32\", \"$FB got rid of this trash today, i admit that bears were right\", ...]> print(sentiments)[4, 2, 0, ...]" }, { "code": null, "e": 3397, "s": 3033, "text": "Before the training, the input texts need preprocessing such as removing URL, ticker symbols, @mentions, symbols etc. Here I simply remove them as it will not be available in voices, but there’re also interesting researches on how to utilise such information such as emoticons and hashtags rather than removing them if the final goal is to analyse the tweet text." }, { "code": null, "e": 3443, "s": 3397, "text": "Now the input has been cleaned up as follows." }, { "code": null, "e": 3720, "s": 3443, "text": "> ###### Input messages after preprocessing ######> print(preprocessed)[\"sick they re running a prime flash sale on shares too\", \"has a good piotroski f score of this indicates a good health and profitability\", \"got rid of this trash today i admit that bears were right\", ...]" }, { "code": null, "e": 3984, "s": 3720, "text": "The next step is to tokenize the text. Here, I use python NLTK library but also give options to use different ways to see what works best for the input. After a few experiments, I decided to use nltk.word_tokenize() without the lemmatization and stopword removal." }, { "code": null, "e": 4437, "s": 3984, "text": "Once the input text is tokenized, we can create a corpus and vocab in the following manner. Word Cloud or bar chart is a good way to quickly view the frequent words in the input. The distribution shows the label is imbalanced having more neutral than other sentiments. It is possible to balance the data by resampling (under- or over-) but here take as they are because this ratio would represent actual occurrence of the sentiment in the tweet stream." }, { "code": null, "e": 4539, "s": 4437, "text": "Now that the input data are ready, create the neural network based model and tokenizer for the model." }, { "code": null, "e": 4962, "s": 4539, "text": "Use pytorch to create a LSTM based model. The class extends torch.nn.Module and define the layers as embedding → lstm → dropout → dense (fully-connected) → output (softmax). The tokenizer for LSTM is to pad the input to the right or to the left up to the specified maximum length and truncate if the input exceeds the maximum length, designed to be used during the training for each batch instead of preprocess all inputs." }, { "code": null, "e": 5081, "s": 4962, "text": "Here I use the Hugging Face implementation of BERT. Simply use their transformers and pre-trained model and tokenizer." }, { "code": null, "e": 5285, "s": 5081, "text": "Create a dataset class and data loader for batching. There are many different ways to define them and this is just a very simple solution to be used with the defined tokenizer which returns torch.tensor." }, { "code": null, "e": 5618, "s": 5285, "text": "The performance was measured in terms of accuracy, f1 and training time for different input sizes. Use Stratified Shuffle Split from scikit-learn that can perform under-sampling by preserving the label distrubtion, based on given train and test size. In each loop, measure the duration by perf_counter() for completing the training." }, { "code": null, "e": 5682, "s": 5618, "text": "Also, define a simple function to return Accuracy and F1 score." }, { "code": null, "e": 5814, "s": 5682, "text": "Note that model parameters are defined here when instantiating the model classes, which can be updated according to the input data." }, { "code": null, "e": 5854, "s": 5814, "text": "Define the training process as follows:" }, { "code": null, "e": 6049, "s": 5854, "text": "Loop the training batchesRun the evaluation at every 1/5 of the entire dataOnce an epoch is complete, show the resultEnd if the score is not improved beyond the patience, or start the next epoch" }, { "code": null, "e": 6075, "s": 6049, "text": "Loop the training batches" }, { "code": null, "e": 6126, "s": 6075, "text": "Run the evaluation at every 1/5 of the entire data" }, { "code": null, "e": 6169, "s": 6126, "text": "Once an epoch is complete, show the result" }, { "code": null, "e": 6247, "s": 6169, "text": "End if the score is not improved beyond the patience, or start the next epoch" }, { "code": null, "e": 6381, "s": 6247, "text": "AdamW Optimizer and Linear Schedule with Warmup for the learning rate are used but these can be swapped with other options as needed." }, { "code": null, "e": 6635, "s": 6381, "text": "In each training batch cycle, tokenize the input messages and move to torch.tensor, perform the feedforward prediction, calculate the loss and back propagate to update the weights. Clipping to avoid exploding gradient problem before the next batch step." }, { "code": null, "e": 6738, "s": 6635, "text": "At the end of each epoch shows Confusion Matrix and scores/loss for both training and validation data." }, { "code": null, "e": 6749, "s": 6738, "text": "Finally :)" }, { "code": null, "e": 6915, "s": 6749, "text": "After the first epoch of the smallest samples (n=1,000), the model simply classify all data as ‘Neutral’, which is reasonable as the ‘Neutral’ is the majority class." }, { "code": null, "e": 7089, "s": 6915, "text": "Completing the five epochs, it looks to have classified the data almost at random. It starts overfitting to the training data from the third epoch (= validation cycle = 10)." }, { "code": null, "e": 7309, "s": 7089, "text": "The largest dataset (n=500,000) contains 500 times more data than the first cycle. It performed much better and now classify most of labels correctly. Overfitting from the fourth cycle, so three epochs will be the best." }, { "code": null, "e": 7424, "s": 7309, "text": "Three epochs of training the pretrained BERT took almost the same time as the five epochs of the above LSTM model." }, { "code": null, "e": 7534, "s": 7424, "text": "BERT shows the similar result but it starts overfitting in third epoch for the largest dataset (n = 500,000)." }, { "code": null, "e": 7788, "s": 7534, "text": "As shown below, it naturally performed better as the number of input data increases and reach 75%+ score at around 100k data. BERT performed a little better than LSTM but no significant difference when the models are trained for the same amount of time." }, { "code": null, "e": 7938, "s": 7788, "text": "In this post, tweets from stockswits are cleaned, tokenized and analyzed to predict the sentiment by a LSTM model as well as a pretrained BERT model." }, { "code": null, "e": 8058, "s": 7938, "text": "Given the same resource and time, the pretrained BERT perfomed slightly better than LSTM but no significant difference." }, { "code": null, "e": 8220, "s": 8058, "text": "Potentially, training the BERT model from scratch on similar tweets could produce much better result, while the required resources and cost is beyond this study." }, { "code": null, "e": 8359, "s": 8220, "text": "Here is a piece of code which handles tweet stream as input and output the sentiment with confidence level, using the trained model above." } ]
Community detection of the countries of the world with Neo4j Graph Data Science | by Tomaz Bratanic | Towards Data Science
While I was waiting for my sourdough to rise, I thought, the best way to spend my time is to perform a network analysis with the Neo4j Graph data science library. Well, maybe also try to draw an acrylic painting, but I won’t bore you with that. If this is the first time you have heard of the GDS library, I can recommend some of my previous blog posts that try to explain the basics: GDS Native projection GDS Cypher projection GDS Multigraph projection If you are ready, it’s time to put on our graph data science hat and get down to business. Neo4j Neo4j APOC plugin Neo4j Graph data science plugin We will be using the Countries of the world dataset made available on Kaggle by Fernando Lasso. Looking at the acknowledgements, the data originates from the CIA’s World Factbook. Unfortunately, the contributor did not provide the year the dataset was compiled. My guess is the year 2013, but I might be wrong. The dataset contains various metrics like area size, population, infant mortality, and more about 227 countries of the world. The graph schema consists of nodes labeled Country that have their features stored as properties. A Country is also a part of a Region. First, we need to download the dataset and copy it to the $Neo4j/import folder. For some reason, the numbers in the CSV file use a comma as a floating point instead of a dot (0,1 instead of 0.1). We need to preprocess the data to be able to cast the numbers to float in Neo4j. With the help of an APOC procedure apoc.cypher.run , we can preprocess and store the data in a single cypher query. apoc.cypher.run allows us to run independent subqueries within the main cypher query and is excellent for various use cases. LOAD CSV WITH HEADERS FROM "file:///countries%20of%20the%20world.csv" as row// cleanup the data and replace comma floating point with a dotCALL apoc.cypher.run( "UNWIND keys($row) as key WITH row, key, toFloat(replace(row[key],',','.')) as clean_value // exclude string properties WHERE NOT key in ['Country','Region'] RETURN collect([key,clean_value]) as keys", {row:row}) YIELD valueMERGE (c:Country{name:trim(row.Country)})SET c+= apoc.map.fromPairs(value.keys)MERGE (r:Region{name:trim(row.Region)})MERGE (c)-[:PART_OF]->(r) Another useful APOC procedure is apoc.meta.nodeTypeProperties. With it, we can examine the node property schema of the graph. We will use it to identify how many missing values each feature of the country has. // Only look at properties of nodes labeled "Country"CALL apoc.meta.nodeTypeProperties({labels:['Country']})YIELD propertyName, propertyObservations, totalObservationsRETURN propertyName, (totalObservations - propertyObservations) as missing_value, (totalObservations - propertyObservations) / toFloat(totalObservations) as pct_missing_valueORDER BY pct_missing_value DESC LIMIT 10 Results It looks like we don’t have many missing values. However, we will disregard features with more than four missing values from our further analysis for the sake of simplicity. High correlation filter is a simple data dimensionality reduction technique. Features with high correlation are likely to carry similar information and are more linearly dependant. Using multiple features with related information can bring down the performance of various models and can be avoided by dropping one of the two correlating features. // Only look at properties of nodes labeled "Country"CALL apoc.meta.nodeTypeProperties({labels:['Country']})YIELD propertyName, propertyObservations, totalObservationsWITH propertyName, (totalObservations - propertyObservations) as missing_value// filter our features with more than 5 missing valuesWHERE missing_value < 5 AND propertyName <> 'name'WITH collect(propertyName) as featuresMATCH (c:Country)UNWIND features as featureUNWIND features as compare_featureWITH feature, compare_feature, collect(coalesce(c[feature],0)) as vector_1, collect(coalesce(c[compare_feature],0)) as vector_2// avoid comparing with a feature with itselfWHERE feature < compare_featureRETURN feature, compare_feature, gds.alpha.similarity.pearson(vector_1, vector_2) AS correlationORDER BY correlation DESC LIMIT 10 Results: Interesting to see that birth rate and infant mortality are very correlated. The death rate is also quite correlated with infant mortality, so we will drop the birth and death rate but keep the infant mortality. The number of phones and net migration seems to be correlated with the GDP. We will drop them both as well and keep the GDP. We will also cut the population and retain both the area and population density, which carry similar information. At this point, we are left with eight features. We will examine their distributions with the apoc.agg.statistics function. It calculates numeric statistics such as minimum, maximum, and percentile ranks for a collection of values. // define excluded featuresWITH ['name', 'Deathrate', 'Birthrate', 'Phones (per 1000)', 'Net migration', 'Population'] as excluded_featuresCALL apoc.meta.nodeTypeProperties({labels:['Country']})YIELD propertyName, propertyObservations, totalObservationsWITH propertyName, (totalObservations - propertyObservations) as missing_valueWHERE missing_value < 5 AND NOT propertyName in excluded_features// Reduce to a single rowWITH collect(propertyName) as potential_featuresMATCH (c:Country)UNWIND potential_features as potential_featureWITH potential_feature, apoc.agg.statistics(c[potential_feature], [0.5,0.75,0.9,0.95,0.99]) as statsRETURN potential_feature, apoc.math.round(stats.min,2) as min, apoc.math.round(stats.max,2) as max, apoc.math.round(stats.mean,2) as mean, apoc.math.round(stats.stdev,2) as stdev, apoc.math.round(stats.`0.5`,2) as p50, apoc.math.round(stats.`0.75`,2) as p75, apoc.math.round(stats.`0.95`,2) as p95, apoc.math.round(stats.`0.99`,2) as p99 Results The Federated state of Micronesia has the ratio of coast to area at 870, which is pretty impressive. On the other hand, there are a total of 44 countries in the world with zero coastlines. Another fun fact is that Greenland has a population density rounded to 0 per square mile with its 56361 inhabitants and 2166086 square miles. It might be a cool place to perform social distancing. We can observe that most of the features appear to be descriptive, except for the Other (%), which is mostly between 80 and 100. Due to the low variance, we will ignore it in our further analysis. We are left with seven features that we are going to use to infer a similarity network between countries. One thing we need to do before that is to populate the missing values. We will use a simple method and fill in the missing values of the features with the average value of the region the country is part of. UNWIND ["Arable (%)", "Crops (%)", "Infant mortality (per 1000 births)", "GDP ($ per capita)"] as featureMATCH (c:Country)WHERE c[feature] IS nullMATCH (c)-[:PART_OF]->(r:Region)<-[:PART_OF]-(other:Country)WHERE other[feature] IS NOT nullWITH c,feature,avg(other[feature]) as avg_valueCALL apoc.create.setProperty(c, feature, avg_value) YIELD nodeRETURN distinct 'missing values populated' Last but not least, we have to normalize our features to prevent any single feature dominating over others due to a larger scale. We will use the simple MinMax method of normalization to rescale features between 0 and 1. UNWIND ["Arable (%)", "Crops (%)", "Infant mortality (per 1000 births)", "GDP ($ per capita)", "Coastline (coast/area ratio)", "Pop. Density (per sq. mi.)", "Area (sq. mi.)"] as featureMATCH (c:Country)// Calculate the min and the max value for each featureWITH max(c[feature]) as max, min(c[feature]) as min, featureMATCH (c1:Country)WITH c1, // define property name to store back results "n_" + feature AS newKey, // normalize values (toFloat(c1[feature]) - min) / (max - min) as normalized_value// store results to propertiesCALL apoc.create.setProperty(c1, newKey, normalized_value) YIELD nodeRETURN distinct 'normalization done' We have finished the data preprocessing and can focus on the data analysis part. The first step of the analysis is to infer a similarity network with the help of the cosine similarity algorithm. We build a vector for each country based on the selected features and compare the cosine similarity between each pair of countries. If the similarity is above the predefined threshold, we store back the results in the form of a relationship between the pair of similar nodes. Defining an optimal threshold is a mix of art and science, and you’ll get better with practice. Ideally, you want to infer a sparse graph as community detection algorithms do not perform well on complete or dense graphs. In this example, we will use the similarityCutoff value of 0.8 (range between -1 and 1). Alongside the similarity threshold, we will also use the topK parameter to store only the top 10 similar neighbors. We do this to ensure a sparser graph. MATCH (c:Country)// build the vector from featuresWITH id(c) as id, [c["n_Arable (%)"], c["n_Crops (%)"], c["n_Infant mortality (per 1000 births)"], c["n_GDP ($ per capita)"], c["n_Coastline (coast/area ratio)"], c["n_Pop. Density (per sq. mi.)"], c["n_Area (sq. mi.)"]] as weightsWITH {item:id, weights: weights} as countryDataWITH collect(countryData) as dataCALL gds.alpha.similarity.cosine.write({ nodeProjection: '*', relationshipProjection: '*', similarityCutoff:0.8, topK:10, data: data})YIELD nodes, similarityPairsRETURN nodes, similarityPairs With Neo4j’s Graph Data Science library, we can run more than 30 different graph algorithms directly in Neo4j. Algorithms are exposed as cypher procedures, similar to the APOC procedures we’ve seen above. GDS uses a projection of the stored graph, that is entirely in-memory to achieve faster execution times. We can project a view of the stored graph utilizing the gdn.graph.create procedure. For more details on the GDS graph projection, check out my previous blog post. In this example, we will project nodes that have a label Country and relationships with a type SIMILAR. CALL gds.graph.create('similarity_network','Country','SIMILAR'); More often than not, we start the graph analysis with the weakly connected components algorithm. It is a community detection algorithm used to find disconnected networks or islands within our graph. As we are only interested in the count of disconnected components, we can run the stats variant of the algorithm. CALL gds.wcc.stats('similarity_network')YIELD componentCount, componentDistributionRETURN componentCount, componentDistribution.min as min, componentDistribution.max as max, componentDistribution.mean as mean, componentDistribution.p50 as p50, componentDistribution.p75 as p75, componentDistribution.p90 as p90 Results The algorithm found only a single component within our graph. This is a favorable outcome as disconnected islands can skew the results of various other graph algorithms. Another community detection algorithm is the Louvain algorithm. In basic terms, densely connected nodes are more likely to form a community. It relies on the modularity optimization to extract communities. The modularity optimization is performed in two steps. The first step involves optimizing the modularity locally. In the second step, it aggregates nodes belonging to the same community into a single node and builds a new network from those aggregated nodes. These two steps are repeated iteratively until a maximum of modularity is attained. A subtle side effect of these iterations is that we can take a look at the community structure at the end of each iteration, hence the Louvain algorithm is regarded as a hierarchical community detection algorithm. To include hierarchical community results, we must set the includeIntermediateCommunities parameter value to true. CALL gds.louvain.write('similarity_network', {maxIterations:20, includeIntermediateCommunities:true, writeProperty:'louvain'})YIELD ranLevels, communityCount,modularity,modularities Results We can observe by the ranLevels value that the Louvain algorithm found two levels of communities in our network. On the final level, it found eight groups. We can now examine the extracted communities of the last level and compare their feature averages. MATCH (c:Country)RETURN c.louvain[-1] as community, count(*) as community_size, avg(c['Arable (%)']) as pct_arable, avg(c['Crops (%)']) as pct_crops, avg(c['Infant mortality (per 1000 births)']) as infant_mortality, avg(c['GDP ($ per capita)']) as gdp, avg(c['Coastline (coast/area ratio)']) as coastline, avg(c['Pop. Density (per sq. mi.)']) as population_density, avg(c['Area (sq. mi.)']) as area_size, collect(c['name'])[..3] as example_membersORDER BY gdp DESC Results Louvain algorithm found eight distinct communities within the similarity network. The biggest group has 51 countries as members and has the largest average GDP at almost 22 thousand dollars. They are second in infant mortality and the coastline ratio but lead in population density by a large margin. There are two communities with an average GDP of around 20 thousand dollars, and then we can observe a steep drop to 7000 dollars in third place. With the decline in GDP, we can also find the rise of infant mortality almost linearly. Another fascinating insight is that most of the more impoverished communities have little to no coastline. We can assess the top representatives of the final level communities with the PageRank algorithm. If we assume that each SIMILAR relationship is a vote of similarity between countries, the PageRank algorithm will assign the highest score to the most similar countries within the community. We will execute the PageRank algorithm for each community separately and consider only nodes and relationships within the given community. This can be easily achieved with cypher projection without any additional transformations. WITH 'MATCH (c:Country) WHERE c.louvain[-1] = $community RETURN id(c) as id' as nodeQuery, 'MATCH (s:Country)-[:SIMILAR]->(t:Country) RETURN id(s) as source, id(t) as target' as relQueryMATCH (c:Country)WITH distinct c.louvain[-1] as community, nodeQuery, relQueryCALL gds.pageRank.stream({nodeQuery:nodeQuery, relationshipQuery:relQuery, parameters:{community:community}, validateRelationships:False})YIELD nodeId, scoreWITH community, nodeId,scoreORDER BY score DESCRETURN community, collect(gds.util.asNode(nodeId).name)[..5] as top_5_representatives Results Excellent visualization is worth more than a thousand words. Gephi is a great tool to create network visualizations. As we might expect by now, APOC offers a handy procedure apoc.gephi.add that seamlessly streams network data from Neo4j to Gephi. Find out more in the documentation or in my previous blog post. As we observed before, there are eight distinct communities in our network. The community with the highest average GDP is in the top right corner, and the countries with the highest to lowest average GDP follow in the clockwise direction. One intriguing triangle I found is right in the middle of the visualization formed by Russia, China, and Brazil. Also, if you look closely, you will see that Panama is part of the red community, but is positioned in the middle. That is because it has similar relationships to one or two countries from most of the communities, but is related to three countries from the red community, and hence belongs to it. We mentioned before that the Louvain algorithm can be used to find hierarchical communities with the includeIntermediateCommunities parameter and that in our example, it found two levels of communities. We will now examine the groups of countries on the first level. A rule of thumb is that communities on a lower level will be more granular and smaller. MATCH (c:Country)RETURN c.louvain[0] as community, count(*) as community_size, avg(c['Arable (%)']) as pct_arable, avg(c['Crops (%)']) as pct_crops, avg(c['Infant mortality (per 1000 births)']) as infant_mortality, avg(c['GDP ($ per capita)']) as gdp, avg(c['Coastline (coast/area ratio)']) as coastline, avg(c['Pop. Density (per sq. mi.)']) as population_density, avg(c['Area (sq. mi.)']) as area_size, collect(c['name'])[..3] as example_membersORDER BY gdp DESC Results As expected, there are almost twice as many communities on the first level compared to the second and final level. An exciting community formed in second place by the average GDP. It contains only five countries, which are quite tiny as their average area size is only 364 square miles. On the other hand, they have a very high population density of around 10000 people per square mile. Example members are Macau, Monaco, and Hong Kong. Another excellent tool for network visualization with a higher focus on graph exploration is Neo4j Bloom. It provides the ability to customize the graph perspective and search queries, which can be used by people without any cypher query language skill to explore and search for insights within the graph. If you are interested to learn more, you can check this blog post written by William Lyon. We will take a look at the countries of the final community with the highest GDP. It is a community of 51 countries, that has four distinct communities on the first hierarchical level. Before, we mentioned an exciting community of five tiny countries with an incredibly high population density. They are colored red in this visualization. The blue community has around 25% higher average GDP and almost half the infant mortality as the yellow one. On the other hand, the yellow community has on average more coastline than the blue one. Neo4j ecosystem is well suited to perform and visualize network analysis. Graph Data Science library is a practical addition to the ecosystem that allows us to run various graph algorithms and perform graph analysis without much hassle. You can try it out either on your computer or you can create a Neo4j Sandbox account and get started within minutes. As always, the code is available on GitHub.
[ { "code": null, "e": 556, "s": 171, "text": "While I was waiting for my sourdough to rise, I thought, the best way to spend my time is to perform a network analysis with the Neo4j Graph data science library. Well, maybe also try to draw an acrylic painting, but I won’t bore you with that. If this is the first time you have heard of the GDS library, I can recommend some of my previous blog posts that try to explain the basics:" }, { "code": null, "e": 578, "s": 556, "text": "GDS Native projection" }, { "code": null, "e": 600, "s": 578, "text": "GDS Cypher projection" }, { "code": null, "e": 626, "s": 600, "text": "GDS Multigraph projection" }, { "code": null, "e": 717, "s": 626, "text": "If you are ready, it’s time to put on our graph data science hat and get down to business." }, { "code": null, "e": 723, "s": 717, "text": "Neo4j" }, { "code": null, "e": 741, "s": 723, "text": "Neo4j APOC plugin" }, { "code": null, "e": 773, "s": 741, "text": "Neo4j Graph data science plugin" }, { "code": null, "e": 1210, "s": 773, "text": "We will be using the Countries of the world dataset made available on Kaggle by Fernando Lasso. Looking at the acknowledgements, the data originates from the CIA’s World Factbook. Unfortunately, the contributor did not provide the year the dataset was compiled. My guess is the year 2013, but I might be wrong. The dataset contains various metrics like area size, population, infant mortality, and more about 227 countries of the world." }, { "code": null, "e": 1346, "s": 1210, "text": "The graph schema consists of nodes labeled Country that have their features stored as properties. A Country is also a part of a Region." }, { "code": null, "e": 1864, "s": 1346, "text": "First, we need to download the dataset and copy it to the $Neo4j/import folder. For some reason, the numbers in the CSV file use a comma as a floating point instead of a dot (0,1 instead of 0.1). We need to preprocess the data to be able to cast the numbers to float in Neo4j. With the help of an APOC procedure apoc.cypher.run , we can preprocess and store the data in a single cypher query. apoc.cypher.run allows us to run independent subqueries within the main cypher query and is excellent for various use cases." }, { "code": null, "e": 2452, "s": 1864, "text": "LOAD CSV WITH HEADERS FROM \"file:///countries%20of%20the%20world.csv\" as row// cleanup the data and replace comma floating point with a dotCALL apoc.cypher.run( \"UNWIND keys($row) as key WITH row, key, toFloat(replace(row[key],',','.')) as clean_value // exclude string properties WHERE NOT key in ['Country','Region'] RETURN collect([key,clean_value]) as keys\", {row:row}) YIELD valueMERGE (c:Country{name:trim(row.Country)})SET c+= apoc.map.fromPairs(value.keys)MERGE (r:Region{name:trim(row.Region)})MERGE (c)-[:PART_OF]->(r)" }, { "code": null, "e": 2662, "s": 2452, "text": "Another useful APOC procedure is apoc.meta.nodeTypeProperties. With it, we can examine the node property schema of the graph. We will use it to identify how many missing values each feature of the country has." }, { "code": null, "e": 3056, "s": 2662, "text": "// Only look at properties of nodes labeled \"Country\"CALL apoc.meta.nodeTypeProperties({labels:['Country']})YIELD propertyName, propertyObservations, totalObservationsRETURN propertyName, (totalObservations - propertyObservations) as missing_value, (totalObservations - propertyObservations) / toFloat(totalObservations) as pct_missing_valueORDER BY pct_missing_value DESC LIMIT 10" }, { "code": null, "e": 3064, "s": 3056, "text": "Results" }, { "code": null, "e": 3238, "s": 3064, "text": "It looks like we don’t have many missing values. However, we will disregard features with more than four missing values from our further analysis for the sake of simplicity." }, { "code": null, "e": 3585, "s": 3238, "text": "High correlation filter is a simple data dimensionality reduction technique. Features with high correlation are likely to carry similar information and are more linearly dependant. Using multiple features with related information can bring down the performance of various models and can be avoided by dropping one of the two correlating features." }, { "code": null, "e": 4413, "s": 3585, "text": "// Only look at properties of nodes labeled \"Country\"CALL apoc.meta.nodeTypeProperties({labels:['Country']})YIELD propertyName, propertyObservations, totalObservationsWITH propertyName, (totalObservations - propertyObservations) as missing_value// filter our features with more than 5 missing valuesWHERE missing_value < 5 AND propertyName <> 'name'WITH collect(propertyName) as featuresMATCH (c:Country)UNWIND features as featureUNWIND features as compare_featureWITH feature, compare_feature, collect(coalesce(c[feature],0)) as vector_1, collect(coalesce(c[compare_feature],0)) as vector_2// avoid comparing with a feature with itselfWHERE feature < compare_featureRETURN feature, compare_feature, gds.alpha.similarity.pearson(vector_1, vector_2) AS correlationORDER BY correlation DESC LIMIT 10" }, { "code": null, "e": 4422, "s": 4413, "text": "Results:" }, { "code": null, "e": 4873, "s": 4422, "text": "Interesting to see that birth rate and infant mortality are very correlated. The death rate is also quite correlated with infant mortality, so we will drop the birth and death rate but keep the infant mortality. The number of phones and net migration seems to be correlated with the GDP. We will drop them both as well and keep the GDP. We will also cut the population and retain both the area and population density, which carry similar information." }, { "code": null, "e": 5104, "s": 4873, "text": "At this point, we are left with eight features. We will examine their distributions with the apoc.agg.statistics function. It calculates numeric statistics such as minimum, maximum, and percentile ranks for a collection of values." }, { "code": null, "e": 6194, "s": 5104, "text": "// define excluded featuresWITH ['name', 'Deathrate', 'Birthrate', 'Phones (per 1000)', 'Net migration', 'Population'] as excluded_featuresCALL apoc.meta.nodeTypeProperties({labels:['Country']})YIELD propertyName, propertyObservations, totalObservationsWITH propertyName, (totalObservations - propertyObservations) as missing_valueWHERE missing_value < 5 AND NOT propertyName in excluded_features// Reduce to a single rowWITH collect(propertyName) as potential_featuresMATCH (c:Country)UNWIND potential_features as potential_featureWITH potential_feature, apoc.agg.statistics(c[potential_feature], [0.5,0.75,0.9,0.95,0.99]) as statsRETURN potential_feature, apoc.math.round(stats.min,2) as min, apoc.math.round(stats.max,2) as max, apoc.math.round(stats.mean,2) as mean, apoc.math.round(stats.stdev,2) as stdev, apoc.math.round(stats.`0.5`,2) as p50, apoc.math.round(stats.`0.75`,2) as p75, apoc.math.round(stats.`0.95`,2) as p95, apoc.math.round(stats.`0.99`,2) as p99" }, { "code": null, "e": 6202, "s": 6194, "text": "Results" }, { "code": null, "e": 6588, "s": 6202, "text": "The Federated state of Micronesia has the ratio of coast to area at 870, which is pretty impressive. On the other hand, there are a total of 44 countries in the world with zero coastlines. Another fun fact is that Greenland has a population density rounded to 0 per square mile with its 56361 inhabitants and 2166086 square miles. It might be a cool place to perform social distancing." }, { "code": null, "e": 6785, "s": 6588, "text": "We can observe that most of the features appear to be descriptive, except for the Other (%), which is mostly between 80 and 100. Due to the low variance, we will ignore it in our further analysis." }, { "code": null, "e": 7098, "s": 6785, "text": "We are left with seven features that we are going to use to infer a similarity network between countries. One thing we need to do before that is to populate the missing values. We will use a simple method and fill in the missing values of the features with the average value of the region the country is part of." }, { "code": null, "e": 7509, "s": 7098, "text": "UNWIND [\"Arable (%)\", \"Crops (%)\", \"Infant mortality (per 1000 births)\", \"GDP ($ per capita)\"] as featureMATCH (c:Country)WHERE c[feature] IS nullMATCH (c)-[:PART_OF]->(r:Region)<-[:PART_OF]-(other:Country)WHERE other[feature] IS NOT nullWITH c,feature,avg(other[feature]) as avg_valueCALL apoc.create.setProperty(c, feature, avg_value) YIELD nodeRETURN distinct 'missing values populated'" }, { "code": null, "e": 7730, "s": 7509, "text": "Last but not least, we have to normalize our features to prevent any single feature dominating over others due to a larger scale. We will use the simple MinMax method of normalization to rescale features between 0 and 1." }, { "code": null, "e": 8427, "s": 7730, "text": "UNWIND [\"Arable (%)\", \"Crops (%)\", \"Infant mortality (per 1000 births)\", \"GDP ($ per capita)\", \"Coastline (coast/area ratio)\", \"Pop. Density (per sq. mi.)\", \"Area (sq. mi.)\"] as featureMATCH (c:Country)// Calculate the min and the max value for each featureWITH max(c[feature]) as max, min(c[feature]) as min, featureMATCH (c1:Country)WITH c1, // define property name to store back results \"n_\" + feature AS newKey, // normalize values (toFloat(c1[feature]) - min) / (max - min) as normalized_value// store results to propertiesCALL apoc.create.setProperty(c1, newKey, normalized_value) YIELD nodeRETURN distinct 'normalization done'" }, { "code": null, "e": 9362, "s": 8427, "text": "We have finished the data preprocessing and can focus on the data analysis part. The first step of the analysis is to infer a similarity network with the help of the cosine similarity algorithm. We build a vector for each country based on the selected features and compare the cosine similarity between each pair of countries. If the similarity is above the predefined threshold, we store back the results in the form of a relationship between the pair of similar nodes. Defining an optimal threshold is a mix of art and science, and you’ll get better with practice. Ideally, you want to infer a sparse graph as community detection algorithms do not perform well on complete or dense graphs. In this example, we will use the similarityCutoff value of 0.8 (range between -1 and 1). Alongside the similarity threshold, we will also use the topK parameter to store only the top 10 similar neighbors. We do this to ensure a sparser graph." }, { "code": null, "e": 10038, "s": 9362, "text": "MATCH (c:Country)// build the vector from featuresWITH id(c) as id, [c[\"n_Arable (%)\"], c[\"n_Crops (%)\"], c[\"n_Infant mortality (per 1000 births)\"], c[\"n_GDP ($ per capita)\"], c[\"n_Coastline (coast/area ratio)\"], c[\"n_Pop. Density (per sq. mi.)\"], c[\"n_Area (sq. mi.)\"]] as weightsWITH {item:id, weights: weights} as countryDataWITH collect(countryData) as dataCALL gds.alpha.similarity.cosine.write({ nodeProjection: '*', relationshipProjection: '*', similarityCutoff:0.8, topK:10, data: data})YIELD nodes, similarityPairsRETURN nodes, similarityPairs" }, { "code": null, "e": 10243, "s": 10038, "text": "With Neo4j’s Graph Data Science library, we can run more than 30 different graph algorithms directly in Neo4j. Algorithms are exposed as cypher procedures, similar to the APOC procedures we’ve seen above." }, { "code": null, "e": 10615, "s": 10243, "text": "GDS uses a projection of the stored graph, that is entirely in-memory to achieve faster execution times. We can project a view of the stored graph utilizing the gdn.graph.create procedure. For more details on the GDS graph projection, check out my previous blog post. In this example, we will project nodes that have a label Country and relationships with a type SIMILAR." }, { "code": null, "e": 10680, "s": 10615, "text": "CALL gds.graph.create('similarity_network','Country','SIMILAR');" }, { "code": null, "e": 10993, "s": 10680, "text": "More often than not, we start the graph analysis with the weakly connected components algorithm. It is a community detection algorithm used to find disconnected networks or islands within our graph. As we are only interested in the count of disconnected components, we can run the stats variant of the algorithm." }, { "code": null, "e": 11341, "s": 10993, "text": "CALL gds.wcc.stats('similarity_network')YIELD componentCount, componentDistributionRETURN componentCount, componentDistribution.min as min, componentDistribution.max as max, componentDistribution.mean as mean, componentDistribution.p50 as p50, componentDistribution.p75 as p75, componentDistribution.p90 as p90" }, { "code": null, "e": 11349, "s": 11341, "text": "Results" }, { "code": null, "e": 11519, "s": 11349, "text": "The algorithm found only a single component within our graph. This is a favorable outcome as disconnected islands can skew the results of various other graph algorithms." }, { "code": null, "e": 12397, "s": 11519, "text": "Another community detection algorithm is the Louvain algorithm. In basic terms, densely connected nodes are more likely to form a community. It relies on the modularity optimization to extract communities. The modularity optimization is performed in two steps. The first step involves optimizing the modularity locally. In the second step, it aggregates nodes belonging to the same community into a single node and builds a new network from those aggregated nodes. These two steps are repeated iteratively until a maximum of modularity is attained. A subtle side effect of these iterations is that we can take a look at the community structure at the end of each iteration, hence the Louvain algorithm is regarded as a hierarchical community detection algorithm. To include hierarchical community results, we must set the includeIntermediateCommunities parameter value to true." }, { "code": null, "e": 12592, "s": 12397, "text": "CALL gds.louvain.write('similarity_network', {maxIterations:20, includeIntermediateCommunities:true, writeProperty:'louvain'})YIELD ranLevels, communityCount,modularity,modularities" }, { "code": null, "e": 12600, "s": 12592, "text": "Results" }, { "code": null, "e": 12855, "s": 12600, "text": "We can observe by the ranLevels value that the Louvain algorithm found two levels of communities in our network. On the final level, it found eight groups. We can now examine the extracted communities of the last level and compare their feature averages." }, { "code": null, "e": 13375, "s": 12855, "text": "MATCH (c:Country)RETURN c.louvain[-1] as community, count(*) as community_size, avg(c['Arable (%)']) as pct_arable, avg(c['Crops (%)']) as pct_crops, avg(c['Infant mortality (per 1000 births)']) as infant_mortality, avg(c['GDP ($ per capita)']) as gdp, avg(c['Coastline (coast/area ratio)']) as coastline, avg(c['Pop. Density (per sq. mi.)']) as population_density, avg(c['Area (sq. mi.)']) as area_size, collect(c['name'])[..3] as example_membersORDER BY gdp DESC" }, { "code": null, "e": 13383, "s": 13375, "text": "Results" }, { "code": null, "e": 14025, "s": 13383, "text": "Louvain algorithm found eight distinct communities within the similarity network. The biggest group has 51 countries as members and has the largest average GDP at almost 22 thousand dollars. They are second in infant mortality and the coastline ratio but lead in population density by a large margin. There are two communities with an average GDP of around 20 thousand dollars, and then we can observe a steep drop to 7000 dollars in third place. With the decline in GDP, we can also find the rise of infant mortality almost linearly. Another fascinating insight is that most of the more impoverished communities have little to no coastline." }, { "code": null, "e": 14545, "s": 14025, "text": "We can assess the top representatives of the final level communities with the PageRank algorithm. If we assume that each SIMILAR relationship is a vote of similarity between countries, the PageRank algorithm will assign the highest score to the most similar countries within the community. We will execute the PageRank algorithm for each community separately and consider only nodes and relationships within the given community. This can be easily achieved with cypher projection without any additional transformations." }, { "code": null, "e": 15198, "s": 14545, "text": "WITH 'MATCH (c:Country) WHERE c.louvain[-1] = $community RETURN id(c) as id' as nodeQuery, 'MATCH (s:Country)-[:SIMILAR]->(t:Country) RETURN id(s) as source, id(t) as target' as relQueryMATCH (c:Country)WITH distinct c.louvain[-1] as community, nodeQuery, relQueryCALL gds.pageRank.stream({nodeQuery:nodeQuery, relationshipQuery:relQuery, parameters:{community:community}, validateRelationships:False})YIELD nodeId, scoreWITH community, nodeId,scoreORDER BY score DESCRETURN community, collect(gds.util.asNode(nodeId).name)[..5] as top_5_representatives" }, { "code": null, "e": 15206, "s": 15198, "text": "Results" }, { "code": null, "e": 15517, "s": 15206, "text": "Excellent visualization is worth more than a thousand words. Gephi is a great tool to create network visualizations. As we might expect by now, APOC offers a handy procedure apoc.gephi.add that seamlessly streams network data from Neo4j to Gephi. Find out more in the documentation or in my previous blog post." }, { "code": null, "e": 16166, "s": 15517, "text": "As we observed before, there are eight distinct communities in our network. The community with the highest average GDP is in the top right corner, and the countries with the highest to lowest average GDP follow in the clockwise direction. One intriguing triangle I found is right in the middle of the visualization formed by Russia, China, and Brazil. Also, if you look closely, you will see that Panama is part of the red community, but is positioned in the middle. That is because it has similar relationships to one or two countries from most of the communities, but is related to three countries from the red community, and hence belongs to it." }, { "code": null, "e": 16521, "s": 16166, "text": "We mentioned before that the Louvain algorithm can be used to find hierarchical communities with the includeIntermediateCommunities parameter and that in our example, it found two levels of communities. We will now examine the groups of countries on the first level. A rule of thumb is that communities on a lower level will be more granular and smaller." }, { "code": null, "e": 17040, "s": 16521, "text": "MATCH (c:Country)RETURN c.louvain[0] as community, count(*) as community_size, avg(c['Arable (%)']) as pct_arable, avg(c['Crops (%)']) as pct_crops, avg(c['Infant mortality (per 1000 births)']) as infant_mortality, avg(c['GDP ($ per capita)']) as gdp, avg(c['Coastline (coast/area ratio)']) as coastline, avg(c['Pop. Density (per sq. mi.)']) as population_density, avg(c['Area (sq. mi.)']) as area_size, collect(c['name'])[..3] as example_membersORDER BY gdp DESC" }, { "code": null, "e": 17048, "s": 17040, "text": "Results" }, { "code": null, "e": 17485, "s": 17048, "text": "As expected, there are almost twice as many communities on the first level compared to the second and final level. An exciting community formed in second place by the average GDP. It contains only five countries, which are quite tiny as their average area size is only 364 square miles. On the other hand, they have a very high population density of around 10000 people per square mile. Example members are Macau, Monaco, and Hong Kong." }, { "code": null, "e": 17882, "s": 17485, "text": "Another excellent tool for network visualization with a higher focus on graph exploration is Neo4j Bloom. It provides the ability to customize the graph perspective and search queries, which can be used by people without any cypher query language skill to explore and search for insights within the graph. If you are interested to learn more, you can check this blog post written by William Lyon." }, { "code": null, "e": 18067, "s": 17882, "text": "We will take a look at the countries of the final community with the highest GDP. It is a community of 51 countries, that has four distinct communities on the first hierarchical level." }, { "code": null, "e": 18419, "s": 18067, "text": "Before, we mentioned an exciting community of five tiny countries with an incredibly high population density. They are colored red in this visualization. The blue community has around 25% higher average GDP and almost half the infant mortality as the yellow one. On the other hand, the yellow community has on average more coastline than the blue one." }, { "code": null, "e": 18773, "s": 18419, "text": "Neo4j ecosystem is well suited to perform and visualize network analysis. Graph Data Science library is a practical addition to the ecosystem that allows us to run various graph algorithms and perform graph analysis without much hassle. You can try it out either on your computer or you can create a Neo4j Sandbox account and get started within minutes." } ]
@Formula Annotation in Hibernate Example - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In hibernate, we have many annotations. Each annotation has its importance to perform an operation. Likewise, @Formula is a hibernate annotation to calculate the dynamic value and assign that value to the property. @Formula annotation takes the expression as a parameter, and at fetch time it will evaluate the expression and assigns an evaluated value to the property. This @Formula parameter can be as complex as we want. That means, it may be a simple expression or it may be a complex query, this can be applied on top of the property. In this tutorial, we are going to calculate the Employee total salary, using the @Formula annotation in hibernate. To make the example as simple, we figure the total employee salary like below. Employee total salary = basic + conveyance + hra; Let’s implement this calculation by using @Formula annotation in hibernate. Project Structure: Required Dependencies : <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.springframework.samples</groupId> <artifactId>Hibernate-Formula-Example</artifactId> <version>0.0.1-SNAPSHOT</version> <properties> <!-- Generic properties --> <java.version>1.6</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <!-- Spring --> <spring-framework.version>3.2.3.RELEASE</spring-framework.version> <!-- Hibernate / JPA --> <hibernate.version>4.2.1.Final</hibernate.version> <!-- Logging --> <logback.version>1.0.13</logback.version> <slf4j.version>1.7.5</slf4j.version> <!-- Test --> <junit.version>4.11</junit.version> </properties> <dependencies> <!-- Hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${hibernate.version}</version> </dependency> <!-- MySQL Driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.0.5</version> </dependency> </dependencies> </project> Salaries.java package com.onlinetutorialspoint.bean; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.Formula; @Entity @Table(name = "salaries") public class Salaries { @Id @Column(name = "empid") private int empId; @Column(name = "empname") private String empName; @Column(name = "basic") private int basic; @Column(name = "conveyance") private int conveyance; @Column(name = "hra") private int hra; @Formula(" basic + conveyance + hra ") private float total; public int getEmpId() { return empId; } public void setEmpId(int empId) { this.empId = empId; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } public int getBasic() { return basic; } public void setBasic(int basic) { this.basic = basic; } public int getConveyance() { return conveyance; } public void setConveyance(int conveyance) { this.conveyance = conveyance; } public int getHra() { return hra; } public void setHra(int hra) { this.hra = hra; } public float getTotal() { return total; } public void setTotal(float total) { this.total = total; } } import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.AnnotationConfiguration; import com.onlinetutorialspoint.bean.Salaries; public class Main { private static final SessionFactory concreteSessionFactory; static { try { concreteSessionFactory = new AnnotationConfiguration() .configure().buildSessionFactory(); } catch (Throwable ex) { throw new ExceptionInInitializerError(ex); } } public static Session getSession() throws HibernateException { return concreteSessionFactory.openSession(); } public static void main(String[] args) { Session session=getSession(); Transaction tx = session.beginTransaction(); Salaries salaries = new Salaries(); salaries.setEmpName("Rahul"); salaries.setBasic(10000); salaries.setConveyance(3000); salaries.setHra(7000); session.save(salaries); tx.commit(); Salaries d= (Salaries)session.get(Salaries.class,new Integer(1)); System.out.println("Employee Total Salary :"+d.getTotal()); } } On the above example, we use session.get(Salaries.class, new Integer(1)) to get the Salaries details from hibernate cache or database. Hibernate: insert into salaries (basic, conveyance, empname, hra, empid) values (?, ?, ?, ?, ?) Hibernate: select salaries0_.empid as empid1_0_0_, salaries0_.basic as basic2_0_0_, salaries0_.conveyance as conveyan3_0_0_, salaries0_.empname as empname4_0_0_, salaries0_.hra as hra5_0_0_, salaries0_.basic + salaries0_.conveyance + salaries0_.hra as formula0_0_ from salaries salaries0_ where salaries0_.empid=? Employee Total Salary :20000.0 On the above example, we use @Formula annotation for simple expression. If we want to make this some more extent, we do.. Like below. @Formula("(select min(s.hra) from salaries s) ") private float total; If you change the code like above, you can get the minimum hra in salaries table. Happy Learning 🙂 Hibernate-Formula-Annotation-Example File size: 15 KB Downloads: 930 Calling Stored Procedures in Hibernate Hibernate Filters Example Annotation AngularJs Search Filter Example Basic Hibernate Example with XML Configuration Hibernate Composite Key Mapping Example Hibernate One to One Mapping using primary key (XML) Hibernate 4 Example with Annotations Mysql Hibernate Criteria API with Example Hibernate Left Join Example Hibernate One To Many Using Annotations Hibernate Table per Class strategy Annotations Example @Qualifier annotation example in Spring What is Hibernate Hibernate cache first level example hibernate update query example Calling Stored Procedures in Hibernate Hibernate Filters Example Annotation AngularJs Search Filter Example Basic Hibernate Example with XML Configuration Hibernate Composite Key Mapping Example Hibernate One to One Mapping using primary key (XML) Hibernate 4 Example with Annotations Mysql Hibernate Criteria API with Example Hibernate Left Join Example Hibernate One To Many Using Annotations Hibernate Table per Class strategy Annotations Example @Qualifier annotation example in Spring What is Hibernate Hibernate cache first level example hibernate update query example Sumit July 17, 2020 at 1:45 pm - Reply I am seeing the below error. My POJO looks like this: private Long longOldValue; private String oldValue; private Long longNewValue; private String newValue; private long created; private String reasonChange; @Formula(“longNewValue-longOldValue”) private Long difference; java.sql.SQLSyntaxErrorException: Unknown column ‘applicatio1_.longNewValue’ in ‘field list’ at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120) ~[mysql-connector-java-8.0.19.jar:8.0.19] at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.19.jar:8.0.19] at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.19.jar:8.0.19] at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953) ~[mysql-connector-java-8.0.19.jar:8.0.19] at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1003) ~[mysql-connector-java-8.0.19.jar:8.0.19] Sumit July 17, 2020 at 1:45 pm - Reply I am seeing the below error. My POJO looks like this: private Long longOldValue; private String oldValue; private Long longNewValue; private String newValue; private long created; private String reasonChange; @Formula(“longNewValue-longOldValue”) private Long difference; java.sql.SQLSyntaxErrorException: Unknown column ‘applicatio1_.longNewValue’ in ‘field list’ at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120) ~[mysql-connector-java-8.0.19.jar:8.0.19] at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.19.jar:8.0.19] at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.19.jar:8.0.19] at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953) ~[mysql-connector-java-8.0.19.jar:8.0.19] at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1003) ~[mysql-connector-java-8.0.19.jar:8.0.19] I am seeing the below error. My POJO looks like this: private Long longOldValue; private String oldValue; private Long longNewValue; private String newValue; private long created; private String reasonChange; @Formula(“longNewValue-longOldValue”) private Long difference; java.sql.SQLSyntaxErrorException: Unknown column ‘applicatio1_.longNewValue’ in ‘field list’ at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120) ~[mysql-connector-java-8.0.19.jar:8.0.19] at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.19.jar:8.0.19] at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.19.jar:8.0.19] at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953) ~[mysql-connector-java-8.0.19.jar:8.0.19] at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1003) ~[mysql-connector-java-8.0.19.jar:8.0.19] Δ Hibernate – Introduction Hibernate – Advantages Hibernate – Download and Setup Hibernate – Sql Dialect list Hibernate – Helloworld – XML Hibernate – Install Tools in Eclipse Hibernate – Object States Hibernate – Helloworld – Annotations Hibernate – One to One Mapping – XML Hibernate – One to One Mapping foreign key – XML Hibernate – One To Many -XML Hibernate – One To Many – Annotations Hibernate – Many to Many Mapping – XML Hibernate – Many to One – XML Hibernate – Composite Key Mapping Hibernate – Named Query Hibernate – Native SQL Query Hibernate – load() vs get() Hibernate Criteria API with Example Hibernate – Restrictions Hibernate – Projection Hibernate – Query Language (HQL) Hibernate – Groupby Criteria HQL Hibernate – Orderby Criteria Hibernate – HQLSelect Operation Hibernate – HQL Update, Delete Hibernate – Update Query Hibernate – Update vs Merge Hibernate – Right Join Hibernate – Left Join Hibernate – Pagination Hibernate – Generator Classes Hibernate – Custom Generator Hibernate – Inheritance Mappings Hibernate – Table per Class Hibernate – Table per Sub Class Hibernate – Table per Concrete Class Hibernate – Table per Class Annotations Hibernate – Stored Procedures Hibernate – @Formula Annotation Hibernate – Singleton SessionFactory Hibernate – Interceptor hbm2ddl.auto Example in Hibernate XML Config Hibernate – First Level Cache
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 613, "s": 398, "text": "In hibernate, we have many annotations. Each annotation has its importance to perform an operation. Likewise, @Formula is a hibernate annotation to calculate the dynamic value and assign that value to the property." }, { "code": null, "e": 768, "s": 613, "text": "@Formula annotation takes the expression as a parameter, and at fetch time it will evaluate the expression and assigns an evaluated value to the property." }, { "code": null, "e": 938, "s": 768, "text": "This @Formula parameter can be as complex as we want. That means, it may be a simple expression or it may be a complex query, this can be applied on top of the property." }, { "code": null, "e": 1054, "s": 938, "text": "In this tutorial, we are going to calculate the Employee total salary, using the @Formula annotation in hibernate. " }, { "code": null, "e": 1133, "s": 1054, "text": "To make the example as simple, we figure the total employee salary like below." }, { "code": null, "e": 1183, "s": 1133, "text": "Employee total salary = basic + conveyance + hra;" }, { "code": null, "e": 1279, "s": 1183, "text": "Let’s implement this calculation by using @Formula annotation in hibernate. Project Structure: " }, { "code": null, "e": 1303, "s": 1279, "text": "Required Dependencies :" }, { "code": null, "e": 2732, "s": 1303, "text": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>org.springframework.samples</groupId>\n <artifactId>Hibernate-Formula-Example</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n \n <properties>\n\n <!-- Generic properties -->\n <java.version>1.6</java.version>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n\n <!-- Spring -->\n <spring-framework.version>3.2.3.RELEASE</spring-framework.version>\n\n <!-- Hibernate / JPA -->\n <hibernate.version>4.2.1.Final</hibernate.version>\n\n <!-- Logging -->\n <logback.version>1.0.13</logback.version>\n <slf4j.version>1.7.5</slf4j.version>\n\n <!-- Test -->\n <junit.version>4.11</junit.version>\n\n </properties>\n \n <dependencies>\n <!-- Hibernate -->\n <dependency>\n <groupId>org.hibernate</groupId>\n <artifactId>hibernate-entitymanager</artifactId>\n <version>${hibernate.version}</version>\n </dependency>\n <!-- MySQL Driver -->\n <dependency>\n <groupId>mysql</groupId>\n <artifactId>mysql-connector-java</artifactId>\n <version>5.0.5</version>\n </dependency>\n </dependencies>\t\n</project>" }, { "code": null, "e": 2746, "s": 2732, "text": "Salaries.java" }, { "code": null, "e": 4184, "s": 2746, "text": "package com.onlinetutorialspoint.bean;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport org.hibernate.annotations.Formula;\n\n@Entity\n@Table(name = \"salaries\")\npublic class Salaries {\n @Id\n @Column(name = \"empid\")\n private int empId;\n @Column(name = \"empname\")\n private String empName;\n @Column(name = \"basic\")\n private int basic;\n @Column(name = \"conveyance\")\n private int conveyance;\n @Column(name = \"hra\")\n private int hra;\n\n @Formula(\" basic + conveyance + hra \")\n private float total;\n\n public int getEmpId() {\n return empId;\n }\n\n public void setEmpId(int empId) {\n this.empId = empId;\n }\n\n public String getEmpName() {\n return empName;\n }\n\n public void setEmpName(String empName) {\n this.empName = empName;\n }\n\n public int getBasic() {\n return basic;\n }\n\n public void setBasic(int basic) {\n this.basic = basic;\n }\n\n public int getConveyance() {\n return conveyance;\n }\n\n public void setConveyance(int conveyance) {\n this.conveyance = conveyance;\n }\n\n public int getHra() {\n return hra;\n }\n\n public void setHra(int hra) {\n this.hra = hra;\n }\n\n public float getTotal() {\n return total;\n }\n\n public void setTotal(float total) {\n this.total = total;\n }\n\n}\n" }, { "code": null, "e": 5452, "s": 4184, "text": "import org.hibernate.HibernateException;\nimport org.hibernate.Session;\nimport org.hibernate.SessionFactory;\nimport org.hibernate.Transaction;\nimport org.hibernate.cfg.AnnotationConfiguration;\n\nimport com.onlinetutorialspoint.bean.Salaries;\n\npublic class Main {\n private static final SessionFactory concreteSessionFactory;\n static {\n try {\n concreteSessionFactory = new AnnotationConfiguration()\n .configure().buildSessionFactory();\n } catch (Throwable ex) {\n throw new ExceptionInInitializerError(ex);\n }\n }\n public static Session getSession()\n throws HibernateException {\n return concreteSessionFactory.openSession();\n }\n\n public static void main(String[] args) {\n Session session=getSession();\n Transaction tx = session.beginTransaction();\n Salaries salaries = new Salaries();\n salaries.setEmpName(\"Rahul\");\n salaries.setBasic(10000);\n salaries.setConveyance(3000);\n salaries.setHra(7000);\n session.save(salaries);\n tx.commit();\n \n Salaries d= (Salaries)session.get(Salaries.class,new Integer(1)); \n \n System.out.println(\"Employee Total Salary :\"+d.getTotal());\n\n }\n\n}\n" }, { "code": null, "e": 5587, "s": 5452, "text": "On the above example, we use session.get(Salaries.class, new Integer(1)) to get the Salaries details from hibernate cache or database." }, { "code": null, "e": 6030, "s": 5587, "text": "Hibernate: insert into salaries (basic, conveyance, empname, hra, empid) values (?, ?, ?, ?, ?)\nHibernate: select salaries0_.empid as empid1_0_0_, salaries0_.basic as basic2_0_0_, salaries0_.conveyance as conveyan3_0_0_, salaries0_.empname as empname4_0_0_, salaries0_.hra as hra5_0_0_, salaries0_.basic + salaries0_.conveyance + salaries0_.hra as formula0_0_ from salaries salaries0_ where salaries0_.empid=?\nEmployee Total Salary :20000.0" }, { "code": null, "e": 6164, "s": 6030, "text": "On the above example, we use @Formula annotation for simple expression. If we want to make this some more extent, we do.. Like below." }, { "code": null, "e": 6234, "s": 6164, "text": "@Formula(\"(select min(s.hra) from salaries s) \")\nprivate float total;" }, { "code": null, "e": 6316, "s": 6234, "text": "If you change the code like above, you can get the minimum hra in salaries table." }, { "code": null, "e": 6333, "s": 6316, "text": "Happy Learning 🙂" }, { "code": null, "e": 6406, "s": 6333, "text": "\n\nHibernate-Formula-Annotation-Example\n\nFile size: 15 KB\nDownloads: 930\n" }, { "code": null, "e": 6983, "s": 6406, "text": "\nCalling Stored Procedures in Hibernate\nHibernate Filters Example Annotation\nAngularJs Search Filter Example\nBasic Hibernate Example with XML Configuration\nHibernate Composite Key Mapping Example\nHibernate One to One Mapping using primary key (XML)\nHibernate 4 Example with Annotations Mysql\nHibernate Criteria API with Example\nHibernate Left Join Example\nHibernate One To Many Using Annotations\nHibernate Table per Class strategy Annotations Example\n@Qualifier annotation example in Spring\nWhat is Hibernate\nHibernate cache first level example\nhibernate update query example\n" }, { "code": null, "e": 7022, "s": 6983, "text": "Calling Stored Procedures in Hibernate" }, { "code": null, "e": 7059, "s": 7022, "text": "Hibernate Filters Example Annotation" }, { "code": null, "e": 7091, "s": 7059, "text": "AngularJs Search Filter Example" }, { "code": null, "e": 7138, "s": 7091, "text": "Basic Hibernate Example with XML Configuration" }, { "code": null, "e": 7178, "s": 7138, "text": "Hibernate Composite Key Mapping Example" }, { "code": null, "e": 7231, "s": 7178, "text": "Hibernate One to One Mapping using primary key (XML)" }, { "code": null, "e": 7274, "s": 7231, "text": "Hibernate 4 Example with Annotations Mysql" }, { "code": null, "e": 7310, "s": 7274, "text": "Hibernate Criteria API with Example" }, { "code": null, "e": 7338, "s": 7310, "text": "Hibernate Left Join Example" }, { "code": null, "e": 7378, "s": 7338, "text": "Hibernate One To Many Using Annotations" }, { "code": null, "e": 7433, "s": 7378, "text": "Hibernate Table per Class strategy Annotations Example" }, { "code": null, "e": 7473, "s": 7433, "text": "@Qualifier annotation example in Spring" }, { "code": null, "e": 7491, "s": 7473, "text": "What is Hibernate" }, { "code": null, "e": 7527, "s": 7491, "text": "Hibernate cache first level example" }, { "code": null, "e": 7558, "s": 7527, "text": "hibernate update query example" }, { "code": null, "e": 8633, "s": 7558, "text": "\n\n\n\n\n\nSumit\nJuly 17, 2020 at 1:45 pm - Reply \n\nI am seeing the below error. My POJO looks like this:\nprivate Long longOldValue;\nprivate String oldValue;\nprivate Long longNewValue;\nprivate String newValue;\nprivate long created;\nprivate String reasonChange;\n@Formula(“longNewValue-longOldValue”)\nprivate Long difference;\njava.sql.SQLSyntaxErrorException: Unknown column ‘applicatio1_.longNewValue’ in ‘field list’\nat com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120) ~[mysql-connector-java-8.0.19.jar:8.0.19]\nat com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.19.jar:8.0.19]\nat com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.19.jar:8.0.19]\nat com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953) ~[mysql-connector-java-8.0.19.jar:8.0.19]\nat com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1003) ~[mysql-connector-java-8.0.19.jar:8.0.19]\n\n\n\n\n" }, { "code": null, "e": 9706, "s": 8633, "text": "\n\n\n\n\nSumit\nJuly 17, 2020 at 1:45 pm - Reply \n\nI am seeing the below error. My POJO looks like this:\nprivate Long longOldValue;\nprivate String oldValue;\nprivate Long longNewValue;\nprivate String newValue;\nprivate long created;\nprivate String reasonChange;\n@Formula(“longNewValue-longOldValue”)\nprivate Long difference;\njava.sql.SQLSyntaxErrorException: Unknown column ‘applicatio1_.longNewValue’ in ‘field list’\nat com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120) ~[mysql-connector-java-8.0.19.jar:8.0.19]\nat com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.19.jar:8.0.19]\nat com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.19.jar:8.0.19]\nat com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953) ~[mysql-connector-java-8.0.19.jar:8.0.19]\nat com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1003) ~[mysql-connector-java-8.0.19.jar:8.0.19]\n\n\n\n" }, { "code": null, "e": 9760, "s": 9706, "text": "I am seeing the below error. My POJO looks like this:" }, { "code": null, "e": 9978, "s": 9760, "text": "private Long longOldValue;\nprivate String oldValue;\nprivate Long longNewValue;\nprivate String newValue;\nprivate long created;\nprivate String reasonChange;\n@Formula(“longNewValue-longOldValue”)\nprivate Long difference;" }, { "code": null, "e": 10729, "s": 9978, "text": "java.sql.SQLSyntaxErrorException: Unknown column ‘applicatio1_.longNewValue’ in ‘field list’\nat com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120) ~[mysql-connector-java-8.0.19.jar:8.0.19]\nat com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.19.jar:8.0.19]\nat com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.19.jar:8.0.19]\nat com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953) ~[mysql-connector-java-8.0.19.jar:8.0.19]\nat com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1003) ~[mysql-connector-java-8.0.19.jar:8.0.19]" }, { "code": null, "e": 10735, "s": 10733, "text": "Δ" }, { "code": null, "e": 10761, "s": 10735, "text": " Hibernate – Introduction" }, { "code": null, "e": 10785, "s": 10761, "text": " Hibernate – Advantages" }, { "code": null, "e": 10817, "s": 10785, "text": " Hibernate – Download and Setup" }, { "code": null, "e": 10847, "s": 10817, "text": " Hibernate – Sql Dialect list" }, { "code": null, "e": 10877, "s": 10847, "text": " Hibernate – Helloworld – XML" }, { "code": null, "e": 10915, "s": 10877, "text": " Hibernate – Install Tools in Eclipse" }, { "code": null, "e": 10942, "s": 10915, "text": " Hibernate – Object States" }, { "code": null, "e": 10980, "s": 10942, "text": " Hibernate – Helloworld – Annotations" }, { "code": null, "e": 11018, "s": 10980, "text": " Hibernate – One to One Mapping – XML" }, { "code": null, "e": 11068, "s": 11018, "text": " Hibernate – One to One Mapping foreign key – XML" }, { "code": null, "e": 11098, "s": 11068, "text": " Hibernate – One To Many -XML" }, { "code": null, "e": 11137, "s": 11098, "text": " Hibernate – One To Many – Annotations" }, { "code": null, "e": 11177, "s": 11137, "text": " Hibernate – Many to Many Mapping – XML" }, { "code": null, "e": 11208, "s": 11177, "text": " Hibernate – Many to One – XML" }, { "code": null, "e": 11243, "s": 11208, "text": " Hibernate – Composite Key Mapping" }, { "code": null, "e": 11268, "s": 11243, "text": " Hibernate – Named Query" }, { "code": null, "e": 11298, "s": 11268, "text": " Hibernate – Native SQL Query" }, { "code": null, "e": 11327, "s": 11298, "text": " Hibernate – load() vs get()" }, { "code": null, "e": 11364, "s": 11327, "text": " Hibernate Criteria API with Example" }, { "code": null, "e": 11390, "s": 11364, "text": " Hibernate – Restrictions" }, { "code": null, "e": 11414, "s": 11390, "text": " Hibernate – Projection" }, { "code": null, "e": 11448, "s": 11414, "text": " Hibernate – Query Language (HQL)" }, { "code": null, "e": 11482, "s": 11448, "text": " Hibernate – Groupby Criteria HQL" }, { "code": null, "e": 11512, "s": 11482, "text": " Hibernate – Orderby Criteria" }, { "code": null, "e": 11545, "s": 11512, "text": " Hibernate – HQLSelect Operation" }, { "code": null, "e": 11577, "s": 11545, "text": " Hibernate – HQL Update, Delete" }, { "code": null, "e": 11603, "s": 11577, "text": " Hibernate – Update Query" }, { "code": null, "e": 11632, "s": 11603, "text": " Hibernate – Update vs Merge" }, { "code": null, "e": 11656, "s": 11632, "text": " Hibernate – Right Join" }, { "code": null, "e": 11679, "s": 11656, "text": " Hibernate – Left Join" }, { "code": null, "e": 11703, "s": 11679, "text": " Hibernate – Pagination" }, { "code": null, "e": 11734, "s": 11703, "text": " Hibernate – Generator Classes" }, { "code": null, "e": 11764, "s": 11734, "text": " Hibernate – Custom Generator" }, { "code": null, "e": 11798, "s": 11764, "text": " Hibernate – Inheritance Mappings" }, { "code": null, "e": 11827, "s": 11798, "text": " Hibernate – Table per Class" }, { "code": null, "e": 11860, "s": 11827, "text": " Hibernate – Table per Sub Class" }, { "code": null, "e": 11898, "s": 11860, "text": " Hibernate – Table per Concrete Class" }, { "code": null, "e": 11940, "s": 11898, "text": " Hibernate – Table per Class Annotations" }, { "code": null, "e": 11971, "s": 11940, "text": " Hibernate – Stored Procedures" }, { "code": null, "e": 12004, "s": 11971, "text": " Hibernate – @Formula Annotation" }, { "code": null, "e": 12042, "s": 12004, "text": " Hibernate – Singleton SessionFactory" }, { "code": null, "e": 12067, "s": 12042, "text": " Hibernate – Interceptor" }, { "code": null, "e": 12113, "s": 12067, "text": " hbm2ddl.auto Example in Hibernate XML Config" } ]
How to push an array in MongoDB?
To push an array, use $push in MongoDB. Let us first create a collection with documents − > db.demo399.insertOne({Name:"Chris",Age:21}); { "acknowledged" : true, "insertedId" : ObjectId("5e610339fac4d418a017856d") } > db.demo399.insertOne({Name:"David",Age:22}); { "acknowledged" : true, "insertedId" : ObjectId("5e610341fac4d418a017856e") } > db.demo399.insertOne({Name:"Chris",Age:21}); { "acknowledged" : true, "insertedId" : ObjectId("5e610355fac4d418a017856f") } > db.demo399.insertOne({Name:"Bob",Age:23}); { "acknowledged" : true, "insertedId" : ObjectId("5e61035efac4d418a0178570") } > db.demo399.insertOne({Name:"David",Age:22}); { "acknowledged" : true, "insertedId" : ObjectId("5e610364fac4d418a0178571") } Display all documents from a collection with the help of find() method − > db.demo399.find(); This will produce the following output − { "_id" : ObjectId("5e610339fac4d418a017856d"), "Name" : "Chris", "Age" : 21 } { "_id" : ObjectId("5e610341fac4d418a017856e"), "Name" : "David", "Age" : 22 } { "_id" : ObjectId("5e610355fac4d418a017856f"), "Name" : "Chris", "Age" : 21 } { "_id" : ObjectId("5e61035efac4d418a0178570"), "Name" : "Bob", "Age" : 23 } { "_id" : ObjectId("5e610364fac4d418a0178571"), "Name" : "David", "Age" : 22 } Following is the query to push an array − > db.demo399.aggregate( ... [ ... { ... $group: ... { ... _id: null, ... array: { $push: { Name: "$Name", Age: "$Age" } } ... } ... } ... ] ... ) This will produce the following output − { "_id" : null, "array" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "David", "Age" : 22 }, { "Name" : "Chris", "Age" : 21 }, { "Name" : "Bob", "Age" : 23 }, { "Name" : "David", "Age" : 22 } ] }
[ { "code": null, "e": 1152, "s": 1062, "text": "To push an array, use $push in MongoDB. Let us first create a collection with documents −" }, { "code": null, "e": 1810, "s": 1152, "text": "> db.demo399.insertOne({Name:\"Chris\",Age:21});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e610339fac4d418a017856d\")\n}\n> db.demo399.insertOne({Name:\"David\",Age:22});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e610341fac4d418a017856e\")\n}\n> db.demo399.insertOne({Name:\"Chris\",Age:21});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e610355fac4d418a017856f\")\n}\n> db.demo399.insertOne({Name:\"Bob\",Age:23});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e61035efac4d418a0178570\")\n}\n> db.demo399.insertOne({Name:\"David\",Age:22});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e610364fac4d418a0178571\")\n}" }, { "code": null, "e": 1883, "s": 1810, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1904, "s": 1883, "text": "> db.demo399.find();" }, { "code": null, "e": 1945, "s": 1904, "text": "This will produce the following output −" }, { "code": null, "e": 2338, "s": 1945, "text": "{ \"_id\" : ObjectId(\"5e610339fac4d418a017856d\"), \"Name\" : \"Chris\", \"Age\" : 21 }\n{ \"_id\" : ObjectId(\"5e610341fac4d418a017856e\"), \"Name\" : \"David\", \"Age\" : 22 }\n{ \"_id\" : ObjectId(\"5e610355fac4d418a017856f\"), \"Name\" : \"Chris\", \"Age\" : 21 }\n{ \"_id\" : ObjectId(\"5e61035efac4d418a0178570\"), \"Name\" : \"Bob\", \"Age\" : 23 }\n{ \"_id\" : ObjectId(\"5e610364fac4d418a0178571\"), \"Name\" : \"David\", \"Age\" : 22 }" }, { "code": null, "e": 2380, "s": 2338, "text": "Following is the query to push an array −" }, { "code": null, "e": 2595, "s": 2380, "text": "> db.demo399.aggregate(\n... [\n... {\n... $group:\n... {\n... _id: null,\n... array: { $push: { Name: \"$Name\", Age: \"$Age\" } }\n... }\n... }\n... ]\n... )" }, { "code": null, "e": 2636, "s": 2595, "text": "This will produce the following output −" }, { "code": null, "e": 2835, "s": 2636, "text": "{ \"_id\" : null, \"array\" : [ { \"Name\" : \"Chris\", \"Age\" : 21 }, { \"Name\" : \"David\", \"Age\" : 22 }, { \"Name\" : \"Chris\", \"Age\" : 21 }, { \"Name\" : \"Bob\", \"Age\" : 23 }, { \"Name\" : \"David\", \"Age\" : 22 } ] }" } ]
Convert all numbers in range [L, R] to binary number - GeeksforGeeks
24 Dec, 2021 Given two positive integer numbers L and R. The task is to convert all the numbers from L to R to binary number. Examples: Input: L = 1, R = 4Output: 11011100Explanation: The binary representation of the numbers 1, 2, 3 and 4 are: 1 = (1)22 = (10)23 = (11)24 = (100)2 Input: L = 2, R = 8Output:10111001011101111000 Approach: The problem can be solved using following approach. Traverse from L to R and convert every number to binary number. Store each number and print it at the end. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ code to implement the above approach#include <bits/stdc++.h>using namespace std; // Function to convert a number// to its binary equivalentvector<int> convertToBinary(int num){ vector<int> bits; if (num == 0) { bits.push_back(0); return bits; } while (num != 0) { bits.push_back(num % 2); // Integer division // gives quotient num = num / 2; } reverse(bits.begin(), bits.end()); return bits;} // Function to convert all numbers// in range [L, R] to binaryvector<vector<int> > getAllBinary(int l, int r){ // Vector to store the binary // representations of the numbers vector<vector<int> > binary_nos; for (int i = l; i <= r; i++) { vector<int> bits = convertToBinary(i); binary_nos.push_back(bits); } return binary_nos;} // Driver codeint main(){ int L = 2, R = 8; vector<vector<int> > binary_nos = getAllBinary(L, R); for (int i = 0; i < binary_nos.size(); i++) { for (int j = 0; j < binary_nos[i].size(); j++) cout << binary_nos[i][j]; cout << endl; } return 0;} // Java code to implement the above approachimport java.util.ArrayList;import java.util.Collections; class GFG { // Function to convert a number // to its binary equivalent public static ArrayList<Integer> convertToBinary(int num) { ArrayList<Integer> bits = new ArrayList<Integer>(); if (num == 0) { bits.add(0); return bits; } while (num != 0) { bits.add(num % 2); // Integer division // gives quotient num = num / 2; } Collections.reverse(bits); return bits; } // Function to convert all numbers // in range [L, R] to binary public static ArrayList<ArrayList<Integer>> getAllBinary(int l, int r) { // Vector to store the binary // representations of the numbers ArrayList<ArrayList<Integer>> binary_nos = new ArrayList<ArrayList<Integer>>(); for (int i = l; i <= r; i++) { ArrayList<Integer> bits = convertToBinary(i); binary_nos.add(bits); } return binary_nos; } // Driver code public static void main(String args[]) { int L = 2, R = 8; ArrayList<ArrayList<Integer>> binary_nos = getAllBinary(L, R); for (int i = 0; i < binary_nos.size(); i++) { for (int j = 0; j < binary_nos.get(i).size(); j++) System.out.print(binary_nos.get(i).get(j)); System.out.println(""); } }} // This code is contributed by saurabh_jaiswal. # Python 3 code to implement the above approach # Function to convert a number# to its binary equivalentdef convertToBinary(num): bits = [] if (num == 0): bits.append(0) return bits while (num != 0): bits.append(num % 2) # Integer division # gives quotient num = num // 2 bits.reverse() return bits # Function to convert all numbers# in range [L, R] to binarydef getAllBinary(l, r): # Vector to store the binary # representations of the numbers binary_nos = [] for i in range(l, r+1): bits = convertToBinary(i) binary_nos.append(bits) return binary_nos # Driver codeif __name__ == "__main__": L = 2 R = 8 binary_nos = getAllBinary(L, R) for i in range(len(binary_nos)): for j in range(len(binary_nos[i])): print(binary_nos[i][j], end="") print() # This code is contributed by ukasp. // C# code to implement the above approachusing System;using System.Collections.Generic; public class GFG { // Function to convert a number // to its binary equivalent public static List<int> convertToBinary(int num) { List<int> bits = new List<int>(); if (num == 0) { bits.Add(0); return bits; } while (num != 0) { bits.Add(num % 2); // int division // gives quotient num = num / 2; } bits.Reverse(); return bits; } // Function to convert all numbers // in range [L, R] to binary public static List<List<int>> getAllBinary(int l, int r) { // List to store the binary // representations of the numbers List<List<int>> binary_nos = new List<List<int>>(); for (int i = l; i <= r; i++) { List<int> bits = convertToBinary(i); binary_nos.Add(bits); } return binary_nos; } // Driver code public static void Main(String []args) { int L = 2, R = 8; List<List<int>> binary_nos = getAllBinary(L, R); for (int i = 0; i < binary_nos.Count; i++) { for (int j = 0; j < binary_nos[i].Count; j++) Console.Write(binary_nos[i][j]); Console.WriteLine(""); } }} // This code is contributed by 29AjayKumar <script> // JavaScript code to implement the above approach // Function to convert a number // to its binary equivalent const convertToBinary = (num) => { let bits = []; if (num == 0) { bits.push(0); return bits; } while (num != 0) { bits.push(num % 2); // Integer division // gives quotient num = parseInt(num / 2); } bits.reverse() return bits; } // Function to convert all numbers // in range [L, R] to binary const getAllBinary = (l, r) => { // Vector to store the binary // representations of the numbers let binary_nos = []; for (let i = l; i <= r; i++) { let bits = convertToBinary(i); binary_nos.push(bits); } return binary_nos; } // Driver code let L = 2, R = 8; let binary_nos = getAllBinary(L, R); for (let i = 0; i < binary_nos.length; i++) { for (let j = 0; j < binary_nos[i].length; j++) document.write(`${binary_nos[i][j]}`); document.write("<br/>"); } // This code is contributed by rakeshsahni</script> 10 11 100 101 110 111 1000 Time Complexity: O(N * LogR) Where N is the count of numbers in range [L, R]Auxiliary Space: O(N * logR) rakeshsahni ukasp _saurabh_jaiswal 29AjayKumar binary-representation Bit Magic Mathematical Mathematical Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Set, Clear and Toggle a given bit of a number in C Program to find parity Bit Tricks for Competitive Programming Check for Integer Overflow Reverse actual bits of the given number Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Program to find sum of elements in a given array
[ { "code": null, "e": 24597, "s": 24569, "text": "\n24 Dec, 2021" }, { "code": null, "e": 24711, "s": 24597, "text": "Given two positive integer numbers L and R. The task is to convert all the numbers from L to R to binary number. " }, { "code": null, "e": 24721, "s": 24711, "text": "Examples:" }, { "code": null, "e": 24866, "s": 24721, "text": "Input: L = 1, R = 4Output: 11011100Explanation: The binary representation of the numbers 1, 2, 3 and 4 are: 1 = (1)22 = (10)23 = (11)24 = (100)2" }, { "code": null, "e": 24913, "s": 24866, "text": "Input: L = 2, R = 8Output:10111001011101111000" }, { "code": null, "e": 24975, "s": 24913, "text": "Approach: The problem can be solved using following approach." }, { "code": null, "e": 25039, "s": 24975, "text": "Traverse from L to R and convert every number to binary number." }, { "code": null, "e": 25082, "s": 25039, "text": "Store each number and print it at the end." }, { "code": null, "e": 25133, "s": 25082, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 25137, "s": 25133, "text": "C++" }, { "code": null, "e": 25142, "s": 25137, "text": "Java" }, { "code": null, "e": 25150, "s": 25142, "text": "Python3" }, { "code": null, "e": 25153, "s": 25150, "text": "C#" }, { "code": null, "e": 25164, "s": 25153, "text": "Javascript" }, { "code": "// C++ code to implement the above approach#include <bits/stdc++.h>using namespace std; // Function to convert a number// to its binary equivalentvector<int> convertToBinary(int num){ vector<int> bits; if (num == 0) { bits.push_back(0); return bits; } while (num != 0) { bits.push_back(num % 2); // Integer division // gives quotient num = num / 2; } reverse(bits.begin(), bits.end()); return bits;} // Function to convert all numbers// in range [L, R] to binaryvector<vector<int> > getAllBinary(int l, int r){ // Vector to store the binary // representations of the numbers vector<vector<int> > binary_nos; for (int i = l; i <= r; i++) { vector<int> bits = convertToBinary(i); binary_nos.push_back(bits); } return binary_nos;} // Driver codeint main(){ int L = 2, R = 8; vector<vector<int> > binary_nos = getAllBinary(L, R); for (int i = 0; i < binary_nos.size(); i++) { for (int j = 0; j < binary_nos[i].size(); j++) cout << binary_nos[i][j]; cout << endl; } return 0;}", "e": 26342, "s": 25164, "text": null }, { "code": "// Java code to implement the above approachimport java.util.ArrayList;import java.util.Collections; class GFG { // Function to convert a number // to its binary equivalent public static ArrayList<Integer> convertToBinary(int num) { ArrayList<Integer> bits = new ArrayList<Integer>(); if (num == 0) { bits.add(0); return bits; } while (num != 0) { bits.add(num % 2); // Integer division // gives quotient num = num / 2; } Collections.reverse(bits); return bits; } // Function to convert all numbers // in range [L, R] to binary public static ArrayList<ArrayList<Integer>> getAllBinary(int l, int r) { // Vector to store the binary // representations of the numbers ArrayList<ArrayList<Integer>> binary_nos = new ArrayList<ArrayList<Integer>>(); for (int i = l; i <= r; i++) { ArrayList<Integer> bits = convertToBinary(i); binary_nos.add(bits); } return binary_nos; } // Driver code public static void main(String args[]) { int L = 2, R = 8; ArrayList<ArrayList<Integer>> binary_nos = getAllBinary(L, R); for (int i = 0; i < binary_nos.size(); i++) { for (int j = 0; j < binary_nos.get(i).size(); j++) System.out.print(binary_nos.get(i).get(j)); System.out.println(\"\"); } }} // This code is contributed by saurabh_jaiswal.", "e": 27694, "s": 26342, "text": null }, { "code": "# Python 3 code to implement the above approach # Function to convert a number# to its binary equivalentdef convertToBinary(num): bits = [] if (num == 0): bits.append(0) return bits while (num != 0): bits.append(num % 2) # Integer division # gives quotient num = num // 2 bits.reverse() return bits # Function to convert all numbers# in range [L, R] to binarydef getAllBinary(l, r): # Vector to store the binary # representations of the numbers binary_nos = [] for i in range(l, r+1): bits = convertToBinary(i) binary_nos.append(bits) return binary_nos # Driver codeif __name__ == \"__main__\": L = 2 R = 8 binary_nos = getAllBinary(L, R) for i in range(len(binary_nos)): for j in range(len(binary_nos[i])): print(binary_nos[i][j], end=\"\") print() # This code is contributed by ukasp.", "e": 28615, "s": 27694, "text": null }, { "code": "// C# code to implement the above approachusing System;using System.Collections.Generic; public class GFG { // Function to convert a number // to its binary equivalent public static List<int> convertToBinary(int num) { List<int> bits = new List<int>(); if (num == 0) { bits.Add(0); return bits; } while (num != 0) { bits.Add(num % 2); // int division // gives quotient num = num / 2; } bits.Reverse(); return bits; } // Function to convert all numbers // in range [L, R] to binary public static List<List<int>> getAllBinary(int l, int r) { // List to store the binary // representations of the numbers List<List<int>> binary_nos = new List<List<int>>(); for (int i = l; i <= r; i++) { List<int> bits = convertToBinary(i); binary_nos.Add(bits); } return binary_nos; } // Driver code public static void Main(String []args) { int L = 2, R = 8; List<List<int>> binary_nos = getAllBinary(L, R); for (int i = 0; i < binary_nos.Count; i++) { for (int j = 0; j < binary_nos[i].Count; j++) Console.Write(binary_nos[i][j]); Console.WriteLine(\"\"); } }} // This code is contributed by 29AjayKumar", "e": 29830, "s": 28615, "text": null }, { "code": "<script> // JavaScript code to implement the above approach // Function to convert a number // to its binary equivalent const convertToBinary = (num) => { let bits = []; if (num == 0) { bits.push(0); return bits; } while (num != 0) { bits.push(num % 2); // Integer division // gives quotient num = parseInt(num / 2); } bits.reverse() return bits; } // Function to convert all numbers // in range [L, R] to binary const getAllBinary = (l, r) => { // Vector to store the binary // representations of the numbers let binary_nos = []; for (let i = l; i <= r; i++) { let bits = convertToBinary(i); binary_nos.push(bits); } return binary_nos; } // Driver code let L = 2, R = 8; let binary_nos = getAllBinary(L, R); for (let i = 0; i < binary_nos.length; i++) { for (let j = 0; j < binary_nos[i].length; j++) document.write(`${binary_nos[i][j]}`); document.write(\"<br/>\"); } // This code is contributed by rakeshsahni</script>", "e": 31028, "s": 29830, "text": null }, { "code": null, "e": 31058, "s": 31031, "text": "10\n11\n100\n101\n110\n111\n1000" }, { "code": null, "e": 31165, "s": 31060, "text": "Time Complexity: O(N * LogR) Where N is the count of numbers in range [L, R]Auxiliary Space: O(N * logR)" }, { "code": null, "e": 31179, "s": 31167, "text": "rakeshsahni" }, { "code": null, "e": 31185, "s": 31179, "text": "ukasp" }, { "code": null, "e": 31202, "s": 31185, "text": "_saurabh_jaiswal" }, { "code": null, "e": 31214, "s": 31202, "text": "29AjayKumar" }, { "code": null, "e": 31236, "s": 31214, "text": "binary-representation" }, { "code": null, "e": 31246, "s": 31236, "text": "Bit Magic" }, { "code": null, "e": 31259, "s": 31246, "text": "Mathematical" }, { "code": null, "e": 31272, "s": 31259, "text": "Mathematical" }, { "code": null, "e": 31282, "s": 31272, "text": "Bit Magic" }, { "code": null, "e": 31380, "s": 31282, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31389, "s": 31380, "text": "Comments" }, { "code": null, "e": 31402, "s": 31389, "text": "Old Comments" }, { "code": null, "e": 31453, "s": 31402, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 31476, "s": 31453, "text": "Program to find parity" }, { "code": null, "e": 31515, "s": 31476, "text": "Bit Tricks for Competitive Programming" }, { "code": null, "e": 31542, "s": 31515, "text": "Check for Integer Overflow" }, { "code": null, "e": 31582, "s": 31542, "text": "Reverse actual bits of the given number" }, { "code": null, "e": 31612, "s": 31582, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 31672, "s": 31612, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 31687, "s": 31672, "text": "C++ Data Types" }, { "code": null, "e": 31730, "s": 31687, "text": "Set in C++ Standard Template Library (STL)" } ]
Check if a Java ArrayList contains a given item or not
The java.util.ArrayList.contains() method can be used to check if a Java ArrayList contains a given item or not. This method has a single parameter i.e. the item whose presence in the ArrayList is tested. Also it returns true if the item is present in the ArrayList and false if the item is not present. A program that demonstrates this is given as follows − Live Demo import java.util.ArrayList; import java.util.List; public class Demo { public static void main(String[] args) { List aList = new ArrayList(); aList.add("A"); aList.add("B"); aList.add("C"); aList.add("D"); aList.add("E"); if(aList.contains("C")) System.out.println("The element C is available in the ArrayList"); else System.out.println("The element C is not available in the ArrayList"); if(aList.contains("H")) System.out.println("The element H is available in the ArrayList"); else System.out.println("The element H is not available in the ArrayList"); } } The element C is available in the ArrayList The element H is not available in the ArrayList Now let us understand the above program. The ArrayList aList is created. Then ArrayList.add() is used to add the elements to the ArrayList. ArrayList.contains() is used to check if “C” and “H” are available in the ArrayList. Then an if statement is used to print if they are available or not. A code snippet which demonstrates this is as follows − List aList = new ArrayList(); aList.add("A"); aList.add("B"); aList.add("C"); aList.add("D"); aList.add("E"); if(aList.contains("C")) System.out.println("The element C is available in the ArrayList"); else System.out.println("The element C is not available in the ArrayList"); if(aList.contains("H")) System.out.println("The element H is available in the ArrayList"); else System.out.println("The element H is not available in the ArrayList");
[ { "code": null, "e": 1366, "s": 1062, "text": "The java.util.ArrayList.contains() method can be used to check if a Java ArrayList contains a given item or not. This method has a single parameter i.e. the item whose presence in the ArrayList is tested. Also it returns true if the item is present in the ArrayList and false if the item is not present." }, { "code": null, "e": 1421, "s": 1366, "text": "A program that demonstrates this is given as follows −" }, { "code": null, "e": 1432, "s": 1421, "text": " Live Demo" }, { "code": null, "e": 2094, "s": 1432, "text": "import java.util.ArrayList;\nimport java.util.List;\npublic class Demo {\n public static void main(String[] args) {\n List aList = new ArrayList();\n aList.add(\"A\");\n aList.add(\"B\");\n aList.add(\"C\");\n aList.add(\"D\");\n aList.add(\"E\");\n if(aList.contains(\"C\"))\n System.out.println(\"The element C is available in the ArrayList\");\n else\n System.out.println(\"The element C is not available in the ArrayList\");\n if(aList.contains(\"H\"))\n System.out.println(\"The element H is available in the ArrayList\");\n else\n System.out.println(\"The element H is not available in the ArrayList\");\n }\n}" }, { "code": null, "e": 2186, "s": 2094, "text": "The element C is available in the ArrayList\nThe element H is not available in the ArrayList" }, { "code": null, "e": 2227, "s": 2186, "text": "Now let us understand the above program." }, { "code": null, "e": 2534, "s": 2227, "text": "The ArrayList aList is created. Then ArrayList.add() is used to add the elements to the ArrayList. ArrayList.contains() is used to check if “C” and “H” are available in the ArrayList. Then an if statement is used to print if they are available or not. A code snippet which demonstrates this is as follows −" }, { "code": null, "e": 2990, "s": 2534, "text": "List aList = new ArrayList();\naList.add(\"A\");\naList.add(\"B\");\naList.add(\"C\");\naList.add(\"D\");\naList.add(\"E\");\nif(aList.contains(\"C\"))\n System.out.println(\"The element C is available in the ArrayList\");\nelse\n System.out.println(\"The element C is not available in the ArrayList\");\nif(aList.contains(\"H\"))\n System.out.println(\"The element H is available in the ArrayList\");\nelse\n System.out.println(\"The element H is not available in the ArrayList\");" } ]
JavaScript String - fontsize() Method
This method causes a string to be displayed in the specified size as if it were in a <font size = "size"> tag. Its syntax is as follows − string.fontsize( size ) size − An integer between 1 and 7, a string representing a signed integer between 1 and 7. Returns the string with <font size="size"> tag. Try the following example. <html> <head> <title>JavaScript String fontsize() Method</title> </head> <body> <script type = "text/javascript"> var str = new String("Hello world"); alert(str.fontsize( 3 )); </script> </body> </html> <font size = "3">Hello world</font> 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2577, "s": 2466, "text": "This method causes a string to be displayed in the specified size as if it were in a <font size = \"size\"> tag." }, { "code": null, "e": 2604, "s": 2577, "text": "Its syntax is as follows −" }, { "code": null, "e": 2629, "s": 2604, "text": "string.fontsize( size )\n" }, { "code": null, "e": 2720, "s": 2629, "text": "size − An integer between 1 and 7, a string representing a signed integer between 1 and 7." }, { "code": null, "e": 2768, "s": 2720, "text": "Returns the string with <font size=\"size\"> tag." }, { "code": null, "e": 2795, "s": 2768, "text": "Try the following example." }, { "code": null, "e": 3058, "s": 2795, "text": "<html>\n <head>\n <title>JavaScript String fontsize() Method</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var str = new String(\"Hello world\");\n alert(str.fontsize( 3 ));\n </script> \n </body>\n</html>" }, { "code": null, "e": 3095, "s": 3058, "text": "<font size = \"3\">Hello world</font>\n" }, { "code": null, "e": 3130, "s": 3095, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3144, "s": 3130, "text": " Anadi Sharma" }, { "code": null, "e": 3178, "s": 3144, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 3192, "s": 3178, "text": " Lets Kode It" }, { "code": null, "e": 3227, "s": 3192, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3244, "s": 3227, "text": " Frahaan Hussain" }, { "code": null, "e": 3279, "s": 3244, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3296, "s": 3279, "text": " Frahaan Hussain" }, { "code": null, "e": 3329, "s": 3296, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 3357, "s": 3329, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3391, "s": 3357, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 3419, "s": 3391, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3426, "s": 3419, "text": " Print" }, { "code": null, "e": 3437, "s": 3426, "text": " Add Notes" } ]
How to serialize and deserialize an object in Java?
The Serialization is a process of changing the state of an object into a byte stream, an object is said to be serializable if its class or parent classes implement either the Serializable or Externalizable interface and the Deserialization is a process of converting the serialized object back into a copy of an object. During serialization, if we don’t want to write the state of a particular variable in a byte stream using a transient keyword. When the JVM comes up to the transient keyword, it ignores the original state of a variable and stores a default value of that data type i.e. 0 for int, 0 for byte, 0.0 for float, etc. A Serialization of an object can be done through FileOutputStream and ObjectOutputStream class. import java.io.*; public class SerializationTest implements Serializable { int a = 1, b = 2; transient int c = 3; public static void main(String[] args) throws Exception { SerializationTest obj = new SerializationTest(); // serialization FileOutputStream fos = new FileOutputStream("serialization.txt"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(obj); // de-serialization FileInputStream fis = new FileInputStream("serialization.txt"); ObjectInputStream ois = new ObjectInputStream(fis); SerializationTest test = (SerializationTest)ois.readObject(); System.out.println("a = " + test.a); System.out.println("b = " + test.b); System.out.println("c = " + test.c); } } a = 1 b = 2 c = 0
[ { "code": null, "e": 1382, "s": 1062, "text": "The Serialization is a process of changing the state of an object into a byte stream, an object is said to be serializable if its class or parent classes implement either the Serializable or Externalizable interface and the Deserialization is a process of converting the serialized object back into a copy of an object." }, { "code": null, "e": 1790, "s": 1382, "text": "During serialization, if we don’t want to write the state of a particular variable in a byte stream using a transient keyword. When the JVM comes up to the transient keyword, it ignores the original state of a variable and stores a default value of that data type i.e. 0 for int,\n0 for byte, 0.0 for float, etc. A Serialization of an object can be done through FileOutputStream and ObjectOutputStream class." }, { "code": null, "e": 2567, "s": 1790, "text": "import java.io.*;\npublic class SerializationTest implements Serializable {\n int a = 1, b = 2;\n transient int c = 3;\n public static void main(String[] args) throws Exception {\n SerializationTest obj = new SerializationTest();\n // serialization\n FileOutputStream fos = new FileOutputStream(\"serialization.txt\");\n ObjectOutputStream oos = new ObjectOutputStream(fos);\n oos.writeObject(obj);\n // de-serialization\n FileInputStream fis = new FileInputStream(\"serialization.txt\");\n ObjectInputStream ois = new ObjectInputStream(fis);\n SerializationTest test = (SerializationTest)ois.readObject();\n System.out.println(\"a = \" + test.a);\n System.out.println(\"b = \" + test.b);\n System.out.println(\"c = \" + test.c);\n }\n}" }, { "code": null, "e": 2585, "s": 2567, "text": "a = 1\nb = 2\nc = 0" } ]
Getting and Cleaning Data (JHU Coursera, Course 3) | by Michael Galarnyk | Towards Data Science
The third course in the data science specialization, “Getting and Cleaning Data” is an essential course. As always the code for the quizzes and assignments is located on my github. Week 1 Review: Reading Excel, XML and JSON files is essential. I am happy with the lecture on the data.table package since I use it for all my quizzes and assignments for this specialization. I wish they had more than one lecture on it though as it isn’t that easy to learn. The American Community Survey distributes downloadable data about United States communities. Download the 2006 microdata survey about housing for the state of Idaho using download.file() from here: https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv and load the data into R. The code book, describing the variable names is here: https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FPUMSDataDict06.pdf How many housing units in this survey were worth more than $1,000,000? # fread url requires curl package on mac # install.packages("curl") library(data.table) housing <- data.table::fread("https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv") # VAL attribute says how much property is worth, .N is the number of rows # VAL == 24 means more than $1,000,000 housing[VAL == 24, .N] # Answer: # 53 Use the data you loaded from Question 1. Consider the variable FES in the code book. Which of the "tidy data" principles does this variable violate? Tidy data one variable per column Download the Excel spreadsheet on Natural Gas Aquisition Program here: https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FDATA.gov_NGAP.xlsx Read rows 18-23 and columns 7-15 into R and assign the result to a variable called: dat What is the value of: sum(dat$Zip*dat$Ext,na.rm=T) (original data source: http://catalog.data.gov/dataset/natural-gas-acquisition-program) fileUrl <- "http://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FDATA.gov_NGAP.xlsx" download.file(fileUrl, destfile = paste0(getwd(), '/getdata%2Fdata%2FDATA.gov_NGAP.xlsx'), method = "curl") dat <- xlsx::read.xlsx(file = "getdata%2Fdata%2FDATA.gov_NGAP.xlsx", sheetIndex = 1, rowIndex = 18:23, colIndex = 7:15) sum(dat$Zip*dat$Ext,na.rm=T) # Answer: # 36534720 Read the XML data on Baltimore restaurants from here: https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Frestaurants.xml How many restaurants have zipcode 21231? Use http instead of https, which caused the message Error: XML content does not seem to be XML: 'https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Frestaurants.xml'. # install.packages("XML") library("XML") fileURL<-"https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Frestaurants.xml" doc <- XML::xmlTreeParse(sub("s", "", fileURL), useInternal = TRUE) rootNode <- XML::xmlRoot(doc) zipcodes <- XML::xpathSApply(rootNode, "//zipcode", XML::xmlValue) xmlZipcodeDT <- data.table::data.table(zipcode = zipcodes) xmlZipcodeDT[zipcode == "21231", .N] # Answer: # 127 The American Community Survey distributes downloadable data about United States communities. Download the 2006 microdata survey about housing for the state of Idaho using download.file() from here: https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06pid.csv using the fread() command load the data into an R object DT Which of the following is the fastest way to calculate the average value of the variable pwgtp15 broken down by sex using the data.table package? DT <- data.table::fread("https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06pid.csv") # Answer (fastest): system.time(DT[,mean(pwgtp15),by=SEX]) Week 2 Review: More of the same. Interacting with various data sources (MySQL, HDF5 etc). I wish they would have talked about the github API more. I noticed a lot of students had a lot of trouble with that quiz question. So much so that I wrote a separate blog post on how to Access Data with the Github API. Register an application with the Github API here https://github.com/settings/applications. Access the API to get information on your instructors repositories (hint: this is the url you want "https://api.github.com/users/jtleek/repos"). Use this data to find the time that the datasharing repo was created. What time was it created? This tutorial may be useful (https://github.com/hadley/httr/blob/master/demo/oauth2-github.r). You may also need to run the code in the base R package and not R studio. Since many people had issues with this I wrote a blog post on how to do this question: Github API using R #install.packages("jsonlite") #install.packages("httpuv") #install.packages("httr") library(jsonlite) library(httpuv) library(httr) # Can be github, linkedin etc depending on application oauth_endpoints("github") # Change based on your appname, key, and secret myapp <- oauth_app(appname = "Youtube_Michael_Galarnyk", key = "8758a6bf9a146e1da0c1", secret = "b9504edde46b794414495bd9c33ea28cbfd87824") # Get OAuth credentials github_token <- oauth2.0_token(oauth_endpoints("github"), myapp) # Use API gtoken <- config(token = github_token) req <- GET("https://api.github.com/users/jtleek/repos", gtoken) # Take action on http error stop_for_status(req) # Extract content from a request json1 = content(req) # Convert to a data.frame gitDF = jsonlite::fromJSON(jsonlite::toJSON(json1)) # Subset data.frame gitDF[gitDF$full_name == "jtleek/datasharing", "created_at"] # Answer: # 2013-11-07T13:25:07Z The sqldf package allows for execution of SQL commands on R data frames. We will use the sqldf package to practice the queries we might send with the dbSendQuery command in RMySQL. Download the American Community Survey data and load it into an R object called acs https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06pid.csv Which of the following commands will select only the data for the probability weights pwgtp1 with ages less than 50? # install.packages("sqldf") library("sqldf") url <- "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06pid.csv" f <- file.path(getwd(), "ss06pid.csv") download.file(url, f) acs <- data.table::data.table(read.csv(f)) # Answer: query1 <- sqldf("select pwgtp1 from acs where AGEP < 50") Using the same data frame you created in the previous problem, what is the equivalent function to unique(acs$AGEP) # Answer # sqldf("select distinct AGEP from acs") How many characters are in the 10th, 20th, 30th and 100th lines of HTML from this page: http://biostat.jhsph.edu/~jleek/contact.html (Hint: the nchar() function in R may be helpful) connection <- url("http://biostat.jhsph.edu/~jleek/contact.html") htmlCode <- readLines(connection) close(connection) c(nchar(htmlCode[10]), nchar(htmlCode[20]), nchar(htmlCode[30]), nchar(htmlCode[100])) # Answer: # 45 31 7 25 Read this data set into R and report the sum of the numbers in the fourth of the nine columns. https://d396qusza40orc.cloudfront.net/getdata%2Fwksst8110.for Original source of the data: http://www.cpc.ncep.noaa.gov/data/indices/wksst8110.for (Hint this is a fixed width file format) url <- "https://d396qusza40orc.cloudfront.net/getdata%2Fwksst8110.for" lines <- readLines(url, n = 10) w <- c(1, 9, 5, 4, 1, 3, 5, 4, 1, 3, 5, 4, 1, 3, 5, 4, 1, 3) colNames <- c("filler", "week", "filler", "sstNino12", "filler", "sstaNino12", "filler", "sstNino3", "filler", "sstaNino3", "filler", "sstNino34", "filler", "sstaNino34", "filler", "sstNino4", "filler", "sstaNino4") d <- read.fwf(url, w, header = FALSE, skip = 4, col.names = colNames) d <- d[, grep("^[^filler]", names(d))] sum(d[, 4]) # Answer: # 32426.7 Week 3 and 4 Review: Going over dplyr after going over data.table seemed like a bit much. Week 4 went over Regular Expressions and editing text variables is really important and really should have been covered before the week 3 quiz as it was needed. The American Community Survey distributes downloadable data about United States communities. Download the 2006 microdata survey about housing for the state of Idaho using download.file() from here: https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv and load the data into R. The code book, describing the variable names is here: https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FPUMSDataDict06.pdf Create a logical vector that identifies the households on greater than 10 acres who sold more than $10,000 worth of agriculture products. Assign that logical vector to the variable agricultureLogical. Apply the which() function like this to identify the rows of the data frame where the logical vector is TRUE. which(agricultureLogical) What are the first 3 values that result? download.file('https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv' , 'ACS.csv' , method='curl' ) # Read data into data.frame ACS <- read.csv('ACS.csv') agricultureLogical <- ACS$ACR == 3 & ACS$AGS == 6 head(which(agricultureLogical), 3) # Answer: # 125 238 262 Using the jpeg package read in the following picture of your instructor into R https://d396qusza40orc.cloudfront.net/getdata%2Fjeff.jpg Use the parameter native=TRUE. What are the 30th and 80th quantiles of the resulting data? # install.packages('jpeg') library(jpeg) # Download the file download.file('https://d396qusza40orc.cloudfront.net/getdata%2Fjeff.jpg' , 'jeff.jpg' , mode='wb' ) # Read the image picture <- jpeg::readJPEG('jeff.jpg' , native=TRUE) # Get Sample Quantiles corressponding to given prob quantile(picture, probs = c(0.3, 0.8) ) # Answer: # 30% 80% # -15259150 -10575416 Load the Gross Domestic Product data for the 190 ranked countries in this data set: https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FGDP.csv Load the educational data from this data set: https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FEDSTATS_Country.csv Match the data based on the country shortcode. How many of the IDs match? Sort the data frame in descending order by GDP rank. What is the 13th country in the resulting data frame? Original data sources: http://data.worldbank.org/data-catalog/GDP-ranking-table http://data.worldbank.org/data-catalog/ed-stats # install.packages("data.table) library("data.table") # Download data and read FGDP data into data.table FGDP <- data.table::fread('https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FGDP.csv' , skip=4 , nrows = 190 , select = c(1, 2, 4, 5) , col.names=c("CountryCode", "Rank", "Economy", "Total") ) # Download data and read FGDP data into data.table FEDSTATS_Country <- data.table::fread('https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FEDSTATS_Country.csv' ) mergedDT <- merge(FGDP, FEDSTATS_Country, by = 'CountryCode') # How many of the IDs match? nrow(mergedDT) # Answer: # 189 # Sort the data frame in descending order by GDP rank (so United States is last). # What is the 13th country in the resulting data frame? mergedDT[order(-Rank)][13,.(Economy)] # Answer: # Economy # 1: St. Kitts and Nevis What is the average GDP ranking for the "High income: OECD" and "High income: nonOECD" group? # "High income: OECD" mergedDT[`Income Group` == "High income: OECD" , lapply(.SD, mean) , .SDcols = c("Rank") , by = "Income Group"] # Answer: # # Income Group Rank # 1: High income: OECD 32.96667 # "High income: nonOECD" mergedDT[`Income Group` == "High income: nonOECD" , lapply(.SD, mean) , .SDcols = c("Rank") , by = "Income Group"] # Answer # Income Group Rank # 1: High income: nonOECD 91.91304 Cut the GDP ranking into 5 separate quantile groups. Make a table versus Income.Group. How many countries are Lower middle income but among the 38 nations with highest GDP? # install.packages('dplyr') library('dplyr') breaks <- quantile(mergedDT[, Rank], probs = seq(0, 1, 0.2), na.rm = TRUE) mergedDT$quantileGDP <- cut(mergedDT[, Rank], breaks = breaks) mergedDT[`Income Group` == "Lower middle income", .N, by = c("Income Group", "quantileGDP")] # Answer # Income Group quantileGDP N # 1: Lower middle income (38.6,76.2] 13 # 2: Lower middle income (114,152] 9 # 3: Lower middle income (152,190] 16 # 4: Lower middle income (76.2,114] 11 # 5: Lower middle income (1,38.6] 5 The American Community Survey distributes downloadable data about United States communities. Download the 2006 microdata survey about housing for the state of Idaho using download.file() from here: https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv and load the data into R. The code book, describing the variable names is here: https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FPUMSDataDict06.pdf Apply strsplit() to split all the names of the data frame on the characters "wgtp". What is the value of the 123 element of the resulting list? library("data.table") communities <- data.table::fread("http://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv") varNamesSplit <- strsplit(names(communities), "wgtp") varNamesSplit[[123]] # Answer # "" "15" Load the Gross Domestic Product data for the 190 ranked countries in this data set: https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FGDP.csv Remove the commas from the GDP numbers in millions of dollars and average them. What is the average? Original data sources: http://data.worldbank.org/data-catalog/GDP-ranking-table # Removed the s from https to be compatible with windows computers. # Skip first 5 rows and only read in relevent columns GDPrank <- data.table::fread('http://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FGDP.csv' , skip=5 , nrows=190 , select = c(1, 2, 4, 5) , col.names=c("CountryCode", "Rank", "Country", "GDP") ) # Remove the commas using gsub # Convert to integer after removing commas. # Take mean of GDP column (I know this code may look a little confusing) GDPrank[, mean(as.integer(gsub(pattern = ',', replacement = '', x = GDP )))] # Answer: # 377652.4 In the data set from Question 2 what is a regular expression that would allow you to count the number of countries whose name begins with "United"? Assume that the variable with the country names in it is named countryNames. How many countries begin with United? # Answer: grep("^United",GDPrank[, Country]) Load the Gross Domestic Product data for the 190 ranked countries in this data set: https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FGDP.csv Load the educational data from this data set: https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FEDSTATS_Country.csv Match the data based on the country shortcode. Of the countries for which the end of the fiscal year is available, how many end in June? Original data sources: http://data.worldbank.org/data-catalog/GDP-ranking-table http://data.worldbank.org/data-catalog/ed-stats GDPrank <- data.table::fread('http://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FGDP.csv' , skip=5 , nrows=190 , select = c(1, 2, 4, 5) , col.names=c("CountryCode", "Rank", "Country", "GDP") ) eduDT <- data.table::fread('http://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FEDSTATS_Country.csv') mergedDT <- merge(GDPrank, eduDT, by = 'CountryCode') mergedDT[grepl(pattern = "Fiscal year end: June 30;", mergedDT[, `Special Notes`]), .N] # Answer: # 13 You can use the quantmod (http://www.quantmod.com/) package to get historical stock prices for publicly traded companies on the NASDAQ and NYSE. Use the following code to download data on Amazon's stock price and get the times the data was sampled. library(quantmod) amzn = getSymbols("AMZN",auto.assign=FALSE) sampleTimes = index(amzn) How many values were collected in 2012? How many values were collected on Mondays in 2012? # install.packages("quantmod") library("quantmod") amzn <- getSymbols("AMZN",auto.assign=FALSE) sampleTimes <- index(amzn) timeDT <- data.table::data.table(timeCol = sampleTimes) # How many values were collected in 2012? timeDT[(timeCol >= "2012-01-01") & (timeCol) < "2013-01-01", .N ] # Answer: # 250 # How many values were collected on Mondays in 2012? timeDT[((timeCol >= "2012-01-01") & (timeCol < "2013-01-01")) & (weekdays(timeCol) == "Monday"), .N ] # Answer: # 47 Project Review: The project was highly useful as it makes someone download files, unzip, clean, and organize a data file. Ironically I was doing something similar at work the same week making me think very highly of the course. The official assignment is located on my github. Please let me know if you have any questions or if you have any tips on how I can improve my coding! This John Hopkins specialization has even helped me with my work. The review for the next course “Exploratory Data Analysis” is online.
[ { "code": null, "e": 353, "s": 172, "text": "The third course in the data science specialization, “Getting and Cleaning Data” is an essential course. As always the code for the quizzes and assignments is located on my github." }, { "code": null, "e": 628, "s": 353, "text": "Week 1 Review: Reading Excel, XML and JSON files is essential. I am happy with the lecture on the data.table package since I use it for all my quizzes and assignments for this specialization. I wish they had more than one lecture on it though as it isn’t that easy to learn." }, { "code": null, "e": 826, "s": 628, "text": "The American Community Survey distributes downloadable data about United States communities. Download the 2006 microdata survey about housing for the state of Idaho using download.file() from here:" }, { "code": null, "e": 893, "s": 826, "text": "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv" }, { "code": null, "e": 973, "s": 893, "text": "and load the data into R. The code book, describing the variable names is here:" }, { "code": null, "e": 1047, "s": 973, "text": "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FPUMSDataDict06.pdf" }, { "code": null, "e": 1118, "s": 1047, "text": "How many housing units in this survey were worth more than $1,000,000?" }, { "code": null, "e": 1461, "s": 1118, "text": "# fread url requires curl package on mac \n# install.packages(\"curl\")\n\nlibrary(data.table)\nhousing <- data.table::fread(\"https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv\")\n\n# VAL attribute says how much property is worth, .N is the number of rows\n# VAL == 24 means more than $1,000,000\nhousing[VAL == 24, .N]\n\n# Answer: \n# 53" }, { "code": null, "e": 1610, "s": 1461, "text": "Use the data you loaded from Question 1. Consider the variable FES in the code book. Which of the \"tidy data\" principles does this variable violate?" }, { "code": null, "e": 1644, "s": 1610, "text": "Tidy data one variable per column" }, { "code": null, "e": 1715, "s": 1644, "text": "Download the Excel spreadsheet on Natural Gas Aquisition Program here:" }, { "code": null, "e": 1789, "s": 1715, "text": "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FDATA.gov_NGAP.xlsx" }, { "code": null, "e": 1873, "s": 1789, "text": "Read rows 18-23 and columns 7-15 into R and assign the result to a variable called:" }, { "code": null, "e": 1877, "s": 1873, "text": "dat" }, { "code": null, "e": 1899, "s": 1877, "text": "What is the value of:" }, { "code": null, "e": 1928, "s": 1899, "text": "sum(dat$Zip*dat$Ext,na.rm=T)" }, { "code": null, "e": 2016, "s": 1928, "text": "(original data source: http://catalog.data.gov/dataset/natural-gas-acquisition-program)" }, { "code": null, "e": 2382, "s": 2016, "text": "fileUrl <- \"http://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FDATA.gov_NGAP.xlsx\"\ndownload.file(fileUrl, destfile = paste0(getwd(), '/getdata%2Fdata%2FDATA.gov_NGAP.xlsx'), method = \"curl\")\n\ndat <- xlsx::read.xlsx(file = \"getdata%2Fdata%2FDATA.gov_NGAP.xlsx\", sheetIndex = 1, rowIndex = 18:23, colIndex = 7:15)\nsum(dat$Zip*dat$Ext,na.rm=T)\n\n# Answer:\n# 36534720" }, { "code": null, "e": 2436, "s": 2382, "text": "Read the XML data on Baltimore restaurants from here:" }, { "code": null, "e": 2507, "s": 2436, "text": "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Frestaurants.xml" }, { "code": null, "e": 2548, "s": 2507, "text": "How many restaurants have zipcode 21231?" }, { "code": null, "e": 2718, "s": 2548, "text": "Use http instead of https, which caused the message Error: XML content does not seem to be XML: 'https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Frestaurants.xml'." }, { "code": null, "e": 3121, "s": 2718, "text": "# install.packages(\"XML\")\nlibrary(\"XML\")\nfileURL<-\"https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Frestaurants.xml\"\ndoc <- XML::xmlTreeParse(sub(\"s\", \"\", fileURL), useInternal = TRUE)\nrootNode <- XML::xmlRoot(doc)\n\nzipcodes <- XML::xpathSApply(rootNode, \"//zipcode\", XML::xmlValue)\nxmlZipcodeDT <- data.table::data.table(zipcode = zipcodes)\nxmlZipcodeDT[zipcode == \"21231\", .N]\n\n# Answer: \n# 127" }, { "code": null, "e": 3319, "s": 3121, "text": "The American Community Survey distributes downloadable data about United States communities. Download the 2006 microdata survey about housing for the state of Idaho using download.file() from here:" }, { "code": null, "e": 3386, "s": 3319, "text": "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06pid.csv" }, { "code": null, "e": 3443, "s": 3386, "text": "using the fread() command load the data into an R object" }, { "code": null, "e": 3446, "s": 3443, "text": "DT" }, { "code": null, "e": 3535, "s": 3446, "text": "Which of the following is the fastest way to calculate the average value of the variable" }, { "code": null, "e": 3543, "s": 3535, "text": "pwgtp15" }, { "code": null, "e": 3592, "s": 3543, "text": "broken down by sex using the data.table package?" }, { "code": null, "e": 3746, "s": 3592, "text": "DT <- data.table::fread(\"https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06pid.csv\")\n\n# Answer (fastest):\nsystem.time(DT[,mean(pwgtp15),by=SEX])" }, { "code": null, "e": 4055, "s": 3746, "text": "Week 2 Review: More of the same. Interacting with various data sources (MySQL, HDF5 etc). I wish they would have talked about the github API more. I noticed a lot of students had a lot of trouble with that quiz question. So much so that I wrote a separate blog post on how to Access Data with the Github API." }, { "code": null, "e": 4557, "s": 4055, "text": "Register an application with the Github API here https://github.com/settings/applications.\nAccess the API to get information on your instructors repositories (hint: this is the url you want \"https://api.github.com/users/jtleek/repos\"). Use this data to find the time that the datasharing repo was created. What time was it created? This tutorial may be useful (https://github.com/hadley/httr/blob/master/demo/oauth2-github.r).\nYou may also need to run the code in the base R package and not R studio. " }, { "code": null, "e": 4663, "s": 4557, "text": "Since many people had issues with this I wrote a blog post on how to do this question: Github API using R" }, { "code": null, "e": 5612, "s": 4663, "text": "#install.packages(\"jsonlite\")\n#install.packages(\"httpuv\")\n#install.packages(\"httr\")\n\nlibrary(jsonlite)\nlibrary(httpuv)\nlibrary(httr)\n\n# Can be github, linkedin etc depending on application\noauth_endpoints(\"github\")\n\n# Change based on your appname, key, and secret \nmyapp <- oauth_app(appname = \"Youtube_Michael_Galarnyk\",\n key = \"8758a6bf9a146e1da0c1\",\n secret = \"b9504edde46b794414495bd9c33ea28cbfd87824\")\n\n# Get OAuth credentials\ngithub_token <- oauth2.0_token(oauth_endpoints(\"github\"), myapp)\n\n# Use API\ngtoken <- config(token = github_token)\nreq <- GET(\"https://api.github.com/users/jtleek/repos\", gtoken)\n\n# Take action on http error\nstop_for_status(req)\n\n# Extract content from a request\njson1 = content(req)\n\n# Convert to a data.frame\ngitDF = jsonlite::fromJSON(jsonlite::toJSON(json1))\n\n# Subset data.frame\ngitDF[gitDF$full_name == \"jtleek/datasharing\", \"created_at\"] \n\n# Answer: \n# 2013-11-07T13:25:07Z" }, { "code": null, "e": 5794, "s": 5612, "text": "The sqldf package allows for execution of SQL commands on R data frames. We will use the sqldf package to practice the queries we might send with the dbSendQuery command in RMySQL. " }, { "code": null, "e": 5875, "s": 5794, "text": "Download the American Community Survey data and load it into an R object called " }, { "code": null, "e": 5880, "s": 5875, "text": "acs " }, { "code": null, "e": 5948, "s": 5880, "text": "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06pid.csv " }, { "code": null, "e": 6066, "s": 5948, "text": "Which of the following commands will select only the data for the probability weights pwgtp1 with ages less than 50? " }, { "code": null, "e": 6362, "s": 6066, "text": "# install.packages(\"sqldf\")\nlibrary(\"sqldf\")\n\nurl <- \"https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06pid.csv\"\nf <- file.path(getwd(), \"ss06pid.csv\")\ndownload.file(url, f)\nacs <- data.table::data.table(read.csv(f))\n\n# Answer: \nquery1 <- sqldf(\"select pwgtp1 from acs where AGEP < 50\")" }, { "code": null, "e": 6460, "s": 6362, "text": "Using the same data frame you created in the previous problem, what is the equivalent function to" }, { "code": null, "e": 6477, "s": 6460, "text": "unique(acs$AGEP)" }, { "code": null, "e": 6527, "s": 6477, "text": "# Answer\n# sqldf(\"select distinct AGEP from acs\")" }, { "code": null, "e": 6615, "s": 6527, "text": "How many characters are in the 10th, 20th, 30th and 100th lines of HTML from this page:" }, { "code": null, "e": 6660, "s": 6615, "text": "http://biostat.jhsph.edu/~jleek/contact.html" }, { "code": null, "e": 6709, "s": 6660, "text": "(Hint: the nchar() function in R may be helpful)" }, { "code": null, "e": 6939, "s": 6709, "text": "connection <- url(\"http://biostat.jhsph.edu/~jleek/contact.html\")\nhtmlCode <- readLines(connection)\nclose(connection)\nc(nchar(htmlCode[10]), nchar(htmlCode[20]), nchar(htmlCode[30]), nchar(htmlCode[100]))\n\n# Answer: \n# 45 31 7 25" }, { "code": null, "e": 7034, "s": 6939, "text": "Read this data set into R and report the sum of the numbers in the fourth of the nine columns." }, { "code": null, "e": 7096, "s": 7034, "text": "https://d396qusza40orc.cloudfront.net/getdata%2Fwksst8110.for" }, { "code": null, "e": 7181, "s": 7096, "text": "Original source of the data: http://www.cpc.ncep.noaa.gov/data/indices/wksst8110.for" }, { "code": null, "e": 7222, "s": 7181, "text": "(Hint this is a fixed width file format)" }, { "code": null, "e": 7775, "s": 7222, "text": "url <- \"https://d396qusza40orc.cloudfront.net/getdata%2Fwksst8110.for\"\nlines <- readLines(url, n = 10)\nw <- c(1, 9, 5, 4, 1, 3, 5, 4, 1, 3, 5, 4, 1, 3, 5, 4, 1, 3)\ncolNames <- c(\"filler\", \"week\", \"filler\", \"sstNino12\", \"filler\", \"sstaNino12\", \n \"filler\", \"sstNino3\", \"filler\", \"sstaNino3\", \"filler\", \"sstNino34\", \"filler\", \n \"sstaNino34\", \"filler\", \"sstNino4\", \"filler\", \"sstaNino4\")\nd <- read.fwf(url, w, header = FALSE, skip = 4, col.names = colNames)\nd <- d[, grep(\"^[^filler]\", names(d))]\nsum(d[, 4])\n\n# Answer: \n# 32426.7" }, { "code": null, "e": 8026, "s": 7775, "text": "Week 3 and 4 Review: Going over dplyr after going over data.table seemed like a bit much. Week 4 went over Regular Expressions and editing text variables is really important and really should have been covered before the week 3 quiz as it was needed." }, { "code": null, "e": 8224, "s": 8026, "text": "The American Community Survey distributes downloadable data about United States communities. Download the 2006 microdata survey about housing for the state of Idaho using download.file() from here:" }, { "code": null, "e": 8291, "s": 8224, "text": "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv" }, { "code": null, "e": 8371, "s": 8291, "text": "and load the data into R. The code book, describing the variable names is here:" }, { "code": null, "e": 8445, "s": 8371, "text": "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FPUMSDataDict06.pdf" }, { "code": null, "e": 8782, "s": 8445, "text": "Create a logical vector that identifies the households on greater than 10 acres who sold more than $10,000 worth of agriculture products. Assign that logical vector to the variable agricultureLogical. Apply the which() function like this to identify the rows of the data frame where the logical vector is TRUE. which(agricultureLogical)" }, { "code": null, "e": 8823, "s": 8782, "text": "What are the first 3 values that result?" }, { "code": null, "e": 9132, "s": 8823, "text": "download.file('https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv'\n , 'ACS.csv'\n , method='curl' )\n\n# Read data into data.frame\nACS <- read.csv('ACS.csv')\n\nagricultureLogical <- ACS$ACR == 3 & ACS$AGS == 6\nhead(which(agricultureLogical), 3)\n\n# Answer: \n# 125 238 262" }, { "code": null, "e": 9211, "s": 9132, "text": "Using the jpeg package read in the following picture of your instructor into R" }, { "code": null, "e": 9268, "s": 9211, "text": "https://d396qusza40orc.cloudfront.net/getdata%2Fjeff.jpg" }, { "code": null, "e": 9359, "s": 9268, "text": "Use the parameter native=TRUE. What are the 30th and 80th quantiles of the resulting data?" }, { "code": null, "e": 9796, "s": 9359, "text": "# install.packages('jpeg')\nlibrary(jpeg)\n\n# Download the file\ndownload.file('https://d396qusza40orc.cloudfront.net/getdata%2Fjeff.jpg'\n , 'jeff.jpg'\n , mode='wb' )\n\n# Read the image\npicture <- jpeg::readJPEG('jeff.jpg'\n , native=TRUE)\n\n# Get Sample Quantiles corressponding to given prob\nquantile(picture, probs = c(0.3, 0.8) )\n\n# Answer: \n# 30% 80% \n# -15259150 -10575416 " }, { "code": null, "e": 9880, "s": 9796, "text": "Load the Gross Domestic Product data for the 190 ranked countries in this data set:" }, { "code": null, "e": 9943, "s": 9880, "text": "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FGDP.csv" }, { "code": null, "e": 9989, "s": 9943, "text": "Load the educational data from this data set:" }, { "code": null, "e": 10064, "s": 9989, "text": "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FEDSTATS_Country.csv" }, { "code": null, "e": 10245, "s": 10064, "text": "Match the data based on the country shortcode. How many of the IDs match? Sort the data frame in descending order by GDP rank. What is the 13th country in the resulting data frame?" }, { "code": null, "e": 10373, "s": 10245, "text": "Original data sources: http://data.worldbank.org/data-catalog/GDP-ranking-table http://data.worldbank.org/data-catalog/ed-stats" }, { "code": null, "e": 11420, "s": 10373, "text": "# install.packages(\"data.table)\nlibrary(\"data.table\")\n\n\n# Download data and read FGDP data into data.table\nFGDP <- data.table::fread('https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FGDP.csv'\n , skip=4\n , nrows = 190\n , select = c(1, 2, 4, 5)\n , col.names=c(\"CountryCode\", \"Rank\", \"Economy\", \"Total\")\n )\n\n# Download data and read FGDP data into data.table\nFEDSTATS_Country <- data.table::fread('https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FEDSTATS_Country.csv'\n )\n \nmergedDT <- merge(FGDP, FEDSTATS_Country, by = 'CountryCode')\n\n# How many of the IDs match?\nnrow(mergedDT)\n\n# Answer: \n# 189\n\n# Sort the data frame in descending order by GDP rank (so United States is last). \n# What is the 13th country in the resulting data frame?\nmergedDT[order(-Rank)][13,.(Economy)]\n\n# Answer: \n\n# Economy\n# 1: St. Kitts and Nevis" }, { "code": null, "e": 11514, "s": 11420, "text": "What is the average GDP ranking for the \"High income: OECD\" and \"High income: nonOECD\" group?" }, { "code": null, "e": 12001, "s": 11514, "text": "# \"High income: OECD\" \nmergedDT[`Income Group` == \"High income: OECD\"\n , lapply(.SD, mean)\n , .SDcols = c(\"Rank\")\n , by = \"Income Group\"]\n\n# Answer:\n#\n# Income Group Rank\n# 1: High income: OECD 32.96667\n\n# \"High income: nonOECD\"\nmergedDT[`Income Group` == \"High income: nonOECD\"\n , lapply(.SD, mean)\n , .SDcols = c(\"Rank\")\n , by = \"Income Group\"]\n\n# Answer\n# Income Group Rank\n# 1: High income: nonOECD 91.91304" }, { "code": null, "e": 12174, "s": 12001, "text": "Cut the GDP ranking into 5 separate quantile groups. Make a table versus Income.Group. How many countries are Lower middle income but among the 38 nations with highest GDP?" }, { "code": null, "e": 12702, "s": 12174, "text": "# install.packages('dplyr')\nlibrary('dplyr')\n\nbreaks <- quantile(mergedDT[, Rank], probs = seq(0, 1, 0.2), na.rm = TRUE)\nmergedDT$quantileGDP <- cut(mergedDT[, Rank], breaks = breaks)\nmergedDT[`Income Group` == \"Lower middle income\", .N, by = c(\"Income Group\", \"quantileGDP\")]\n\n# Answer \n# Income Group quantileGDP N\n# 1: Lower middle income (38.6,76.2] 13\n# 2: Lower middle income (114,152] 9\n# 3: Lower middle income (152,190] 16\n# 4: Lower middle income (76.2,114] 11\n# 5: Lower middle income (1,38.6] 5" }, { "code": null, "e": 12900, "s": 12702, "text": "The American Community Survey distributes downloadable data about United States communities. Download the 2006 microdata survey about housing for the state of Idaho using download.file() from here:" }, { "code": null, "e": 12967, "s": 12900, "text": "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv" }, { "code": null, "e": 13047, "s": 12967, "text": "and load the data into R. The code book, describing the variable names is here:" }, { "code": null, "e": 13121, "s": 13047, "text": "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FPUMSDataDict06.pdf" }, { "code": null, "e": 13265, "s": 13121, "text": "Apply strsplit() to split all the names of the data frame on the characters \"wgtp\". What is the value of the 123 element of the resulting list?" }, { "code": null, "e": 13487, "s": 13265, "text": "library(\"data.table\")\ncommunities <- data.table::fread(\"http://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv\")\nvarNamesSplit <- strsplit(names(communities), \"wgtp\")\nvarNamesSplit[[123]]\n\n# Answer \n# \"\" \"15\"" }, { "code": null, "e": 13571, "s": 13487, "text": "Load the Gross Domestic Product data for the 190 ranked countries in this data set:" }, { "code": null, "e": 13634, "s": 13571, "text": "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FGDP.csv" }, { "code": null, "e": 13735, "s": 13634, "text": "Remove the commas from the GDP numbers in millions of dollars and average them. What is the average?" }, { "code": null, "e": 13815, "s": 13735, "text": "Original data sources: http://data.worldbank.org/data-catalog/GDP-ranking-table" }, { "code": null, "e": 14464, "s": 13815, "text": "# Removed the s from https to be compatible with windows computers. \n# Skip first 5 rows and only read in relevent columns\nGDPrank <- data.table::fread('http://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FGDP.csv'\n , skip=5\n , nrows=190\n , select = c(1, 2, 4, 5)\n , col.names=c(\"CountryCode\", \"Rank\", \"Country\", \"GDP\")\n)\n\n# Remove the commas using gsub\n# Convert to integer after removing commas. \n# Take mean of GDP column (I know this code may look a little confusing)\nGDPrank[, mean(as.integer(gsub(pattern = ',', replacement = '', x = GDP )))]\n\n# Answer: \n# 377652.4" }, { "code": null, "e": 14727, "s": 14464, "text": "In the data set from Question 2 what is a regular expression that would allow you to count the number of countries whose name begins with \"United\"? Assume that the variable with the country names in it is named countryNames. How many countries begin with United?" }, { "code": null, "e": 14774, "s": 14727, "text": "# Answer: \ngrep(\"^United\",GDPrank[, Country])\n" }, { "code": null, "e": 14858, "s": 14774, "text": "Load the Gross Domestic Product data for the 190 ranked countries in this data set:" }, { "code": null, "e": 14921, "s": 14858, "text": "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FGDP.csv" }, { "code": null, "e": 14967, "s": 14921, "text": "Load the educational data from this data set:" }, { "code": null, "e": 15042, "s": 14967, "text": "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FEDSTATS_Country.csv" }, { "code": null, "e": 15179, "s": 15042, "text": "Match the data based on the country shortcode. Of the countries for which the end of the fiscal year is available, how many end in June?" }, { "code": null, "e": 15307, "s": 15179, "text": "Original data sources: http://data.worldbank.org/data-catalog/GDP-ranking-table http://data.worldbank.org/data-catalog/ed-stats" }, { "code": null, "e": 15885, "s": 15307, "text": "GDPrank <- data.table::fread('http://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FGDP.csv'\n , skip=5\n , nrows=190\n , select = c(1, 2, 4, 5)\n , col.names=c(\"CountryCode\", \"Rank\", \"Country\", \"GDP\")\n)\n\neduDT <- data.table::fread('http://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FEDSTATS_Country.csv')\n\nmergedDT <- merge(GDPrank, eduDT, by = 'CountryCode')\n\nmergedDT[grepl(pattern = \"Fiscal year end: June 30;\", mergedDT[, `Special Notes`]), .N]\n\n# Answer: \n# 13" }, { "code": null, "e": 16134, "s": 15885, "text": "You can use the quantmod (http://www.quantmod.com/) package to get historical stock prices for publicly traded companies on the NASDAQ and NYSE. Use the following code to download data on Amazon's stock price and get the times the data was sampled." }, { "code": null, "e": 16224, "s": 16134, "text": "library(quantmod) \namzn = getSymbols(\"AMZN\",auto.assign=FALSE) \nsampleTimes = index(amzn)" }, { "code": null, "e": 16315, "s": 16224, "text": "How many values were collected in 2012? How many values were collected on Mondays in 2012?" }, { "code": null, "e": 16793, "s": 16315, "text": "# install.packages(\"quantmod\")\nlibrary(\"quantmod\")\namzn <- getSymbols(\"AMZN\",auto.assign=FALSE)\nsampleTimes <- index(amzn) \ntimeDT <- data.table::data.table(timeCol = sampleTimes)\n\n# How many values were collected in 2012? \ntimeDT[(timeCol >= \"2012-01-01\") & (timeCol) < \"2013-01-01\", .N ]\n# Answer: \n# 250\n\n# How many values were collected on Mondays in 2012?\ntimeDT[((timeCol >= \"2012-01-01\") & (timeCol < \"2013-01-01\")) & (weekdays(timeCol) == \"Monday\"), .N ]\n# Answer:\n# 47" }, { "code": null, "e": 17070, "s": 16793, "text": "Project Review: The project was highly useful as it makes someone download files, unzip, clean, and organize a data file. Ironically I was doing something similar at work the same week making me think very highly of the course. The official assignment is located on my github." } ]
Find any pair with given GCD and LCM - GeeksforGeeks
16 Feb, 2022 Given gcd G and lcm L. The task is to print any pair which has gcd G and lcm L.Examples: Input: G = 3, L = 12 Output: 3, 12 Input: G = 1, L = 10 Output: 1, 10 A normal solution will be to perform iteration over all the factor pairs of g*l and check if any pair has gcd g and lcm as l. If they have, then the pair will be the answer.Below is the implementation of the above approach. C++ Java Python3 C# PHP Javascript // C++ program to print any pair// with a given gcd G and lcm L#include <bits/stdc++.h>using namespace std; // Function to print the pairsvoid printPair(int g, int l){ int n = g * l; // iterate over all factor pairs for (int i = 1; i * i <= n; i++) { // check if a factor if (n % i == 0) { int first = i; int second = n / i; // find gcd int gcd = __gcd(first, second); // check if gcd is same as given g // and lcm is same as lcm l if (gcd == g && l % first == 0 && l % second == 0) { cout << first << " " << second; return; } } }} // Driver Codeint main(){ int g = 3, l = 12; printPair(g, l); return 0;} // Java program to print any pair// with a given gcd G and lcm L import java.math.BigInteger; class GFG { // Function to print the pairs static void printPair(int g, int l) { int n = g * l; // iterate over all factor pairs for (int i = 1; i * i <= n; i++) { // check if a factor if (n % i == 0) { int first = i; int second = n / i; // find gcd int gcd = __gcd(first, second); // check if gcd is same as given g // and lcm is same as lcm l if (gcd == g && l % first == 0 && l % second == 0) { System.out.println(first + " " + second); return; } } } }//Function return GCD of two given number private static int __gcd(int a, int b) { // there's a better way to do this. I forget. BigInteger b1 = new BigInteger("" + a); BigInteger b2 = new BigInteger("" + b); BigInteger gcd = b1.gcd(b2); return gcd.intValue(); }// Driver function public static void main(String[] args) { int g = 3, l = 12; printPair(g, l); }}// This code is contributed by RAJPUT-JI # Python program to print any pair# with a given gcd G and lcm L # Function to print the pairsdef printPair(g, l): n = g * l; # iterate over all factor pairs for i in range(1,n+1): # check if a factor if (n % i == 0): first = i; second = n // i; # find gcd gcd = __gcd(first, second); # check if gcd is same as given g # and lcm is same as lcm l if (gcd == g and l % first == 0 and l % second == 0): print(first , " " , second); return; # Function return GCD of two given numberdef __gcd(a, b): if(b==0): return a; else: return __gcd(b, a % b); # Driver Codeg = 3;l = 12;printPair(g, l); # This code is contributed by Princi Singh // C# program to print any pair// with a given gcd G and lcm Lusing System;public class GFG { // Function to print the pairs static void printPair(int g, int l) { int n = g * l; // iterate over all factor pairs for (int i = 1; i * i <= n; i++) { // check if a factor if (n % i == 0) { int first = i; int second = n / i; // find gcd int gcd = __gcd(first, second); // check if gcd is same as given g // and lcm is same as lcm l if (gcd == g && l % first == 0 && l % second == 0) { Console.WriteLine(first + " " + second); return; } } } }//Function return GCD of two given number private static int __gcd(int a, int b) { return b == 0 ? a : __gcd(b, a % b); }// Driver function public static void Main() { int g = 3, l = 12; printPair(g, l); }} // This code is contributed by RAJPUT-JI <?php// PHP program to print any pair// with a given gcd G and lcm L // Function to print the pairsfunction printPair($g, $l){ $n = $g * $l; // iterate over all factor pairs for ($i = 1; $i * $i <= $n; $i++) { // check if a factor if ($n % $i == 0) { $first = $i; $second = (int)$n / $i; // find gcd $gcd = __gcd($first, $second); // check if gcd is same as given g // and lcm is same as lcm l if ($gcd == $g && $l % $first == 0 && $l % $second == 0) { echo $first , " " , $second; return; } } }} // Function return GCD of two given numberfunction __gcd($a, $b){ return $b == 0 ? $a : __gcd($b, $a % $b);} // Driver Code$g = 3;$l = 12;printPair($g, $l); // This code is contributed by ajit <script>// javascript program to print any pair// with a given gcd G and lcm L // Function to print the pairs function printPair(g , l) { var n = g * l; // iterate over all factor pairs for (i = 1; i * i <= n; i++) { // check if a factor if (n % i == 0) { var first = i; var second = n / i; // find gcd var gcd = __gcd(first, second); // check if gcd is same as given g // and lcm is same as lcm l if (gcd == g && l % first == 0 && l % second == 0) { document.write(first + " " + second); return; } } } } // Function return GCD of two given number function __gcd(a, b){ return b == 0 ? a : __gcd(b, a % b);} // Driver function var g = 3, l = 12; printPair(g, l); // This code is contributed by aashish1995</script> Output: 3 12 Time Complexity: O(sqrt(g*l))An efficient solution will be to observe that the lcm is always divisible by gcd, hence the answer can be obtained in O(1). One of the numbers will be the gcd G itself and the other will be the lcm L.Below is the implementation of the above approach. C++ Java Python 3 C# PHP Javascript // C++ program to print any pair// with a given gcd G and lcm L#include <iostream>using namespace std; // Function to print the pairsvoid printPair(int g, int l){ cout << g << " " << l;} // Driver Codeint main(){ int g = 3, l = 12; printPair(g, l); return 0;} // Java program to print any pair// with a given gcd G and lcm L import java.io.*; class GFG { // Function to print the pairs static void printPair(int g, int l){ System.out.print( g + " " + l);} // Driver Code public static void main (String[] args) { int g = 3, l = 12; printPair(g, l); }}// This code is contributed by inder_verma. # Python 3 program to print any pair# with a given gcd G and lcm L # Function to print the pairsdef printPair(g, l): print(g, l) # Driver Codeg = 3; l = 12;printPair(g, l); # This code is contributed# by Akanksha Rai // C# program to print any pair// with a given gcd G and lcm Lusing System; class GFG{ // Function to print the pairsstatic void printPair(int g, int l){ Console.Write( g + " " + l);} // Driver Codepublic static void Main (){ int g = 3, l = 12; printPair(g, l);}} // This code is contributed// by Subhadeep <?php// PHP program to print any pair// with a given gcd G and lcm L // Function to print the pairsfunction printPair($g, $l){ echo $g ; echo (" "); echo $l;} // Driver Code$g = 3;$l = 12;printPair($g, $l); // This code is contributed// by Shivi_Aggarwal?> <script>// javascript program to print any pair// with a given gcd G and lcm L// Function to print the pairs function printPair(g, l) { document.write(g + " " + l); } // Driver Code var g = 3, l = 12; printPair(g, l); // This code is contributed by gauravrajput1</script> Output: 3 12 Time Complexity: O(1) inderDuMCA tufan_gupta2000 Shivi_Aggarwal Rajput-Ji jit_t Akanksha_Rai princi singh aashish1995 GauravRajput1 Kirti_Mangal surinderdawra388 GCD-LCM Technical Scripter 2018 Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Program to print prime numbers from 1 to N. Program to multiply two matrices Fizz Buzz Implementation Modular multiplicative inverse Check if a number is Palindrome Complexity Analysis of Binary Search Find Union and Intersection of two unsorted arrays Count ways to reach the n'th stair Find first and last digits of a number
[ { "code": null, "e": 24692, "s": 24664, "text": "\n16 Feb, 2022" }, { "code": null, "e": 24783, "s": 24692, "text": "Given gcd G and lcm L. The task is to print any pair which has gcd G and lcm L.Examples: " }, { "code": null, "e": 24856, "s": 24783, "text": "Input: G = 3, L = 12 \nOutput: 3, 12\n\nInput: G = 1, L = 10 \nOutput: 1, 10" }, { "code": null, "e": 25083, "s": 24858, "text": "A normal solution will be to perform iteration over all the factor pairs of g*l and check if any pair has gcd g and lcm as l. If they have, then the pair will be the answer.Below is the implementation of the above approach. " }, { "code": null, "e": 25087, "s": 25083, "text": "C++" }, { "code": null, "e": 25092, "s": 25087, "text": "Java" }, { "code": null, "e": 25100, "s": 25092, "text": "Python3" }, { "code": null, "e": 25103, "s": 25100, "text": "C#" }, { "code": null, "e": 25107, "s": 25103, "text": "PHP" }, { "code": null, "e": 25118, "s": 25107, "text": "Javascript" }, { "code": "// C++ program to print any pair// with a given gcd G and lcm L#include <bits/stdc++.h>using namespace std; // Function to print the pairsvoid printPair(int g, int l){ int n = g * l; // iterate over all factor pairs for (int i = 1; i * i <= n; i++) { // check if a factor if (n % i == 0) { int first = i; int second = n / i; // find gcd int gcd = __gcd(first, second); // check if gcd is same as given g // and lcm is same as lcm l if (gcd == g && l % first == 0 && l % second == 0) { cout << first << \" \" << second; return; } } }} // Driver Codeint main(){ int g = 3, l = 12; printPair(g, l); return 0;}", "e": 25887, "s": 25118, "text": null }, { "code": "// Java program to print any pair// with a given gcd G and lcm L import java.math.BigInteger; class GFG { // Function to print the pairs static void printPair(int g, int l) { int n = g * l; // iterate over all factor pairs for (int i = 1; i * i <= n; i++) { // check if a factor if (n % i == 0) { int first = i; int second = n / i; // find gcd int gcd = __gcd(first, second); // check if gcd is same as given g // and lcm is same as lcm l if (gcd == g && l % first == 0 && l % second == 0) { System.out.println(first + \" \" + second); return; } } } }//Function return GCD of two given number private static int __gcd(int a, int b) { // there's a better way to do this. I forget. BigInteger b1 = new BigInteger(\"\" + a); BigInteger b2 = new BigInteger(\"\" + b); BigInteger gcd = b1.gcd(b2); return gcd.intValue(); }// Driver function public static void main(String[] args) { int g = 3, l = 12; printPair(g, l); }}// This code is contributed by RAJPUT-JI", "e": 27130, "s": 25887, "text": null }, { "code": "# Python program to print any pair# with a given gcd G and lcm L # Function to print the pairsdef printPair(g, l): n = g * l; # iterate over all factor pairs for i in range(1,n+1): # check if a factor if (n % i == 0): first = i; second = n // i; # find gcd gcd = __gcd(first, second); # check if gcd is same as given g # and lcm is same as lcm l if (gcd == g and l % first == 0 and l % second == 0): print(first , \" \" , second); return; # Function return GCD of two given numberdef __gcd(a, b): if(b==0): return a; else: return __gcd(b, a % b); # Driver Codeg = 3;l = 12;printPair(g, l); # This code is contributed by Princi Singh", "e": 27952, "s": 27130, "text": null }, { "code": "// C# program to print any pair// with a given gcd G and lcm Lusing System;public class GFG { // Function to print the pairs static void printPair(int g, int l) { int n = g * l; // iterate over all factor pairs for (int i = 1; i * i <= n; i++) { // check if a factor if (n % i == 0) { int first = i; int second = n / i; // find gcd int gcd = __gcd(first, second); // check if gcd is same as given g // and lcm is same as lcm l if (gcd == g && l % first == 0 && l % second == 0) { Console.WriteLine(first + \" \" + second); return; } } } }//Function return GCD of two given number private static int __gcd(int a, int b) { return b == 0 ? a : __gcd(b, a % b); }// Driver function public static void Main() { int g = 3, l = 12; printPair(g, l); }} // This code is contributed by RAJPUT-JI", "e": 29001, "s": 27952, "text": null }, { "code": "<?php// PHP program to print any pair// with a given gcd G and lcm L // Function to print the pairsfunction printPair($g, $l){ $n = $g * $l; // iterate over all factor pairs for ($i = 1; $i * $i <= $n; $i++) { // check if a factor if ($n % $i == 0) { $first = $i; $second = (int)$n / $i; // find gcd $gcd = __gcd($first, $second); // check if gcd is same as given g // and lcm is same as lcm l if ($gcd == $g && $l % $first == 0 && $l % $second == 0) { echo $first , \" \" , $second; return; } } }} // Function return GCD of two given numberfunction __gcd($a, $b){ return $b == 0 ? $a : __gcd($b, $a % $b);} // Driver Code$g = 3;$l = 12;printPair($g, $l); // This code is contributed by ajit", "e": 29899, "s": 29001, "text": null }, { "code": "<script>// javascript program to print any pair// with a given gcd G and lcm L // Function to print the pairs function printPair(g , l) { var n = g * l; // iterate over all factor pairs for (i = 1; i * i <= n; i++) { // check if a factor if (n % i == 0) { var first = i; var second = n / i; // find gcd var gcd = __gcd(first, second); // check if gcd is same as given g // and lcm is same as lcm l if (gcd == g && l % first == 0 && l % second == 0) { document.write(first + \" \" + second); return; } } } } // Function return GCD of two given number function __gcd(a, b){ return b == 0 ? a : __gcd(b, a % b);} // Driver function var g = 3, l = 12; printPair(g, l); // This code is contributed by aashish1995</script>", "e": 30874, "s": 29899, "text": null }, { "code": null, "e": 30884, "s": 30874, "text": "Output: " }, { "code": null, "e": 30889, "s": 30884, "text": "3 12" }, { "code": null, "e": 31171, "s": 30889, "text": "Time Complexity: O(sqrt(g*l))An efficient solution will be to observe that the lcm is always divisible by gcd, hence the answer can be obtained in O(1). One of the numbers will be the gcd G itself and the other will be the lcm L.Below is the implementation of the above approach. " }, { "code": null, "e": 31175, "s": 31171, "text": "C++" }, { "code": null, "e": 31180, "s": 31175, "text": "Java" }, { "code": null, "e": 31189, "s": 31180, "text": "Python 3" }, { "code": null, "e": 31192, "s": 31189, "text": "C#" }, { "code": null, "e": 31196, "s": 31192, "text": "PHP" }, { "code": null, "e": 31207, "s": 31196, "text": "Javascript" }, { "code": "// C++ program to print any pair// with a given gcd G and lcm L#include <iostream>using namespace std; // Function to print the pairsvoid printPair(int g, int l){ cout << g << \" \" << l;} // Driver Codeint main(){ int g = 3, l = 12; printPair(g, l); return 0;}", "e": 31479, "s": 31207, "text": null }, { "code": "// Java program to print any pair// with a given gcd G and lcm L import java.io.*; class GFG { // Function to print the pairs static void printPair(int g, int l){ System.out.print( g + \" \" + l);} // Driver Code public static void main (String[] args) { int g = 3, l = 12; printPair(g, l); }}// This code is contributed by inder_verma.", "e": 31835, "s": 31479, "text": null }, { "code": "# Python 3 program to print any pair# with a given gcd G and lcm L # Function to print the pairsdef printPair(g, l): print(g, l) # Driver Codeg = 3; l = 12;printPair(g, l); # This code is contributed# by Akanksha Rai", "e": 32055, "s": 31835, "text": null }, { "code": "// C# program to print any pair// with a given gcd G and lcm Lusing System; class GFG{ // Function to print the pairsstatic void printPair(int g, int l){ Console.Write( g + \" \" + l);} // Driver Codepublic static void Main (){ int g = 3, l = 12; printPair(g, l);}} // This code is contributed// by Subhadeep", "e": 32375, "s": 32055, "text": null }, { "code": "<?php// PHP program to print any pair// with a given gcd G and lcm L // Function to print the pairsfunction printPair($g, $l){ echo $g ; echo (\" \"); echo $l;} // Driver Code$g = 3;$l = 12;printPair($g, $l); // This code is contributed// by Shivi_Aggarwal?>", "e": 32641, "s": 32375, "text": null }, { "code": "<script>// javascript program to print any pair// with a given gcd G and lcm L// Function to print the pairs function printPair(g, l) { document.write(g + \" \" + l); } // Driver Code var g = 3, l = 12; printPair(g, l); // This code is contributed by gauravrajput1</script>", "e": 32947, "s": 32641, "text": null }, { "code": null, "e": 32957, "s": 32947, "text": "Output: " }, { "code": null, "e": 32962, "s": 32957, "text": "3 12" }, { "code": null, "e": 32985, "s": 32962, "text": "Time Complexity: O(1) " }, { "code": null, "e": 32996, "s": 32985, "text": "inderDuMCA" }, { "code": null, "e": 33012, "s": 32996, "text": "tufan_gupta2000" }, { "code": null, "e": 33027, "s": 33012, "text": "Shivi_Aggarwal" }, { "code": null, "e": 33037, "s": 33027, "text": "Rajput-Ji" }, { "code": null, "e": 33043, "s": 33037, "text": "jit_t" }, { "code": null, "e": 33056, "s": 33043, "text": "Akanksha_Rai" }, { "code": null, "e": 33069, "s": 33056, "text": "princi singh" }, { "code": null, "e": 33081, "s": 33069, "text": "aashish1995" }, { "code": null, "e": 33095, "s": 33081, "text": "GauravRajput1" }, { "code": null, "e": 33108, "s": 33095, "text": "Kirti_Mangal" }, { "code": null, "e": 33125, "s": 33108, "text": "surinderdawra388" }, { "code": null, "e": 33133, "s": 33125, "text": "GCD-LCM" }, { "code": null, "e": 33157, "s": 33133, "text": "Technical Scripter 2018" }, { "code": null, "e": 33170, "s": 33157, "text": "Mathematical" }, { "code": null, "e": 33183, "s": 33170, "text": "Mathematical" }, { "code": null, "e": 33281, "s": 33183, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33313, "s": 33281, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 33357, "s": 33313, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 33390, "s": 33357, "text": "Program to multiply two matrices" }, { "code": null, "e": 33415, "s": 33390, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 33446, "s": 33415, "text": "Modular multiplicative inverse" }, { "code": null, "e": 33478, "s": 33446, "text": "Check if a number is Palindrome" }, { "code": null, "e": 33515, "s": 33478, "text": "Complexity Analysis of Binary Search" }, { "code": null, "e": 33566, "s": 33515, "text": "Find Union and Intersection of two unsorted arrays" }, { "code": null, "e": 33601, "s": 33566, "text": "Count ways to reach the n'th stair" } ]
Find the element that appears once | Practice | GeeksforGeeks
Given a sorted array A[] of N positive integers having all the numbers occurring exactly twice, except for one number which will occur only once. Find the number occurring only once. Example 1: Input: N = 5 A = {1, 1, 2, 5, 5} Output: 2 Explanation: Since 2 occurs once, while other numbers occur twice, 2 is the answer. Example 2: Input: N = 7 A = {2, 2, 5, 5, 20, 30, 30} Output: 20 Explanation: Since 20 occurs once, while other numbers occur twice, 20 is the answer. Your Task: You don't need to read input or print anything. Your task is to complete the function search() which takes two arguments(array A and integer N) and returns the number occurring only once. Expected Time Complexity: O(Log(N)). Expected Auxiliary Space: O(1). Constraints 0 < N <= 10^6 0 <= A[i] <= 10^9 0 velspace011 week ago Java sol O(log N) int l=0; int r=n-1; if(n==1){ return arr[0]; } if(arr[n-1]!=arr[n-2]){ return arr[n-1]; } if(arr[0]!=arr[1]){ return arr[0]; } while(l<=r){ int mid=l+((r-l)/2); if(arr[mid]<arr[mid+1] && arr[mid]>arr[mid-1]){ return arr[mid]; } else if(mid%2==0 && arr[mid]!=arr[mid+1]){ r=mid-1; } else if(mid%2==1 && arr[mid]==arr[mid+1]){ r=mid-1; } else{ l=mid+1; } } return 0; 0 mayank180919992 weeks ago int search(int A[], int N){ //code int res=0; for(int i=0;i<N;i++){ res=res^A[i]; } return res; } -1 mayank180919992 weeks ago int search(int A[], int N){ //code unordered_map<int,int>m; for(int i=0;i<N;i++){ m[A[i]]++; } int ans; for(auto it:m){ if(it.second==1){ ans=it.first; break; } } return ans; } +1 mridulkapoor1234562 weeks ago //OPTIMAL SOLUTION TC->O(logN) SC->O(1) class Solution{ public: int search(int A[], int N){ int lo=0; int hi=N-2; while(lo<=hi){ int mid=(lo+hi)>>1; if(A[mid]==A[mid^1]) lo=mid+1; else hi=mid-1; } return A[lo]; } }; 0 gupta2411sumit3 weeks ago int search(int arr[], int N){ //code for( int i = 0 ; i<N ; i+=2) { if(arr[i]!=arr[i+1]) { return arr[i] ; } }} 0 2001amitvats4 weeks ago C++ BEST SOUTION int search(int A[], int N){ // int res = A[0]; if(A[0]!=A[1]){ return A[0]; } for(int i = 1; i<N-1; i++){ if(A[i-1]!=A[i]){ if(A[i]!=A[i+1]){ return A[i]; } } } if(A[N-2]!=A[N-1]){ return A[N-1]; }} 0 saikirannagarjuna0071 month ago SIMPLE JAVA SOLUTION USING XOR class Sol{ public static int search(int A[], int N) { // your code here int k=0; for(int i=0;i<A.length;i++){ k=k^A[i]; } return k; }} 0 codewithshoaib191 month ago int s = 0; int e = N - 1; if (N == 1) { return A[0]; } if (A[0] != A[1]) { return A[0]; } else if (A[N - 1] != A[N - 2]) { return A[N - 1]; } while (s <= e) { int mid = s + (e - s) / 2; if (A[mid] < A[mid + 1] && A[mid] > A[mid - 1]) { return A[mid]; } else if ((A[mid] == A[mid + 1] && (mid) % 2 == 0) || (A[mid] == A[mid - 1] && (mid - 1) % 2 == 0)) { s = mid + 1; } else { e = mid - 1; } } return -1; +1 bobbyprajapati961 month ago Using XOR : JAVA public static int search(int A[], int N) { int res=0; for(int i=0;i<N;i++) { res=res^A[i]; } return res; } 0 sunghunet2 months ago import collections def search(self, A, N): a=collections.Counter(A) for num , cnt in a.items(): if cnt==1: return num return A[0] 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": 421, "s": 238, "text": "Given a sorted array A[] of N positive integers having all the numbers occurring exactly twice, except for one number which will occur only once. Find the number occurring only once." }, { "code": null, "e": 432, "s": 421, "text": "Example 1:" }, { "code": null, "e": 561, "s": 432, "text": "Input:\nN = 5\nA = {1, 1, 2, 5, 5}\nOutput: 2\nExplanation: \nSince 2 occurs once, while\nother numbers occur twice, \n2 is the answer." }, { "code": null, "e": 572, "s": 561, "text": "Example 2:" }, { "code": null, "e": 712, "s": 572, "text": "Input:\nN = 7\nA = {2, 2, 5, 5, 20, 30, 30}\nOutput: 20\nExplanation:\nSince 20 occurs once, while\nother numbers occur twice, \n20 is the answer." }, { "code": null, "e": 911, "s": 712, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function search() which takes two arguments(array A and integer N) and returns the number occurring only once." }, { "code": null, "e": 980, "s": 911, "text": "Expected Time Complexity: O(Log(N)).\nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 1027, "s": 980, "text": "Constraints\n0 < N <= 10^6\n0 <= A[i] <= 10^9" }, { "code": null, "e": 1029, "s": 1027, "text": "0" }, { "code": null, "e": 1050, "s": 1029, "text": "velspace011 week ago" }, { "code": null, "e": 1721, "s": 1050, "text": "Java sol O(log N)\nint l=0;\n int r=n-1;\n if(n==1){\n return arr[0];\n }\n if(arr[n-1]!=arr[n-2]){\n return arr[n-1];\n }\n if(arr[0]!=arr[1]){\n return arr[0];\n }\n while(l<=r){\n int mid=l+((r-l)/2);\n if(arr[mid]<arr[mid+1] && arr[mid]>arr[mid-1]){\n return arr[mid];\n }\n else if(mid%2==0 && arr[mid]!=arr[mid+1]){\n r=mid-1;\n }\n else if(mid%2==1 && arr[mid]==arr[mid+1]){\n r=mid-1;\n }\n else{\n l=mid+1;\n }\n }\n return 0;" }, { "code": null, "e": 1723, "s": 1721, "text": "0" }, { "code": null, "e": 1749, "s": 1723, "text": "mayank180919992 weeks ago" }, { "code": null, "e": 1877, "s": 1749, "text": "\tint search(int A[], int N){\n\t //code\n\t int res=0;\n\t for(int i=0;i<N;i++){\n\t res=res^A[i];\n\t }\n\t return res;\n\t}" }, { "code": null, "e": 1880, "s": 1877, "text": "-1" }, { "code": null, "e": 1906, "s": 1880, "text": "mayank180919992 weeks ago" }, { "code": null, "e": 2163, "s": 1906, "text": "\tint search(int A[], int N){\n\t //code\n\t unordered_map<int,int>m;\n\t for(int i=0;i<N;i++){\n\t m[A[i]]++;\n\t }\n\t int ans;\n\t for(auto it:m){\n\t if(it.second==1){\n\t ans=it.first;\n\t break;\n\t }\n\t }\n\t return ans;\n\t}" }, { "code": null, "e": 2166, "s": 2163, "text": "+1" }, { "code": null, "e": 2196, "s": 2166, "text": "mridulkapoor1234562 weeks ago" }, { "code": null, "e": 2494, "s": 2196, "text": "//OPTIMAL SOLUTION\nTC->O(logN)\nSC->O(1)\nclass Solution{\npublic:\t\n\tint search(int A[], int N){\n\t int lo=0;\n\t int hi=N-2;\n\t while(lo<=hi){\n\t int mid=(lo+hi)>>1;\n\t if(A[mid]==A[mid^1])\n\t lo=mid+1;\n\t else \n\t hi=mid-1;\n\t }\n\t return A[lo];\n\t}\n};" }, { "code": null, "e": 2496, "s": 2494, "text": "0" }, { "code": null, "e": 2522, "s": 2496, "text": "gupta2411sumit3 weeks ago" }, { "code": null, "e": 2682, "s": 2522, "text": "int search(int arr[], int N){ //code for( int i = 0 ; i<N ; i+=2) { if(arr[i]!=arr[i+1]) { return arr[i] ; } }}" }, { "code": null, "e": 2684, "s": 2682, "text": "0" }, { "code": null, "e": 2708, "s": 2684, "text": "2001amitvats4 weeks ago" }, { "code": null, "e": 2726, "s": 2708, "text": "C++ BEST SOUTION " }, { "code": null, "e": 3013, "s": 2728, "text": "int search(int A[], int N){ // int res = A[0]; if(A[0]!=A[1]){ return A[0]; } for(int i = 1; i<N-1; i++){ if(A[i-1]!=A[i]){ if(A[i]!=A[i+1]){ return A[i]; } } } if(A[N-2]!=A[N-1]){ return A[N-1]; }}" }, { "code": null, "e": 3015, "s": 3013, "text": "0" }, { "code": null, "e": 3047, "s": 3015, "text": "saikirannagarjuna0071 month ago" }, { "code": null, "e": 3079, "s": 3047, "text": "SIMPLE JAVA SOLUTION USING XOR " }, { "code": null, "e": 3260, "s": 3079, "text": "class Sol{ public static int search(int A[], int N) { // your code here int k=0; for(int i=0;i<A.length;i++){ k=k^A[i]; } return k; }}" }, { "code": null, "e": 3264, "s": 3262, "text": "0" }, { "code": null, "e": 3292, "s": 3264, "text": "codewithshoaib191 month ago" }, { "code": null, "e": 3890, "s": 3292, "text": "int s = 0; int e = N - 1; if (N == 1) { return A[0]; } if (A[0] != A[1]) { return A[0]; } else if (A[N - 1] != A[N - 2]) { return A[N - 1]; } while (s <= e) { int mid = s + (e - s) / 2; if (A[mid] < A[mid + 1] && A[mid] > A[mid - 1]) { return A[mid]; } else if ((A[mid] == A[mid + 1] && (mid) % 2 == 0) || (A[mid] == A[mid - 1] && (mid - 1) % 2 == 0)) { s = mid + 1; } else { e = mid - 1; } } return -1;" }, { "code": null, "e": 3893, "s": 3890, "text": "+1" }, { "code": null, "e": 3921, "s": 3893, "text": "bobbyprajapati961 month ago" }, { "code": null, "e": 3939, "s": 3921, "text": "Using XOR : JAVA " }, { "code": null, "e": 4090, "s": 3939, "text": "public static int search(int A[], int N) { int res=0; for(int i=0;i<N;i++) { res=res^A[i]; } return res; }" }, { "code": null, "e": 4092, "s": 4090, "text": "0" }, { "code": null, "e": 4114, "s": 4092, "text": "sunghunet2 months ago" }, { "code": null, "e": 4276, "s": 4114, "text": "import collections\ndef search(self, A, N):\n a=collections.Counter(A)\n for num , cnt in a.items():\n if cnt==1:\n return num\n return A[0]" }, { "code": null, "e": 4422, "s": 4276, "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": 4458, "s": 4422, "text": " Login to access your submissions. " }, { "code": null, "e": 4468, "s": 4458, "text": "\nProblem\n" }, { "code": null, "e": 4478, "s": 4468, "text": "\nContest\n" }, { "code": null, "e": 4541, "s": 4478, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4689, "s": 4541, "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": 4897, "s": 4689, "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": 5003, "s": 4897, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Convert a number from base A to base B - GeeksforGeeks
12 Jan, 2022 Given two positive integers A and B and a string S of size N, denoting a number in base A, the task is to convert the given string S from base A to base B. Examples: Input: S = “10B”, A = 16, B = 10Output: 267Explanation: 10B in hexadecimal (base =16) when converted to decimal (base =10) is 267. Input: S = “10011”, A = 2, B = 8Output: 23Explanation: 10011 in binary (base =2) when converted to octal (base = 8) is 23. Approach: Number systemsis the technique to represent numbers in the computer system architecture. The computer architecture supports the following number systems: Binary Number System (Base 2): The binary number system only consists of two digits, 0s and 1s. The base of this number system is 2. Octal Number System (Base 8): The octal number system consists of 8 digits ranging from 0 to 7. Decimal Number System (Base 10): The decimal number system consists of 10 digits ranging from 0 to 9. Hexadecimal Number System (Base 16): The hexadecimal number system consists of 16 digits with 0 to 9 digits and alphabets A to F. It is also known as alphanumeric code as it consists of both number and alphabets. To convert a number from base A to base B, the idea is to first convert it to its decimal representation and then convert the decimal number to base B. Conversion from any base to Decimal: The decimal equivalent of the number “str” in base “base” is equal to 1 * str[len – 1] + base * str[len – 2] + (base)2 * str[len – 3] + ... Conversion from Decimal to any base: The decimal number “inputNum” can be converted to a number on base “base” by repeatedly dividing inputNum by base and store the remainder. Finally, reverse the obtained string to get the desired result. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to return ASCII// value of a characterint val(char c){ if (c >= '0' && c <= '9') return (int)c - '0'; else return (int)c - 'A' + 10;} // Function to convert a number// from given base to decimal numberint toDeci(string str, int base){ // Stores the length // of the string int len = str.size(); // Initialize power of base int power = 1; // Initialize result int num = 0; // Decimal equivalent is str[len-1]*1 // + str[len-2]*base + str[len-3]*(base^2) + ... for (int i = len - 1; i >= 0; i--) { // A digit in input number must // be less than number's base if (val(str[i]) >= base) { printf("Invalid Number"); return -1; } // Update num num += val(str[i]) * power; // Update power power = power * base; } return num;} // Function to return equivalent// character of a given valuechar reVal(int num){ if (num >= 0 && num <= 9) return (char)(num + '0'); else return (char)(num - 10 + 'A');} // Function to convert a given// decimal number to a given basestring fromDeci(int base, int inputNum){ // Store the result string res = ""; // Repeatedly divide inputNum // by base and take remainder while (inputNum > 0) { // Update res res += reVal(inputNum % base); // Update inputNum inputNum /= base; } // Reverse the result reverse(res.begin(), res.end()); return res;} // Function to convert a given number// from a base to another basevoid convertBase(string s, int a, int b){ // Convert the number from // base A to decimal int num = toDeci(s, a); // Convert the number from // decimal to base B string ans = fromDeci(b, num); // Print the result cout << ans;} // Driver Codeint main(){ // Given input string s = "10B"; int a = 16, b = 10; // Function Call convertBase(s, a, b); return 0;} // Java program for the above approachimport java.util.*; class GFG{ // Function to return ASCII// value of a characterstatic int val(char c){ if (c >= '0' && c <= '9') return(int)c - '0'; else return(int)c - 'A' + 10;} // Function to convert a number// from given base to decimal numberstatic int toDeci(String str, int base){ // Stores the length // of the String int len = str.length(); // Initialize power of base int power = 1; // Initialize result int num = 0; // Decimal equivalent is str[len-1]*1 // + str[len-2]*base + str[len-3]*(base^2) + ... for(int i = len - 1; i >= 0; i--) { // A digit in input number must // be less than number's base if (val(str.charAt(i)) >= base) { System.out.printf("Invalid Number"); return -1; } // Update num num += val(str.charAt(i)) * power; // Update power power = power * base; } return num;} // Function to return equivalent// character of a given valuestatic char reVal(int num){ if (num >= 0 && num <= 9) return(char)(num + '0'); else return(char)(num - 10 + 'A');} // Function to convert a given// decimal number to a given basestatic String fromDeci(int base, int inputNum){ // Store the result String res = ""; // Repeatedly divide inputNum // by base and take remainder while (inputNum > 0) { // Update res res += reVal(inputNum % base); // Update inputNum inputNum /= base; } // Reverse the result res = reverse(res); return res;} // Function to convert a given number// from a base to another basestatic void convertBase(String s, int a, int b){ // Convert the number from // base A to decimal int num = toDeci(s, a); // Convert the number from // decimal to base B String ans = fromDeci(b, num); // Print the result System.out.print(ans);} static String reverse(String input){ char[] a = input.toCharArray(); int l, r = a.length - 1; for(l = 0; l < r; l++, r--) { char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.valueOf(a);} // Driver Codepublic static void main(String[] args){ // Given input String s = "10B"; int a = 16, b = 10; // Function Call convertBase(s, a, b);}} // This code is contributed by 29AjayKumar # Python program for the above approach # Function to return ASCII# value of a characterdef val(c): if (c >= '0' and c <= '9'): return ord(c) - 48 else: return ord(c) - 65 + 10 # Function to convert a number# from given base to decimal numberdef toDeci(strr, base): # Stores the length # of the string lenn = len(strr) # Initialize power of base power = 1 # Initialize result num = 0 # Decimal equivalent is strr[len-1]*1 # + strr[len-2]*base + strr[len-3]*(base^2) + ... for i in range(lenn - 1, -1, -1): # A digit in input number must # be less than number's base if (val(strr[i]) >= base): print("Invalid Number") return -1 # Update num num += val(strr[i]) * power # Update power power = power * base return num # Function to return equivalent# character of a given valuedef reVal(num): if (num >= 0 and num <= 9): return chr(num + 48) else: return chr(num - 10 + 65) # Function to convert a given# decimal number to a given basedef fromDeci(base, inputNum): # Store the result res = "" # Repeatedly divide inputNum # by base and take remainder while (inputNum > 0): # Update res res += reVal(inputNum % base) # Update inputNum inputNum //= base # Reverse the result res = res[::-1] return res # Function to convert a given number# from a base to another basedef convertBase(s, a, b): # Convert the number from # base A to decimal num = toDeci(s, a) # Convert the number from # decimal to base B ans = fromDeci(b, num) # Print the result print(ans) # Driver Code # Given inputs = "10B"a = 16b = 10 # Function CallconvertBase(s, a, b) # This code is contributed by shubhamsingh10 // C# program for the above approachusing System; public class GFG{ // Function to return ASCII // value of a character static int val(char c) { if (c >= '0' && c <= '9') return(int)c - '0'; else return(int)c - 'A' + 10; } // Function to convert a number // from given basse to decimal number static int toDeci(string str, int basse) { // Stores the length // of the string int len = str.Length; // Initialize power of basse int power = 1; // Initialize result int num = 0; // Decimal equivalent is str[len-1]*1 // + str[len-2]*basse + str[len-3]*(basse^2) + ... for(int i = len - 1; i >= 0; i--) { // A digit in input number must // be less than number's basse if (val(str[i]) >= basse) { Console.Write("Invalid Number"); return -1; } // Update num num += val(str[i]) * power; // Update power power = power * basse; } return num; } // Function to return equivalent // character of a given value static char reVal(int num) { if (num >= 0 && num <= 9) return(char)(num + '0'); else return(char)(num - 10 + 'A'); } // Function to convert a given // decimal number to a given basse static string fromDeci(int basse, int inputNum) { // Store the result string res = ""; // Repeatedly divide inputNum // by basse and take remainder while (inputNum > 0) { // Update res res += reVal(inputNum % basse); // Update inputNum inputNum /= basse; } // Reverse the result res = reverse(res); return res; } // Function to convert a given number // from a basse to another basse static void convertbasse(string s, int a, int b) { // Convert the number from // basse A to decimal int num = toDeci(s, a); // Convert the number from // decimal to basse B string ans = fromDeci(b, num); // Print the result Console.Write(ans); } static string reverse(string input) { char[] a = input.ToCharArray(); int l, r = a.Length - 1; for(l = 0; l < r; l++, r--) { char temp = a[l]; a[l] = a[r]; a[r] = temp; } return new string(a); } // Driver Code static public void Main (){ // Given input string s = "10B"; int a = 16, b = 10; // Function Call convertbasse(s, a, b); }} // This code is contributed by shubhamsingh10 <script>// Javascript program for the above approach // Function to return ASCII// value of a characterfunction val(c){ if (c >= '0' && c <= '9') return c.charCodeAt(0) - 48; else return c.charCodeAt(0) - 65 + 10;} // Function to convert a number// from given base to decimal numberfunction toDeci(str, base){ // Stores the length // of the var var len = str.length; // Initialize power of base var power = 1; // Initialize result var num = 0; // Decimal equivalent is str[len-1]*1 // + str[len-2]*base + str[len-3]*(base^2) + ... for (var i = len - 1; i >= 0; i--) { // A digit in input number must // be less than number's base if (val(str[i]) >= base) { document.write("Invalid Number"); return -1; } // Update num num += val(str[i]) * power; // Update power power = power * base; } return num;} // Function to return equivalent// character of a given valueString.fromCharCodefunction reVal(num){ if (num >= 0 && num <= 9) return String.fromCharCode(num + 48); else return String.fromCharCode(num - 10 + 65);} // Function to convert a given// decimal number to a given basefunction fromDeci(base, inputNum){ // Store the result var res = ""; // Repeatedly divide inputNum // by base and take remainder while (inputNum > 0) { // Update res res += reVal(inputNum % base); // Update inputNum inputNum = Math.floor(inputNum/base); } // Reverse the result res = res.split("").reverse().join(""); return res;} // Function to convert a given number// from a base to another basefunction convertBase(s, a, b){ // Convert the number from // base A to decimal var num = toDeci(s, a); // Convert the number from // decimal to base B var ans = fromDeci(b, num); // Print the result document.write(ans);} // Driver Code// Given inputvar s = "10B";var a = 16var b = 10; // Function CallconvertBase(s, a, b); // This code is contributed by ShubhamSingh10</script> 267 Time Complexity: O(N)Auxiliary Space: O(N) 29AjayKumar SHUBHAMSINGH10 adnanirshad158 Kirti_Mangal base-conversion Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Program to print prime numbers from 1 to N. Fizz Buzz Implementation Program to multiply two matrices Modular multiplicative inverse Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java Interfaces in Java
[ { "code": null, "e": 24718, "s": 24690, "text": "\n12 Jan, 2022" }, { "code": null, "e": 24875, "s": 24718, "text": "Given two positive integers A and B and a string S of size N, denoting a number in base A, the task is to convert the given string S from base A to base B." }, { "code": null, "e": 24885, "s": 24875, "text": "Examples:" }, { "code": null, "e": 25016, "s": 24885, "text": "Input: S = “10B”, A = 16, B = 10Output: 267Explanation: 10B in hexadecimal (base =16) when converted to decimal (base =10) is 267." }, { "code": null, "e": 25140, "s": 25016, "text": "Input: S = “10011”, A = 2, B = 8Output: 23Explanation: 10011 in binary (base =2) when converted to octal (base = 8) is 23. " }, { "code": null, "e": 25304, "s": 25140, "text": "Approach: Number systemsis the technique to represent numbers in the computer system architecture. The computer architecture supports the following number systems:" }, { "code": null, "e": 25437, "s": 25304, "text": "Binary Number System (Base 2): The binary number system only consists of two digits, 0s and 1s. The base of this number system is 2." }, { "code": null, "e": 25533, "s": 25437, "text": "Octal Number System (Base 8): The octal number system consists of 8 digits ranging from 0 to 7." }, { "code": null, "e": 25635, "s": 25533, "text": "Decimal Number System (Base 10): The decimal number system consists of 10 digits ranging from 0 to 9." }, { "code": null, "e": 25848, "s": 25635, "text": "Hexadecimal Number System (Base 16): The hexadecimal number system consists of 16 digits with 0 to 9 digits and alphabets A to F. It is also known as alphanumeric code as it consists of both number and alphabets." }, { "code": null, "e": 26002, "s": 25848, "text": "To convert a number from base A to base B, the idea is to first convert it to its decimal representation and then convert the decimal number to base B. " }, { "code": null, "e": 26179, "s": 26002, "text": "Conversion from any base to Decimal: The decimal equivalent of the number “str” in base “base” is equal to 1 * str[len – 1] + base * str[len – 2] + (base)2 * str[len – 3] + ..." }, { "code": null, "e": 26420, "s": 26179, "text": "Conversion from Decimal to any base: The decimal number “inputNum” can be converted to a number on base “base” by repeatedly dividing inputNum by base and store the remainder. Finally, reverse the obtained string to get the desired result. " }, { "code": null, "e": 26471, "s": 26420, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26475, "s": 26471, "text": "C++" }, { "code": null, "e": 26480, "s": 26475, "text": "Java" }, { "code": null, "e": 26488, "s": 26480, "text": "Python3" }, { "code": null, "e": 26491, "s": 26488, "text": "C#" }, { "code": null, "e": 26502, "s": 26491, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to return ASCII// value of a characterint val(char c){ if (c >= '0' && c <= '9') return (int)c - '0'; else return (int)c - 'A' + 10;} // Function to convert a number// from given base to decimal numberint toDeci(string str, int base){ // Stores the length // of the string int len = str.size(); // Initialize power of base int power = 1; // Initialize result int num = 0; // Decimal equivalent is str[len-1]*1 // + str[len-2]*base + str[len-3]*(base^2) + ... for (int i = len - 1; i >= 0; i--) { // A digit in input number must // be less than number's base if (val(str[i]) >= base) { printf(\"Invalid Number\"); return -1; } // Update num num += val(str[i]) * power; // Update power power = power * base; } return num;} // Function to return equivalent// character of a given valuechar reVal(int num){ if (num >= 0 && num <= 9) return (char)(num + '0'); else return (char)(num - 10 + 'A');} // Function to convert a given// decimal number to a given basestring fromDeci(int base, int inputNum){ // Store the result string res = \"\"; // Repeatedly divide inputNum // by base and take remainder while (inputNum > 0) { // Update res res += reVal(inputNum % base); // Update inputNum inputNum /= base; } // Reverse the result reverse(res.begin(), res.end()); return res;} // Function to convert a given number// from a base to another basevoid convertBase(string s, int a, int b){ // Convert the number from // base A to decimal int num = toDeci(s, a); // Convert the number from // decimal to base B string ans = fromDeci(b, num); // Print the result cout << ans;} // Driver Codeint main(){ // Given input string s = \"10B\"; int a = 16, b = 10; // Function Call convertBase(s, a, b); return 0;}", "e": 28552, "s": 26502, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to return ASCII// value of a characterstatic int val(char c){ if (c >= '0' && c <= '9') return(int)c - '0'; else return(int)c - 'A' + 10;} // Function to convert a number// from given base to decimal numberstatic int toDeci(String str, int base){ // Stores the length // of the String int len = str.length(); // Initialize power of base int power = 1; // Initialize result int num = 0; // Decimal equivalent is str[len-1]*1 // + str[len-2]*base + str[len-3]*(base^2) + ... for(int i = len - 1; i >= 0; i--) { // A digit in input number must // be less than number's base if (val(str.charAt(i)) >= base) { System.out.printf(\"Invalid Number\"); return -1; } // Update num num += val(str.charAt(i)) * power; // Update power power = power * base; } return num;} // Function to return equivalent// character of a given valuestatic char reVal(int num){ if (num >= 0 && num <= 9) return(char)(num + '0'); else return(char)(num - 10 + 'A');} // Function to convert a given// decimal number to a given basestatic String fromDeci(int base, int inputNum){ // Store the result String res = \"\"; // Repeatedly divide inputNum // by base and take remainder while (inputNum > 0) { // Update res res += reVal(inputNum % base); // Update inputNum inputNum /= base; } // Reverse the result res = reverse(res); return res;} // Function to convert a given number// from a base to another basestatic void convertBase(String s, int a, int b){ // Convert the number from // base A to decimal int num = toDeci(s, a); // Convert the number from // decimal to base B String ans = fromDeci(b, num); // Print the result System.out.print(ans);} static String reverse(String input){ char[] a = input.toCharArray(); int l, r = a.length - 1; for(l = 0; l < r; l++, r--) { char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.valueOf(a);} // Driver Codepublic static void main(String[] args){ // Given input String s = \"10B\"; int a = 16, b = 10; // Function Call convertBase(s, a, b);}} // This code is contributed by 29AjayKumar", "e": 30985, "s": 28552, "text": null }, { "code": "# Python program for the above approach # Function to return ASCII# value of a characterdef val(c): if (c >= '0' and c <= '9'): return ord(c) - 48 else: return ord(c) - 65 + 10 # Function to convert a number# from given base to decimal numberdef toDeci(strr, base): # Stores the length # of the string lenn = len(strr) # Initialize power of base power = 1 # Initialize result num = 0 # Decimal equivalent is strr[len-1]*1 # + strr[len-2]*base + strr[len-3]*(base^2) + ... for i in range(lenn - 1, -1, -1): # A digit in input number must # be less than number's base if (val(strr[i]) >= base): print(\"Invalid Number\") return -1 # Update num num += val(strr[i]) * power # Update power power = power * base return num # Function to return equivalent# character of a given valuedef reVal(num): if (num >= 0 and num <= 9): return chr(num + 48) else: return chr(num - 10 + 65) # Function to convert a given# decimal number to a given basedef fromDeci(base, inputNum): # Store the result res = \"\" # Repeatedly divide inputNum # by base and take remainder while (inputNum > 0): # Update res res += reVal(inputNum % base) # Update inputNum inputNum //= base # Reverse the result res = res[::-1] return res # Function to convert a given number# from a base to another basedef convertBase(s, a, b): # Convert the number from # base A to decimal num = toDeci(s, a) # Convert the number from # decimal to base B ans = fromDeci(b, num) # Print the result print(ans) # Driver Code # Given inputs = \"10B\"a = 16b = 10 # Function CallconvertBase(s, a, b) # This code is contributed by shubhamsingh10", "e": 32892, "s": 30985, "text": null }, { "code": "// C# program for the above approachusing System; public class GFG{ // Function to return ASCII // value of a character static int val(char c) { if (c >= '0' && c <= '9') return(int)c - '0'; else return(int)c - 'A' + 10; } // Function to convert a number // from given basse to decimal number static int toDeci(string str, int basse) { // Stores the length // of the string int len = str.Length; // Initialize power of basse int power = 1; // Initialize result int num = 0; // Decimal equivalent is str[len-1]*1 // + str[len-2]*basse + str[len-3]*(basse^2) + ... for(int i = len - 1; i >= 0; i--) { // A digit in input number must // be less than number's basse if (val(str[i]) >= basse) { Console.Write(\"Invalid Number\"); return -1; } // Update num num += val(str[i]) * power; // Update power power = power * basse; } return num; } // Function to return equivalent // character of a given value static char reVal(int num) { if (num >= 0 && num <= 9) return(char)(num + '0'); else return(char)(num - 10 + 'A'); } // Function to convert a given // decimal number to a given basse static string fromDeci(int basse, int inputNum) { // Store the result string res = \"\"; // Repeatedly divide inputNum // by basse and take remainder while (inputNum > 0) { // Update res res += reVal(inputNum % basse); // Update inputNum inputNum /= basse; } // Reverse the result res = reverse(res); return res; } // Function to convert a given number // from a basse to another basse static void convertbasse(string s, int a, int b) { // Convert the number from // basse A to decimal int num = toDeci(s, a); // Convert the number from // decimal to basse B string ans = fromDeci(b, num); // Print the result Console.Write(ans); } static string reverse(string input) { char[] a = input.ToCharArray(); int l, r = a.Length - 1; for(l = 0; l < r; l++, r--) { char temp = a[l]; a[l] = a[r]; a[r] = temp; } return new string(a); } // Driver Code static public void Main (){ // Given input string s = \"10B\"; int a = 16, b = 10; // Function Call convertbasse(s, a, b); }} // This code is contributed by shubhamsingh10", "e": 35794, "s": 32892, "text": null }, { "code": "<script>// Javascript program for the above approach // Function to return ASCII// value of a characterfunction val(c){ if (c >= '0' && c <= '9') return c.charCodeAt(0) - 48; else return c.charCodeAt(0) - 65 + 10;} // Function to convert a number// from given base to decimal numberfunction toDeci(str, base){ // Stores the length // of the var var len = str.length; // Initialize power of base var power = 1; // Initialize result var num = 0; // Decimal equivalent is str[len-1]*1 // + str[len-2]*base + str[len-3]*(base^2) + ... for (var i = len - 1; i >= 0; i--) { // A digit in input number must // be less than number's base if (val(str[i]) >= base) { document.write(\"Invalid Number\"); return -1; } // Update num num += val(str[i]) * power; // Update power power = power * base; } return num;} // Function to return equivalent// character of a given valueString.fromCharCodefunction reVal(num){ if (num >= 0 && num <= 9) return String.fromCharCode(num + 48); else return String.fromCharCode(num - 10 + 65);} // Function to convert a given// decimal number to a given basefunction fromDeci(base, inputNum){ // Store the result var res = \"\"; // Repeatedly divide inputNum // by base and take remainder while (inputNum > 0) { // Update res res += reVal(inputNum % base); // Update inputNum inputNum = Math.floor(inputNum/base); } // Reverse the result res = res.split(\"\").reverse().join(\"\"); return res;} // Function to convert a given number// from a base to another basefunction convertBase(s, a, b){ // Convert the number from // base A to decimal var num = toDeci(s, a); // Convert the number from // decimal to base B var ans = fromDeci(b, num); // Print the result document.write(ans);} // Driver Code// Given inputvar s = \"10B\";var a = 16var b = 10; // Function CallconvertBase(s, a, b); // This code is contributed by ShubhamSingh10</script>", "e": 37913, "s": 35794, "text": null }, { "code": null, "e": 37917, "s": 37913, "text": "267" }, { "code": null, "e": 37962, "s": 37919, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 37976, "s": 37964, "text": "29AjayKumar" }, { "code": null, "e": 37991, "s": 37976, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 38006, "s": 37991, "text": "adnanirshad158" }, { "code": null, "e": 38019, "s": 38006, "text": "Kirti_Mangal" }, { "code": null, "e": 38035, "s": 38019, "text": "base-conversion" }, { "code": null, "e": 38048, "s": 38035, "text": "Mathematical" }, { "code": null, "e": 38067, "s": 38048, "text": "School Programming" }, { "code": null, "e": 38080, "s": 38067, "text": "Mathematical" }, { "code": null, "e": 38178, "s": 38080, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38210, "s": 38178, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 38254, "s": 38210, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 38279, "s": 38254, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 38312, "s": 38279, "text": "Program to multiply two matrices" }, { "code": null, "e": 38343, "s": 38312, "text": "Modular multiplicative inverse" }, { "code": null, "e": 38361, "s": 38343, "text": "Python Dictionary" }, { "code": null, "e": 38377, "s": 38361, "text": "Arrays in C/C++" }, { "code": null, "e": 38396, "s": 38377, "text": "Inheritance in C++" }, { "code": null, "e": 38421, "s": 38396, "text": "Reverse a string in Java" } ]
MySQL error 1452 - Cannot add or a child row: a foreign key constraint fails
To understand error 1452, first we need to create a table and relate that to another table with the help of a foreign key constraint. Creating the first table − mysql> CREATE table ForeignTable -> ( -> id int, -> name varchar(200), -> Fk_pk int -> ); Query OK, 0 rows affected (0.43 sec) After creating the first table successfully, we will create the second table − mysql> CREATE table primaryTable1 -> ( -> Fk_pk int, -> DeptName varchar(200), -> Primary key(Fk_pk) -> ); Query OK, 0 rows affected (0.48 sec) Now, we have created both tables. Then both the tables are related with the help of alter command as well as adding foreign key constraint. The syntax is as follows − alter table yourFirstTable add constraint anyConstraintName foreign key(column_name which is acts foreign key in second table) yourSecondTable(column_name which acts primary key in second table). Now, the above query is used to relate both the tables. This is given as follows − mysql> alter table ForeignTable add constraint constFKPK foreign key(Fk_pk) references primaryTable1(Fk_pk); Query OK, 0 rows affected (1.57 sec) Records: 0 Duplicates: 0 Warnings: 0 Now, both the tables are related. The records are inserted into the table ‘foreignTable’ as follows − mysql> INSERT into ForeignTable values(1,'John',1); This results in an error that is shown in the below output − ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`business`.`foreigntable`, CONSTRAINT `constFKPK` FOREIGN KEY (`Fk_pk`) REFERENCES `primarytable1` (`fk_pk`)) In the above output, we are getting the error ‘Cannot add or update a child row: a foreign key constraint fails’. We can remove this error by inserting the records into the table primaryTable1 as shown below − mysql> INSERT into primaryTable1 values(1,'ComputerScience'); Query OK, 1 row affected (0.14 sec) After inserting the records into the table primaryTable1, we can insert the required records into the table ForeignTable without any errors. This is shown below − mysql> INSERT into ForeignTable values(1,'John',1); Query OK, 1 row affected (0.13 sec) Now, we can display the table records of ForeignTable with the help of the select command, which is as follows − mysql> SELECT * from ForeignTable; The output of the above query is − +------+------+-------+ | id | name | Fk_pk | +------+------+-------+ | 1 | John | 1 | +------+------+-------+ 1 row in set (0.00 sec) We can also display the table records of primarytable1 with the help of the select command, which is as follows − mysql> SELECT * from primarytable1; The output of the above query is − +-------+-----------------+ | Fk_pk | DeptName | +-------+-----------------+ | 1 | ComputerScience | +-------+-----------------+ 1 row in set (0.00 sec) The error 1452 - Cannot add or update a child row: a foreign key constraint fails occurs when data record is initially inserted into the ForeignTable. Note: First, add the record into the second table i.e primarytable1 to avoid the above error.
[ { "code": null, "e": 1196, "s": 1062, "text": "To understand error 1452, first we need to create a table and relate that to another table with\nthe help of a foreign key constraint." }, { "code": null, "e": 1223, "s": 1196, "text": "Creating the first table −" }, { "code": null, "e": 1350, "s": 1223, "text": "mysql> CREATE table ForeignTable\n-> (\n-> id int,\n-> name varchar(200),\n-> Fk_pk int\n-> );\nQuery OK, 0 rows affected (0.43 sec)" }, { "code": null, "e": 1429, "s": 1350, "text": "After creating the first table successfully, we will create the second table −" }, { "code": null, "e": 1573, "s": 1429, "text": "mysql> CREATE table primaryTable1\n-> (\n-> Fk_pk int,\n-> DeptName varchar(200),\n-> Primary key(Fk_pk)\n-> );\nQuery OK, 0 rows affected (0.48 sec)" }, { "code": null, "e": 1740, "s": 1573, "text": "Now, we have created both tables. Then both the tables are related with the help of alter\ncommand as well as adding foreign key constraint. The syntax is as follows −" }, { "code": null, "e": 1936, "s": 1740, "text": "alter table yourFirstTable add constraint anyConstraintName foreign key(column_name which is\nacts foreign key in second table) yourSecondTable(column_name which acts primary key in\nsecond table)." }, { "code": null, "e": 2019, "s": 1936, "text": "Now, the above query is used to relate both the tables. This is given as follows −" }, { "code": null, "e": 2202, "s": 2019, "text": "mysql> alter table ForeignTable add constraint constFKPK foreign key(Fk_pk) references\nprimaryTable1(Fk_pk);\nQuery OK, 0 rows affected (1.57 sec)\nRecords: 0 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 2304, "s": 2202, "text": "Now, both the tables are related. The records are inserted into the table ‘foreignTable’ as\nfollows −" }, { "code": null, "e": 2357, "s": 2304, "text": "mysql> INSERT into ForeignTable values(1,'John',1);\n" }, { "code": null, "e": 2418, "s": 2357, "text": "This results in an error that is shown in the below output −" }, { "code": null, "e": 2614, "s": 2418, "text": "ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails\n(`business`.`foreigntable`, CONSTRAINT `constFKPK` FOREIGN KEY (`Fk_pk`)\nREFERENCES `primarytable1` (`fk_pk`))" }, { "code": null, "e": 2824, "s": 2614, "text": "In the above output, we are getting the error ‘Cannot add or update a child row: a foreign key\nconstraint fails’. We can remove this error by inserting the records into the table primaryTable1\nas shown below −" }, { "code": null, "e": 2922, "s": 2824, "text": "mysql> INSERT into primaryTable1 values(1,'ComputerScience');\nQuery OK, 1 row affected (0.14 sec)" }, { "code": null, "e": 3085, "s": 2922, "text": "After inserting the records into the table primaryTable1, we can insert the required records into\nthe table ForeignTable without any errors. This is shown below −" }, { "code": null, "e": 3173, "s": 3085, "text": "mysql> INSERT into ForeignTable values(1,'John',1);\nQuery OK, 1 row affected (0.13 sec)" }, { "code": null, "e": 3286, "s": 3173, "text": "Now, we can display the table records of ForeignTable with the help of the select command,\nwhich is as follows −" }, { "code": null, "e": 3322, "s": 3286, "text": "mysql> SELECT * from ForeignTable;\n" }, { "code": null, "e": 3357, "s": 3322, "text": "The output of the above query is −" }, { "code": null, "e": 3501, "s": 3357, "text": "+------+------+-------+\n| id | name | Fk_pk |\n+------+------+-------+\n| 1 | John | 1 |\n+------+------+-------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 3615, "s": 3501, "text": "We can also display the table records of primarytable1 with the help of the select command,\nwhich is as follows −" }, { "code": null, "e": 3652, "s": 3615, "text": "mysql> SELECT * from primarytable1;\n" }, { "code": null, "e": 3687, "s": 3652, "text": "The output of the above query is −" }, { "code": null, "e": 3851, "s": 3687, "text": "+-------+-----------------+\n| Fk_pk | DeptName |\n+-------+-----------------+\n| 1 | ComputerScience |\n+-------+-----------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 4002, "s": 3851, "text": "The error 1452 - Cannot add or update a child row: a foreign key constraint fails occurs when data record is initially inserted into the ForeignTable." }, { "code": null, "e": 4097, "s": 4002, "text": "Note: First, add the record into the second table i.e primarytable1 to avoid the above error.\n" } ]
Get the aggregated result and find the count of repeated values in different MongoDB documents
To get the count of repeated values in different documents, use aggregate(). Let us create a collection with documents − > db.demo452.insertOne({"StudentName":"John","StudentAge":21});{ "acknowledged" : true, "insertedId" : ObjectId("5e7b7e3371f552a0ebb0a6f3") } > db.demo452.insertOne({"StudentName":"John","StudentAge":22});{ "acknowledged" : true, "insertedId" : ObjectId("5e7b7e3671f552a0ebb0a6f4") } > db.demo452.insertOne({"StudentName":"John","StudentAge":23});{ "acknowledged" : true, "insertedId" : ObjectId("5e7b7e3971f552a0ebb0a6f5") } > db.demo452.insertOne({"StudentName":"David","StudentAge":24});{ "acknowledged" : true, "insertedId" : ObjectId("5e7b7e4371f552a0ebb0a6f6") } > db.demo452.insertOne({"StudentName":"David","StudentAge":25});{ "acknowledged" : true, "insertedId" : ObjectId("5e7b7e4571f552a0ebb0a6f7") } Display all documents from a collection with the help of find() method − > db.demo452.find(); This will produce the following output − { "_id" : ObjectId("5e7b7e3371f552a0ebb0a6f3"), "StudentName" : "John", "StudentAge" : 21 } { "_id" : ObjectId("5e7b7e3671f552a0ebb0a6f4"), "StudentName" : "John", "StudentAge" : 22 } { "_id" : ObjectId("5e7b7e3971f552a0ebb0a6f5"), "StudentName" : "John", "StudentAge" : 23 } { "_id" : ObjectId("5e7b7e4371f552a0ebb0a6f6"), "StudentName" : "David", "StudentAge" : 24} { "_id" : ObjectId("5e7b7e4571f552a0ebb0a6f7"), "StudentName" : "David", "StudentAge" : 25} Following is the query to find the count of repeated values in different MongoDB documents − > db.demo452.aggregate([ ... {$group: {_id:"$StudentName", count:{$sum:1}}}, ... {$sort: {count:-1}}, ... ... {$group: {_id:1, StudentName:{$push:{StudentName:"$_id", count:"$count"}}}}, ... {$project: { ... first : {$arrayElemAt: ["$StudentName", 0]}, ... second: {$arrayElemAt: ["$StudentName", 1]}, ... others: {$slice:["$StudentName", 2, {$size: "$StudentName"}]} ... } ... }, ... ... {$project: { ... status: [ ... "$first", ... "$second", ... { ... StudentName: "New Student Name", ... count: {$sum: "$others.count"} ... } ... ] ... } ... }, ... ... {$unwind: "$status"}, ... {$project: { _id:0, StudentName: "$status.StudentName", count: "$status.count" }} ... ]) This will produce the following output − { "StudentName" : "John", "count" : 3 } { "StudentName" : "David", "count" : 2 } { "StudentName" : "New Student Name", "count" : 0 }
[ { "code": null, "e": 1183, "s": 1062, "text": "To get the count of repeated values in different documents, use aggregate(). Let us create a collection with documents −" }, { "code": null, "e": 1925, "s": 1183, "text": "> db.demo452.insertOne({\"StudentName\":\"John\",\"StudentAge\":21});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e7b7e3371f552a0ebb0a6f3\")\n}\n> db.demo452.insertOne({\"StudentName\":\"John\",\"StudentAge\":22});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e7b7e3671f552a0ebb0a6f4\")\n}\n> db.demo452.insertOne({\"StudentName\":\"John\",\"StudentAge\":23});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e7b7e3971f552a0ebb0a6f5\")\n}\n> db.demo452.insertOne({\"StudentName\":\"David\",\"StudentAge\":24});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e7b7e4371f552a0ebb0a6f6\")\n}\n> db.demo452.insertOne({\"StudentName\":\"David\",\"StudentAge\":25});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e7b7e4571f552a0ebb0a6f7\")\n}" }, { "code": null, "e": 1998, "s": 1925, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 2019, "s": 1998, "text": "> db.demo452.find();" }, { "code": null, "e": 2060, "s": 2019, "text": "This will produce the following output −" }, { "code": null, "e": 2520, "s": 2060, "text": "{ \"_id\" : ObjectId(\"5e7b7e3371f552a0ebb0a6f3\"), \"StudentName\" : \"John\", \"StudentAge\" : 21 }\n{ \"_id\" : ObjectId(\"5e7b7e3671f552a0ebb0a6f4\"), \"StudentName\" : \"John\", \"StudentAge\" : 22 }\n{ \"_id\" : ObjectId(\"5e7b7e3971f552a0ebb0a6f5\"), \"StudentName\" : \"John\", \"StudentAge\" : 23 }\n{ \"_id\" : ObjectId(\"5e7b7e4371f552a0ebb0a6f6\"), \"StudentName\" : \"David\", \"StudentAge\" : 24}\n{ \"_id\" : ObjectId(\"5e7b7e4571f552a0ebb0a6f7\"), \"StudentName\" : \"David\", \"StudentAge\" : 25}" }, { "code": null, "e": 2613, "s": 2520, "text": "Following is the query to find the count of repeated values in different MongoDB documents −" }, { "code": null, "e": 3365, "s": 2613, "text": "> db.demo452.aggregate([\n... {$group: {_id:\"$StudentName\", count:{$sum:1}}},\n... {$sort: {count:-1}},\n...\n... {$group: {_id:1, StudentName:{$push:{StudentName:\"$_id\", count:\"$count\"}}}},\n... {$project: {\n... first : {$arrayElemAt: [\"$StudentName\", 0]},\n... second: {$arrayElemAt: [\"$StudentName\", 1]},\n... others: {$slice:[\"$StudentName\", 2, {$size: \"$StudentName\"}]}\n... }\n... },\n...\n... {$project: {\n... status: [\n... \"$first\",\n... \"$second\",\n... {\n... StudentName: \"New Student Name\",\n... count: {$sum: \"$others.count\"}\n... }\n... ]\n... }\n... },\n...\n... {$unwind: \"$status\"},\n... {$project: { _id:0, StudentName: \"$status.StudentName\", count: \"$status.count\" }}\n... ])" }, { "code": null, "e": 3406, "s": 3365, "text": "This will produce the following output −" }, { "code": null, "e": 3539, "s": 3406, "text": "{ \"StudentName\" : \"John\", \"count\" : 3 }\n{ \"StudentName\" : \"David\", \"count\" : 2 }\n{ \"StudentName\" : \"New Student Name\", \"count\" : 0 }" } ]
Fast XML parsing using Expat in Python
Python allows XML data to be read and processed through its inbuilt module called expat. It is a non-validating XML parser. it creates an XML parser object and captures the attributes of its objects into various handler functions. In the below example we will see how the various handler functions can help us read the XML file as well as give the attribute values as the output data. This generated data can be used for the processing. import xml.parsers.expat # Capture the first element def first_element(tag, attrs): print ('first element:', tag, attrs) # Capture the last element def last_element(tag): print ('last element:', tag) # Capture the character Data def character_value(value): print ('Character value:', repr(value)) parser_expat = xml.parsers.expat.ParserCreate() parser_expat.StartElementHandler = first_element parser_expat.EndElementHandler = last_element parser_expat.CharacterDataHandler = character_value parser_expat.Parse(""" <?xml version="1.0"?> <parent student_rollno="15"> <child1 Student_name="Krishna"> Strive for progress, not perfection</child1> <child2 student_name="vamsi"> There are no shortcuts to any place worth going</child2> </parent>""", 1) Running the above code gives us the following result − first element: parent {'student_rollno': '15'} Character value: '\n' first element: child1 {'Student_name': 'Krishna'} Character value: 'Strive for progress, not perfection' last element: child1 Character value: '\n' first element: child2 {'student_name': 'vamsi'} Character value: ' There are no shortcuts to any place worth going' last element: child2 Character value: '\n' last element: parent
[ { "code": null, "e": 1499, "s": 1062, "text": "Python allows XML data to be read and processed through its inbuilt module called expat. It is a non-validating XML parser. it creates an XML parser object and captures the attributes of its objects into various handler functions. In the below example we will see how the various handler functions can help us read the XML file as well as give the attribute values as the output data. This generated data can be used for the processing." }, { "code": null, "e": 2255, "s": 1499, "text": "import xml.parsers.expat\n# Capture the first element\ndef first_element(tag, attrs):\n print ('first element:', tag, attrs)\n# Capture the last element\ndef last_element(tag):\n print ('last element:', tag)\n# Capture the character Data\ndef character_value(value):\n print ('Character value:', repr(value))\nparser_expat = xml.parsers.expat.ParserCreate()\nparser_expat.StartElementHandler = first_element\nparser_expat.EndElementHandler = last_element\nparser_expat.CharacterDataHandler = character_value\nparser_expat.Parse(\"\"\" <?xml version=\"1.0\"?>\n<parent student_rollno=\"15\">\n<child1 Student_name=\"Krishna\"> Strive for progress, not perfection</child1>\n<child2 student_name=\"vamsi\"> There are no shortcuts to any place worth going</child2>\n</parent>\"\"\", 1)" }, { "code": null, "e": 2310, "s": 2255, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2707, "s": 2310, "text": "first element: parent {'student_rollno': '15'}\nCharacter value: '\\n'\nfirst element: child1 {'Student_name': 'Krishna'}\nCharacter value: 'Strive for progress, not perfection'\nlast element: child1\nCharacter value: '\\n'\nfirst element: child2 {'student_name': 'vamsi'}\nCharacter value: ' There are no shortcuts to any place worth going'\nlast element: child2\nCharacter value: '\\n'\nlast element: parent" } ]
How Deep Neural Networks Look for Features in Images? With Keras and Google Colab | by Saptashwa Bhattacharyya | Towards Data Science
When I first started taking steps from learning standard machine algorithms like Logistic Regression, Support Vector Machine towards deep learning and neural network, I used to often fascinate that the deep layers in the networks are kind of ‘black boxes’. Later on this false understanding went away and, once I learnt to plot the intermediate convolutional layer output, it almost became an obsession to randomly select images and see what’s happening in each layer. Today, I would like to give a step by step description on how you can extract features from hidden conv. layers using Keras (running on top of TensorFlow). For simplicity, I took the dogs vs. cats data-set, and I will build a VGG161 like model so, the problem essentially boils down to a binary classification problem. What you can expect to learn from this post — Learn to use Google Colab to deploy your deep learning models. I found this is extremely useful as you can use cloud GPU for free, with 12.72 GB RAM and 350 GB disk space. Extract hidden conv. layer outputs using Keras. Two different ways to tile these outputs to form a compact image. So without delay let’s get started! If you don’t have a GPU and large CPU resources, Google Colab can come to your rescue to train moderate to heavy deep networks. Currently Colab offers 12 GB Nvidia Tesla GPU and it can be used up to 12 hours continuously. Provided you are accustomed working with Jupyter environment, you can easily settle in with Google Colab. Check detailed tutorials on using Colab2 provided by Google, here, I describe the two steps that are necessary to go through the tutorial. Using GPU: To access the GPU you need to change the run-time type. The pictures below shows the Colab environment. Using GPU: To access the GPU you need to change the run-time type. The pictures below shows the Colab environment. 2. Mount Your Drive: You need to mount your google drive to access files from the drive. For that you need to run the commands below — from google.colab import drivedrive.mount('/content/gdrive') The URL will provide you the one time authorization code, copy and paste it in the box below and press enter. You will get the confirmation — Mounted at /content/gdrive. After this, you are ready to use files and folders directly from your drive. Now let’s dive into the tutorial. Let’s build our model using Keras Sequential — To finish training faster, I used a model which is more like a mini-version of VGG16 architecture (2 layers of conv. layers followed by a pooling layer), with input size set to (160, 160). Let’s check the model summary — I guess most of you know to count parameters. But let’s just go through first few layers to review this. For the first layer, input image size is (160, 160) with 3 channels (n_c). The filter size (f) is (3, 3) and number of filters (n_f) are 16. So the total number of weights (f× f × n_f × n_c) = 432. Number of biases = n_f = 16. Total number of parameters = 448. Similarly for the second layer we have — weights = (3× 3 × 16 × 16) = 2304, biases = 16, so, total number of parameters = 2320 and so on... Data Pre-Processing: Before using Keras ImageDataGenerator class, we have to remember that here we will use files and folders directly from google drive. So we have to be precise about the file paths. Let’s see the modified code blocks — I used only 2800 images for training and 600 images for the validation to save time. Next steps inevitably are compiling and fitting the model — I have used 100 epochs and with the parameter settings, accuracy of 89% and 83% on training and validation data were achieved. In Google Colab with GPU it takes around 75–80 minutes to train this model. I tried predicting class labels on some random images downloaded from internet — I see 3 images including one angry cat were predicted as dogs. Rather than focusing on increasing accuracy, our focus is to check the outputs from hidden conv. layers and see how different filters in a layer are trying to find different features in an image. Let’s do that I will describe two methods to visualize the conv. layer outputs, they are rather similar but, process of tiling the images are different. You can choose based on your preference... 1st Method: Stack the Layer Outputs Horizontally Let’s check the layer names: from keras.preprocessing.image import load img_to_array, load_imgimport random layer_names_list = [layr.name for layr in model.layers]print ("layer names list: ", layer_names_list) >>> layer names list: ['conv2d_1', 'block0_conv2', 'block0_pool1', 'block1_conv1', 'block1_conv2', 'block1_pool1', 'block2_conv1', 'block2_conv2', 'block2_pool1', 'block3_conv1', 'block3_pool', 'flatten_1', 'dense_2', 'Dropout_1', 'dense_3'] I will select few conv. layers from which I would like to see the output, selected_layers = [‘block0_conv2’, ‘block2_conv1’, ‘block2_conv2’]matched_indices = [i for i, item in enumerate(layer_names_list) if item in selected_layers]print (matched_indices)>>> [1, 6, 7] To get outputs from the selected layers, we will use Keras layer.output method. Then append the outputs on a list, Let’s see: selected_layers_outputs = []for lr in range(len(matched_indices)): outputs = model.layers[matched_indices[lr]].output #output from selected layers selected_layers_outputs.append(outputs) Next step is important, as we will instantiate a new model, which will take a random image (of either cat or dog) as input and the outputs will be the selected conv. layer outputs. Check the Keras Model API for more details. visual_model = keras.models.Model(inputs = model.input, outputs = selected_layers_outputs) If you remember the input of our original model (VGG like), it was batches of images with input size (None, 160, 160, 3). We will select the same input size dimension but as we just want to process only 1 randomly selected image at a time, our batch size will be 1. First, let’s select an image randomly, we will do that using random.choice, which returns a random element from a non-empty sequence. dog_files = [os.path.join(dog_train_dir, f) for f in dog_train_images]cat_files = [os.path.join(cat_train_dir, g) for g in cat_train_images]random_cat_dog = random.choice(dog_files + cat_files)print (“random file name: “, random_cat_dog) In the next step, we want to resize this image and convert this image to a numpy array and finally, reshape it to a consistent format (batch size, height, width, channel). Let’s do that using Keras load_img, Keras img_to_array and numpy modules. rand_img = load_img(random_cat_dog, target_size=(160, 160))rand_img_arr = img_to_array(rand_img)print ("shape of selected image :", rand_img_arr.shape)x_in = np.reshape(rand_img_arr, (1, 160, 160, 3)) # batch size 1>>> shape of selected image : (160, 160, 3) Once we have processed the image in a format that is suitable as an input for our model, let’s generate predictions from the model for the selected layers. selected_feature_maps = visual_model.predict(x_in) Now comes the part of arranging these predictions in such way, so that it is possible to visualize the effect of each filter on those selected layers. This part is little tricky and we need to unleash our playfulness with numpy. Let me give a brief outline of how we can proceed. If you look back to the model.summary() then you will get the overview of the shapes and the last element of the tuple is the number of filters and, first/second element of the tuple is the height/width of the image. First we create grids of zeroes with shape (height, height*number of filters), so that later we can stack the outputs horizontally. Next, we loop over the number of filters. We need to remember that the batch size is 1 so, to select a particular filter output from a selected layer we do this (check the detailed code later) — for i in range(n_filters): y = feat_map [0, :, :, i] Then we standardize and post process the output of the filters to make it visually recognizable. Finally, we stack the filter output in the display grid that we created before (grids of zeros). Using matplotlib imshow, we can visualize the effect of each filters on a particular layer where the images will be stacked side by side. As you can see in the image below. I found a fantastic detailed answer on how imshow method works; please check it to understand better on what happened on the last line of the second for loop in the code below. for lr_name, feat_map in zip(selected_layers, selected_feature_maps): n_filters = feat_map.shape[-1] n_size = feat_map.shape[1] display_grid = np.zeros((n_size, n_size * n_filters)) for i in range(n_filters): y = feat_map[0, :, :, i] y = y - y.mean() y = y/y.std() y = y*64 y = y + 128 y = np.clip(y, 0, 255).astype('uint8')# value only between 0, 255. display_grid[:, i * n_size : (i+1) * n_size] = y scale = 20./n_filters plt.figure(figsize=(scale * n_filters * 1.4, scale * 2)) plt.title(lr_name, fontsize=16) plt.grid(False)plt.imshow(display_grid, aspect='auto', cmap='plasma')plt.savefig('/content/gdrive/My Drive/Colab Notebooks/cat_dog_visual_%s.png'%(lr_name), dpi=300) Here, we could see that the filters in the 2nd layer (block0_conv2) of the model where it sees the complete input (160, 160), mostly look for some basic edges. But, as we go deeper the input size reduces, for example in block2_conv2 layer the shape of the image is (40, 40) and, here the visual information are almost unrecognizable but features related to the class of the image are caught by the filters. Also you see the number of sparse filters increasing as we go deep in the network because, with increasing number of filters in each layer, the pattern encoded by the previous layer filters are not seen in the current layer. That’s why almost always you will see the in the first layer all filters are activated but from the second layer on sparsity increases. I found the previous method of staking outputs horizontally reasonable but not visually compelling so, I give the second method which I found in Francois Chollet’s book Deep Learning with Python. This is very similar to the first one but instead of stacking output from all filters horizontally, we put them in an array. So the main concept here is to determine the shape of the array and stack the filter outputs as previously. 2nd Method: Here we take one benefit from the number of filters used in each layer and that is, they are all multiples of 16. So number of columns of each grid will be 16 and, the number of rows will depend on the number of filters used in the selected Convolutional layer. So, number of columns (ncols) will be given by = number of filters/16. Here, our grid of zeros will have shape (height*ncols, 16 * width). Consider that the height and width of the images are same in every layer. images_per_row = 16for lr_name1, feat_map1 in zip(selected_layers1, selected_feature_maps1): n_filters1 = feat_map1.shape[-1] n_size1 = feat_map1.shape[1] n_cols = n_filters1 // images_per_row display_grid1 = np.zeros((n_size1 * n_cols, images_per_row * n_size1)) for col in range(n_cols): for row in range(images_per_row): chan_img = feat_map1[0, :, :, col*images_per_row + row] chan_img = chan_img — chan_img.mean() chan_img = chan_img / chan_img.std() chan_img = chan_img * 64 chan_img = chan_img + 128 chan_img = np.clip(chan_img, 0, 255).astype(‘uint8’) display_grid1[col * n_size1 : (col+1) * n_size1, row * n_size1 : (row+1) * n_size1] = chan_img scale1 = 1./n_size1 plt.figure(figsize=(scale1 * display_grid1.shape[1]*1.4, scale1 * display_grid1.shape[0] * 2.)) plt.title(lr_name1) plt.grid(False) plt.imshow(display_grid1, aspect=’auto’, cmap=’viridis’) plt.savefig(‘/content/gdrive/My Drive/Colab Notebooks/cat_dog_visual2_%s.png’%(lr_name1), dpi=300) With this representation you can clearly see how the filters in the deeper layers in our model concentrate on specific features of the cat, like the shape of the eyes, nose, eyebrow region, etc. In this post, we have seen how one can use Google Colab to build and train your fairly large deep learning network. Our main focus was to visualize the journey of an image through several layers of a deep neural network and, we have learned two ways to do that. Also, rather than thinking of the deep layers as black boxes, visualization should help us to see through and understand them much better. [1] Very Deep Convolutional Networks for Large-Scale Image Recognition; K. Simonyan, A. Zisserman. [2] Colab Tutorials by Google. [3] Tensorflow Specialization Course: Deep Learning.ai [4] Deep Learning with Python; Francois Chollet. pages: 160–177. [5] Resource for Dealing with Files in Colab: Neptune.ai [6] Link to the Notebook Used for this Post!
[ { "code": null, "e": 959, "s": 171, "text": "When I first started taking steps from learning standard machine algorithms like Logistic Regression, Support Vector Machine towards deep learning and neural network, I used to often fascinate that the deep layers in the networks are kind of ‘black boxes’. Later on this false understanding went away and, once I learnt to plot the intermediate convolutional layer output, it almost became an obsession to randomly select images and see what’s happening in each layer. Today, I would like to give a step by step description on how you can extract features from hidden conv. layers using Keras (running on top of TensorFlow). For simplicity, I took the dogs vs. cats data-set, and I will build a VGG161 like model so, the problem essentially boils down to a binary classification problem." }, { "code": null, "e": 1005, "s": 959, "text": "What you can expect to learn from this post —" }, { "code": null, "e": 1177, "s": 1005, "text": "Learn to use Google Colab to deploy your deep learning models. I found this is extremely useful as you can use cloud GPU for free, with 12.72 GB RAM and 350 GB disk space." }, { "code": null, "e": 1225, "s": 1177, "text": "Extract hidden conv. layer outputs using Keras." }, { "code": null, "e": 1291, "s": 1225, "text": "Two different ways to tile these outputs to form a compact image." }, { "code": null, "e": 1327, "s": 1291, "text": "So without delay let’s get started!" }, { "code": null, "e": 1794, "s": 1327, "text": "If you don’t have a GPU and large CPU resources, Google Colab can come to your rescue to train moderate to heavy deep networks. Currently Colab offers 12 GB Nvidia Tesla GPU and it can be used up to 12 hours continuously. Provided you are accustomed working with Jupyter environment, you can easily settle in with Google Colab. Check detailed tutorials on using Colab2 provided by Google, here, I describe the two steps that are necessary to go through the tutorial." }, { "code": null, "e": 1909, "s": 1794, "text": "Using GPU: To access the GPU you need to change the run-time type. The pictures below shows the Colab environment." }, { "code": null, "e": 2024, "s": 1909, "text": "Using GPU: To access the GPU you need to change the run-time type. The pictures below shows the Colab environment." }, { "code": null, "e": 2159, "s": 2024, "text": "2. Mount Your Drive: You need to mount your google drive to access files from the drive. For that you need to run the commands below —" }, { "code": null, "e": 2220, "s": 2159, "text": "from google.colab import drivedrive.mount('/content/gdrive')" }, { "code": null, "e": 2362, "s": 2220, "text": "The URL will provide you the one time authorization code, copy and paste it in the box below and press enter. You will get the confirmation —" }, { "code": null, "e": 2391, "s": 2362, "text": "Mounted at /content/gdrive. " }, { "code": null, "e": 2502, "s": 2391, "text": "After this, you are ready to use files and folders directly from your drive. Now let’s dive into the tutorial." }, { "code": null, "e": 2549, "s": 2502, "text": "Let’s build our model using Keras Sequential —" }, { "code": null, "e": 2770, "s": 2549, "text": "To finish training faster, I used a model which is more like a mini-version of VGG16 architecture (2 layers of conv. layers followed by a pooling layer), with input size set to (160, 160). Let’s check the model summary —" }, { "code": null, "e": 3276, "s": 2770, "text": "I guess most of you know to count parameters. But let’s just go through first few layers to review this. For the first layer, input image size is (160, 160) with 3 channels (n_c). The filter size (f) is (3, 3) and number of filters (n_f) are 16. So the total number of weights (f× f × n_f × n_c) = 432. Number of biases = n_f = 16. Total number of parameters = 448. Similarly for the second layer we have — weights = (3× 3 × 16 × 16) = 2304, biases = 16, so, total number of parameters = 2320 and so on..." }, { "code": null, "e": 3514, "s": 3276, "text": "Data Pre-Processing: Before using Keras ImageDataGenerator class, we have to remember that here we will use files and folders directly from google drive. So we have to be precise about the file paths. Let’s see the modified code blocks —" }, { "code": null, "e": 3659, "s": 3514, "text": "I used only 2800 images for training and 600 images for the validation to save time. Next steps inevitably are compiling and fitting the model —" }, { "code": null, "e": 3862, "s": 3659, "text": "I have used 100 epochs and with the parameter settings, accuracy of 89% and 83% on training and validation data were achieved. In Google Colab with GPU it takes around 75–80 minutes to train this model." }, { "code": null, "e": 3943, "s": 3862, "text": "I tried predicting class labels on some random images downloaded from internet —" }, { "code": null, "e": 4216, "s": 3943, "text": "I see 3 images including one angry cat were predicted as dogs. Rather than focusing on increasing accuracy, our focus is to check the outputs from hidden conv. layers and see how different filters in a layer are trying to find different features in an image. Let’s do that" }, { "code": null, "e": 4398, "s": 4216, "text": "I will describe two methods to visualize the conv. layer outputs, they are rather similar but, process of tiling the images are different. You can choose based on your preference..." }, { "code": null, "e": 4447, "s": 4398, "text": "1st Method: Stack the Layer Outputs Horizontally" }, { "code": null, "e": 4476, "s": 4447, "text": "Let’s check the layer names:" }, { "code": null, "e": 4900, "s": 4476, "text": "from keras.preprocessing.image import load img_to_array, load_imgimport random layer_names_list = [layr.name for layr in model.layers]print (\"layer names list: \", layer_names_list) >>> layer names list: ['conv2d_1', 'block0_conv2', 'block0_pool1', 'block1_conv1', 'block1_conv2', 'block1_pool1', 'block2_conv1', 'block2_conv2', 'block2_pool1', 'block3_conv1', 'block3_pool', 'flatten_1', 'dense_2', 'Dropout_1', 'dense_3']" }, { "code": null, "e": 4974, "s": 4900, "text": "I will select few conv. layers from which I would like to see the output," }, { "code": null, "e": 5168, "s": 4974, "text": "selected_layers = [‘block0_conv2’, ‘block2_conv1’, ‘block2_conv2’]matched_indices = [i for i, item in enumerate(layer_names_list) if item in selected_layers]print (matched_indices)>>> [1, 6, 7]" }, { "code": null, "e": 5294, "s": 5168, "text": "To get outputs from the selected layers, we will use Keras layer.output method. Then append the outputs on a list, Let’s see:" }, { "code": null, "e": 5488, "s": 5294, "text": "selected_layers_outputs = []for lr in range(len(matched_indices)): outputs = model.layers[matched_indices[lr]].output #output from selected layers selected_layers_outputs.append(outputs)" }, { "code": null, "e": 5713, "s": 5488, "text": "Next step is important, as we will instantiate a new model, which will take a random image (of either cat or dog) as input and the outputs will be the selected conv. layer outputs. Check the Keras Model API for more details." }, { "code": null, "e": 5804, "s": 5713, "text": "visual_model = keras.models.Model(inputs = model.input, outputs = selected_layers_outputs)" }, { "code": null, "e": 6204, "s": 5804, "text": "If you remember the input of our original model (VGG like), it was batches of images with input size (None, 160, 160, 3). We will select the same input size dimension but as we just want to process only 1 randomly selected image at a time, our batch size will be 1. First, let’s select an image randomly, we will do that using random.choice, which returns a random element from a non-empty sequence." }, { "code": null, "e": 6442, "s": 6204, "text": "dog_files = [os.path.join(dog_train_dir, f) for f in dog_train_images]cat_files = [os.path.join(cat_train_dir, g) for g in cat_train_images]random_cat_dog = random.choice(dog_files + cat_files)print (“random file name: “, random_cat_dog)" }, { "code": null, "e": 6688, "s": 6442, "text": "In the next step, we want to resize this image and convert this image to a numpy array and finally, reshape it to a consistent format (batch size, height, width, channel). Let’s do that using Keras load_img, Keras img_to_array and numpy modules." }, { "code": null, "e": 6947, "s": 6688, "text": "rand_img = load_img(random_cat_dog, target_size=(160, 160))rand_img_arr = img_to_array(rand_img)print (\"shape of selected image :\", rand_img_arr.shape)x_in = np.reshape(rand_img_arr, (1, 160, 160, 3)) # batch size 1>>> shape of selected image : (160, 160, 3)" }, { "code": null, "e": 7103, "s": 6947, "text": "Once we have processed the image in a format that is suitable as an input for our model, let’s generate predictions from the model for the selected layers." }, { "code": null, "e": 7154, "s": 7103, "text": "selected_feature_maps = visual_model.predict(x_in)" }, { "code": null, "e": 7978, "s": 7154, "text": "Now comes the part of arranging these predictions in such way, so that it is possible to visualize the effect of each filter on those selected layers. This part is little tricky and we need to unleash our playfulness with numpy. Let me give a brief outline of how we can proceed. If you look back to the model.summary() then you will get the overview of the shapes and the last element of the tuple is the number of filters and, first/second element of the tuple is the height/width of the image. First we create grids of zeroes with shape (height, height*number of filters), so that later we can stack the outputs horizontally. Next, we loop over the number of filters. We need to remember that the batch size is 1 so, to select a particular filter output from a selected layer we do this (check the detailed code later) —" }, { "code": null, "e": 8032, "s": 7978, "text": "for i in range(n_filters): y = feat_map [0, :, :, i]" }, { "code": null, "e": 8576, "s": 8032, "text": "Then we standardize and post process the output of the filters to make it visually recognizable. Finally, we stack the filter output in the display grid that we created before (grids of zeros). Using matplotlib imshow, we can visualize the effect of each filters on a particular layer where the images will be stacked side by side. As you can see in the image below. I found a fantastic detailed answer on how imshow method works; please check it to understand better on what happened on the last line of the second for loop in the code below." }, { "code": null, "e": 9285, "s": 8576, "text": "for lr_name, feat_map in zip(selected_layers, selected_feature_maps): n_filters = feat_map.shape[-1] n_size = feat_map.shape[1] display_grid = np.zeros((n_size, n_size * n_filters)) for i in range(n_filters): y = feat_map[0, :, :, i] y = y - y.mean() y = y/y.std() y = y*64 y = y + 128 y = np.clip(y, 0, 255).astype('uint8')# value only between 0, 255. display_grid[:, i * n_size : (i+1) * n_size] = y scale = 20./n_filters plt.figure(figsize=(scale * n_filters * 1.4, scale * 2)) plt.title(lr_name, fontsize=16) plt.grid(False)plt.imshow(display_grid, aspect='auto', cmap='plasma')plt.savefig('/content/gdrive/My Drive/Colab Notebooks/cat_dog_visual_%s.png'%(lr_name), dpi=300)" }, { "code": null, "e": 10053, "s": 9285, "text": "Here, we could see that the filters in the 2nd layer (block0_conv2) of the model where it sees the complete input (160, 160), mostly look for some basic edges. But, as we go deeper the input size reduces, for example in block2_conv2 layer the shape of the image is (40, 40) and, here the visual information are almost unrecognizable but features related to the class of the image are caught by the filters. Also you see the number of sparse filters increasing as we go deep in the network because, with increasing number of filters in each layer, the pattern encoded by the previous layer filters are not seen in the current layer. That’s why almost always you will see the in the first layer all filters are activated but from the second layer on sparsity increases." }, { "code": null, "e": 10482, "s": 10053, "text": "I found the previous method of staking outputs horizontally reasonable but not visually compelling so, I give the second method which I found in Francois Chollet’s book Deep Learning with Python. This is very similar to the first one but instead of stacking output from all filters horizontally, we put them in an array. So the main concept here is to determine the shape of the array and stack the filter outputs as previously." }, { "code": null, "e": 10969, "s": 10482, "text": "2nd Method: Here we take one benefit from the number of filters used in each layer and that is, they are all multiples of 16. So number of columns of each grid will be 16 and, the number of rows will depend on the number of filters used in the selected Convolutional layer. So, number of columns (ncols) will be given by = number of filters/16. Here, our grid of zeros will have shape (height*ncols, 16 * width). Consider that the height and width of the images are same in every layer." }, { "code": null, "e": 11980, "s": 10969, "text": "images_per_row = 16for lr_name1, feat_map1 in zip(selected_layers1, selected_feature_maps1): n_filters1 = feat_map1.shape[-1] n_size1 = feat_map1.shape[1] n_cols = n_filters1 // images_per_row display_grid1 = np.zeros((n_size1 * n_cols, images_per_row * n_size1)) for col in range(n_cols): for row in range(images_per_row): chan_img = feat_map1[0, :, :, col*images_per_row + row] chan_img = chan_img — chan_img.mean() chan_img = chan_img / chan_img.std() chan_img = chan_img * 64 chan_img = chan_img + 128 chan_img = np.clip(chan_img, 0, 255).astype(‘uint8’) display_grid1[col * n_size1 : (col+1) * n_size1, row * n_size1 : (row+1) * n_size1] = chan_img scale1 = 1./n_size1 plt.figure(figsize=(scale1 * display_grid1.shape[1]*1.4, scale1 * display_grid1.shape[0] * 2.)) plt.title(lr_name1) plt.grid(False) plt.imshow(display_grid1, aspect=’auto’, cmap=’viridis’) plt.savefig(‘/content/gdrive/My Drive/Colab Notebooks/cat_dog_visual2_%s.png’%(lr_name1), dpi=300)" }, { "code": null, "e": 12175, "s": 11980, "text": "With this representation you can clearly see how the filters in the deeper layers in our model concentrate on specific features of the cat, like the shape of the eyes, nose, eyebrow region, etc." }, { "code": null, "e": 12576, "s": 12175, "text": "In this post, we have seen how one can use Google Colab to build and train your fairly large deep learning network. Our main focus was to visualize the journey of an image through several layers of a deep neural network and, we have learned two ways to do that. Also, rather than thinking of the deep layers as black boxes, visualization should help us to see through and understand them much better." }, { "code": null, "e": 12675, "s": 12576, "text": "[1] Very Deep Convolutional Networks for Large-Scale Image Recognition; K. Simonyan, A. Zisserman." }, { "code": null, "e": 12706, "s": 12675, "text": "[2] Colab Tutorials by Google." }, { "code": null, "e": 12761, "s": 12706, "text": "[3] Tensorflow Specialization Course: Deep Learning.ai" }, { "code": null, "e": 12826, "s": 12761, "text": "[4] Deep Learning with Python; Francois Chollet. pages: 160–177." }, { "code": null, "e": 12883, "s": 12826, "text": "[5] Resource for Dealing with Files in Colab: Neptune.ai" } ]
Highcharts - Column Chart using HTML Table
Following is an example of a Column Chart using HTML table. We have already seen the configuration used to draw a chart in Highcharts Configuration Syntax chapter. Let us now see additional configurations and also how we have added table under data. An example of a Column Chart using the HTML table is given below. The Data module provides a simplified interface for adding data to a chart from sources like CVS, HTML tables or grid views. A HTML table or the id of such is to be parsed as input data. The related options are startRow, endRow, startColumn and endColumn to delimit what part of the table is used. data: { table: 'dataTable' } highcharts_column_table.htm <html> <head> <title>Highcharts Tutorial</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script src = "https://code.highcharts.com/highcharts.js"></script> <script src = "https://code.highcharts.com/modules/data.js"></script> </head> <body> <div id = "container" style = "width: 550px; height: 400px; margin: 0 auto"></div> <script language = "JavaScript"> $(document).ready(function() { var data = { table: 'datatable' }; var chart = { type: 'column' }; var title = { text: 'Data extracted from a HTML table in the page' }; var yAxis = { allowDecimals: false, title: { text: 'Units' } }; var tooltip = { formatter: function () { return '<b>' + this.series.name + '</b><br/>' + this.point.y + ' ' + this.point.name.toLowerCase(); } }; var credits = { enabled: false }; var json = {}; json.chart = chart; json.title = title; json.data = data; json.yAxis = yAxis; json.credits = credits; json.tooltip = tooltip; $('#container').highcharts(json); }); </script> <table id = "datatable"> <thead> <tr> <th></th> <th>Jane</th> <th>John</th> </tr> </thead> <tbody> <tr> <th>Apples</th> <td>3</td> <td>4</td> </tr> <tr> <th>Pears</th> <td>2</td> <td>0</td> </tr> <tr> <th>Plums</th> <td>5</td> <td>11</td> </tr> <tr> <th>Bananas</th> <td>1</td> <td>1</td> </tr> <tr> <th>Oranges</th> <td>2</td> <td>4</td> </tr> </tbody> </table> </body> </html> Verify the result. Print Add Notes Bookmark this page
[ { "code": null, "e": 2077, "s": 2017, "text": "Following is an example of a Column Chart using HTML table." }, { "code": null, "e": 2267, "s": 2077, "text": "We have already seen the configuration used to draw a chart in Highcharts Configuration Syntax chapter. Let us now see additional configurations and also how we have added table under data." }, { "code": null, "e": 2333, "s": 2267, "text": "An example of a Column Chart using the HTML table is given below." }, { "code": null, "e": 2458, "s": 2333, "text": "The Data module provides a simplified interface for adding data to a chart from sources like CVS, HTML tables or grid views." }, { "code": null, "e": 2631, "s": 2458, "text": "A HTML table or the id of such is to be parsed as input data. The related options are startRow, endRow, startColumn and endColumn to delimit what part of the table is used." }, { "code": null, "e": 2665, "s": 2631, "text": "data: {\n table: 'dataTable' \n}" }, { "code": null, "e": 2693, "s": 2665, "text": "highcharts_column_table.htm" }, { "code": null, "e": 5091, "s": 2693, "text": "<html>\n <head>\n <title>Highcharts Tutorial</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n <script src = \"https://code.highcharts.com/highcharts.js\"></script> \n <script src = \"https://code.highcharts.com/modules/data.js\"></script>\n </head>\n \n <body>\n <div id = \"container\" style = \"width: 550px; height: 400px; margin: 0 auto\"></div>\n <script language = \"JavaScript\">\n $(document).ready(function() {\n var data = {\n table: 'datatable'\n };\n var chart = {\n type: 'column'\n };\n var title = {\n text: 'Data extracted from a HTML table in the page' \n }; \n var yAxis = {\n allowDecimals: false,\n title: {\n text: 'Units'\n }\n };\n var tooltip = {\n formatter: function () {\n return '<b>' + this.series.name + '</b><br/>' +\n this.point.y + ' ' + this.point.name.toLowerCase();\n }\n };\n var credits = {\n enabled: false\n }; \n var json = {}; \n json.chart = chart; \n json.title = title; \n json.data = data;\n json.yAxis = yAxis;\n json.credits = credits; \n json.tooltip = tooltip; \n $('#container').highcharts(json);\n });\n </script>\n \n <table id = \"datatable\">\n <thead>\n <tr>\n <th></th>\n <th>Jane</th>\n <th>John</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>Apples</th>\n <td>3</td>\n <td>4</td>\n </tr>\n <tr>\n <th>Pears</th>\n <td>2</td>\n <td>0</td>\n </tr>\n <tr>\n <th>Plums</th>\n <td>5</td>\n <td>11</td>\n </tr>\n <tr>\n <th>Bananas</th>\n <td>1</td>\n <td>1</td>\n </tr>\n <tr>\n <th>Oranges</th>\n <td>2</td>\n <td>4</td>\n </tr>\n </tbody>\n </table>\n </body>\n \n</html>" }, { "code": null, "e": 5110, "s": 5091, "text": "Verify the result." }, { "code": null, "e": 5117, "s": 5110, "text": " Print" }, { "code": null, "e": 5128, "s": 5117, "text": " Add Notes" } ]
How to Implement Sunglint Detection for Sentinel 2 Images in Python using Metadata Info | Towards Data Science
Optical Remote Sensing analysis depends on understanding the processes of absorption and scattering of solar radiance on ground objects. If we measure the solar incidence radiance and the surface’s irradiance, we will be able to estimate surface’s reflectance. Reflectance in various wavelengths is the key to understand the target we are observing, as each material will reflect and absorb energy differently depending on the considered wavelength. Figure 1 shows the mean reflectance spectra of different materials such as water, soil, vegetation and rocks. Some undesired effects, though, can interfere in the observed reflectance. These effects are specially present in space-borne sensors, as they are located outside Earth’s atmosphere and the presence of clouds, water vapor, etc. are constantly absorbing and scattering electromagnetic energy. Another important effect that can interfere in the observed reflectance is sunglint. Sunglint is caused by the specular (or mirror-like) reflectance of incident radiance on some surfaces in the same angle of the satellite or other sensor viewing it. In these cases, the sensor will not measure the characteristics of the observed target, but a mixture with the spectra of the emitting source. And this can bring issues for many remote sensing applications. In fire detection, for example, Giglio et. al. (2003)[1] shows that the effect of sunglint on some targets like water bodies, wet soil, cirrus clouds and even bare soil can cause false fire alarms. In water resources, this effect is specially important as water surfaces are the most affected by the sunglint (Figure 2). Because of this, glint correction or at least glint identification is an important task for most remote sensing applications. As our objective is not to dig deep in electromagnetic radiance theory, but to show how one can use Python and Sentinel 2 metadata info to estimate the occurrence of sunglint in the scene. For a full glint removal in aquatic systems, I suggest the paper from Harmel et. al. (2018)[2]. Instead, we will show how to predict the presence of sunglint using the approach proposed by Giglio et. al. (2003). In this approach we have to check the relationship between the solar and viewing angles (zenith and azimuth) at the moment the image has been acquired, according to the following equation: In this equation the subscripts v, s and g stands for viewing, solar and glint angles, θ refers to zenith angles and Φ is the azimuth angle difference between the sun and the sensor, as represented in Figure 3. The final glint angle value will be obtained by Arccos(θg) . According to the author, the resulting glint angle is a predictor of occurrence of sunglint. The smaller the glint angle value, the more “aligned” are the sensor and the sun and it will be higher the probability of sunglint. All the information we need for this calculation is contained in the Sentinel’s 2 metadata file MTD_TL.xml. This file is located inside the GRANULE subdirectory. So, let’s take a look at it. It can be overwhelming if we open this file for the first time, but if we look for Sun_Angles_Grid tag, we can find all the information we need concerning the sun position: Note that it is presented in steps of 5000m (23x23 grid), so this is not exactly a “pixelwise” information, but we can interpolate it to match pixel resolution afterwards. We will start by reading the sun angles from the metadata through the lxml package. At the end, we will use a pandas Dataframe just for visualization purpose. Code output: ( 0 1 2 3 4 0 19.5389 19.4952 19.4514 19.4076 19.3638 1 19.5431 19.4994 19.4556 19.4119 19.3681 2 19.5474 19.5037 19.4600 19.4162 19.3725 3 19.5518 19.5081 19.4644 19.4207 19.3769 4 19.5564 19.5126 19.4689 19.4252 19.3815, 0 1 2 3 4 0 80.1116 80.1092 80.1067 80.1041 80.1014 1 79.9860 79.9833 79.9804 79.9775 79.9745 2 79.8605 79.8574 79.8543 79.8510 79.8477 3 79.7350 79.7316 79.7281 79.7246 79.7209 4 79.6095 79.6058 79.6021 79.5982 79.5942) If we compare with the angles from the XML file, we can see that our data was loaded correctly. We could do the same for the sensors, but if you look carefully, you will see that we have many different sensors, and they have different angles. As we want to have a mean glint prediction for our scene, we will use an average of the angles for each sensor. To accomplish this, we will create a generic function that reads the arrays of a given node name and returns its average to retrieve mean zenith and azimuth for the sensors. At the end we will plot the angles using matplotlib. Code output: Note: We may see that the viewing azimuth angles have some issues in detectors transitions. The discussion thread about this problem can be found here (https://forum.step.esa.int/t/sentinel-2-viewing-angles-interpolation-on-per-pixel-basis/2776/4) Now that we have all the angles we need, it’s time to calculate the glint angle. First we should convert them all to radians (the unit used by numpy’s trigonometric functions). Then, the final calculation is pretty straightforward. To visualize the results, we will create an annotated heatmap with its values. Code output: To visualize the portions of the image that are more prone to have sunglint, nothing better than superimposing the glint angles grid with the image’s rgb representation. To get the rgb representation of the satellite image, we will use the rasterio package to read the Red, Green and Blue bands, as explained in the Python for Geosciences: Satellite Image Analysis series(here). Code output: Now, we can superimpose both grids using the imshow function from matplotlib and adjusting correctly the extents argument and the alpha to apply a transparency. ax.imshow(rgb*4, alpha=0.6, extent=(-0.5, 22.5, 22.5, -0.5))fig In this story we’ve discussed how to estimate the sunglint occurrence based on the solar and viewing angles available en Sentinel’s 2 metadata as proposed by Giglio (2003). With this information it is possible to adjust any remote sensing application that is affected by the sunglint presence. As an example, this simple sunglint prediction is being currently implemented in the waterdetect python package (here)[3] as a way to adjust the maximum thresholds levels when sunglint is expected. It could also be used in cloud detectors, to avoid water as being identified as clouds or in fire detection to prevent false positives. If you have any doubts our comments about this subject, don’t hesitate to write it in the comments. And don’t forget to follow me if you want to receive more stories like this. So stay tuned and see you in the next story. For more stories like this: https://cordmaur.medium.com/ If you liked this article and want to continue reading/learning these and other stories without limits, consider becoming a Medium member. You can also check out my portfolio at https://cordmaur.carrd.co/. cordmaur.medium.com [1] Giglio, L.; Descloitres, J.; Justice, C. O.; Kaufman, Y. J. An Enhanced Contextual Fire Detection Algorithm for MODIS. Remote Sensing of Environment 2003, 87 (2), 273–282. https://doi.org/10.1016/S0034-4257(03)00184-6. [2] Harmel, T.; Chami, M.; Tormos, T.; Reynaud, N.; Danis, P.-A. Sunglint Correction of the Multi-Spectral Instrument (MSI)-SENTINEL-2 Imagery over Inland and Sea Waters from SWIR Bands. Remote Sensing of Environment 2018, 204, 308–321. https://doi.org/10.1016/j.rse.2017.10.022. [3] Cordeiro, M. C. R.; Martinez, J.-M.; Peña-Luque, S. Automatic Water Detection from Multidimensional Hierarchical Clustering for Sentinel-2 Images and a Comparison with Level 2A Processors. Remote Sensing of Environment 2021, 253, 112209. https://doi.org/10.1016/j.rse.2020.112209.
[ { "code": null, "e": 732, "s": 172, "text": "Optical Remote Sensing analysis depends on understanding the processes of absorption and scattering of solar radiance on ground objects. If we measure the solar incidence radiance and the surface’s irradiance, we will be able to estimate surface’s reflectance. Reflectance in various wavelengths is the key to understand the target we are observing, as each material will reflect and absorb energy differently depending on the considered wavelength. Figure 1 shows the mean reflectance spectra of different materials such as water, soil, vegetation and rocks." }, { "code": null, "e": 1109, "s": 732, "text": "Some undesired effects, though, can interfere in the observed reflectance. These effects are specially present in space-borne sensors, as they are located outside Earth’s atmosphere and the presence of clouds, water vapor, etc. are constantly absorbing and scattering electromagnetic energy. Another important effect that can interfere in the observed reflectance is sunglint." }, { "code": null, "e": 1481, "s": 1109, "text": "Sunglint is caused by the specular (or mirror-like) reflectance of incident radiance on some surfaces in the same angle of the satellite or other sensor viewing it. In these cases, the sensor will not measure the characteristics of the observed target, but a mixture with the spectra of the emitting source. And this can bring issues for many remote sensing applications." }, { "code": null, "e": 1802, "s": 1481, "text": "In fire detection, for example, Giglio et. al. (2003)[1] shows that the effect of sunglint on some targets like water bodies, wet soil, cirrus clouds and even bare soil can cause false fire alarms. In water resources, this effect is specially important as water surfaces are the most affected by the sunglint (Figure 2)." }, { "code": null, "e": 1928, "s": 1802, "text": "Because of this, glint correction or at least glint identification is an important task for most remote sensing applications." }, { "code": null, "e": 2518, "s": 1928, "text": "As our objective is not to dig deep in electromagnetic radiance theory, but to show how one can use Python and Sentinel 2 metadata info to estimate the occurrence of sunglint in the scene. For a full glint removal in aquatic systems, I suggest the paper from Harmel et. al. (2018)[2]. Instead, we will show how to predict the presence of sunglint using the approach proposed by Giglio et. al. (2003). In this approach we have to check the relationship between the solar and viewing angles (zenith and azimuth) at the moment the image has been acquired, according to the following equation:" }, { "code": null, "e": 2729, "s": 2518, "text": "In this equation the subscripts v, s and g stands for viewing, solar and glint angles, θ refers to zenith angles and Φ is the azimuth angle difference between the sun and the sensor, as represented in Figure 3." }, { "code": null, "e": 3015, "s": 2729, "text": "The final glint angle value will be obtained by Arccos(θg) . According to the author, the resulting glint angle is a predictor of occurrence of sunglint. The smaller the glint angle value, the more “aligned” are the sensor and the sun and it will be higher the probability of sunglint." }, { "code": null, "e": 3379, "s": 3015, "text": "All the information we need for this calculation is contained in the Sentinel’s 2 metadata file MTD_TL.xml. This file is located inside the GRANULE subdirectory. So, let’s take a look at it. It can be overwhelming if we open this file for the first time, but if we look for Sun_Angles_Grid tag, we can find all the information we need concerning the sun position:" }, { "code": null, "e": 3710, "s": 3379, "text": "Note that it is presented in steps of 5000m (23x23 grid), so this is not exactly a “pixelwise” information, but we can interpolate it to match pixel resolution afterwards. We will start by reading the sun angles from the metadata through the lxml package. At the end, we will use a pandas Dataframe just for visualization purpose." }, { "code": null, "e": 3723, "s": 3710, "text": "Code output:" }, { "code": null, "e": 4290, "s": 3723, "text": "( 0 1 2 3 4 0 19.5389 19.4952 19.4514 19.4076 19.3638 1 19.5431 19.4994 19.4556 19.4119 19.3681 2 19.5474 19.5037 19.4600 19.4162 19.3725 3 19.5518 19.5081 19.4644 19.4207 19.3769 4 19.5564 19.5126 19.4689 19.4252 19.3815, 0 1 2 3 4 0 80.1116 80.1092 80.1067 80.1041 80.1014 1 79.9860 79.9833 79.9804 79.9775 79.9745 2 79.8605 79.8574 79.8543 79.8510 79.8477 3 79.7350 79.7316 79.7281 79.7246 79.7209 4 79.6095 79.6058 79.6021 79.5982 79.5942)" }, { "code": null, "e": 4872, "s": 4290, "text": "If we compare with the angles from the XML file, we can see that our data was loaded correctly. We could do the same for the sensors, but if you look carefully, you will see that we have many different sensors, and they have different angles. As we want to have a mean glint prediction for our scene, we will use an average of the angles for each sensor. To accomplish this, we will create a generic function that reads the arrays of a given node name and returns its average to retrieve mean zenith and azimuth for the sensors. At the end we will plot the angles using matplotlib." }, { "code": null, "e": 4885, "s": 4872, "text": "Code output:" }, { "code": null, "e": 5133, "s": 4885, "text": "Note: We may see that the viewing azimuth angles have some issues in detectors transitions. The discussion thread about this problem can be found here (https://forum.step.esa.int/t/sentinel-2-viewing-angles-interpolation-on-per-pixel-basis/2776/4)" }, { "code": null, "e": 5444, "s": 5133, "text": "Now that we have all the angles we need, it’s time to calculate the glint angle. First we should convert them all to radians (the unit used by numpy’s trigonometric functions). Then, the final calculation is pretty straightforward. To visualize the results, we will create an annotated heatmap with its values." }, { "code": null, "e": 5457, "s": 5444, "text": "Code output:" }, { "code": null, "e": 5836, "s": 5457, "text": "To visualize the portions of the image that are more prone to have sunglint, nothing better than superimposing the glint angles grid with the image’s rgb representation. To get the rgb representation of the satellite image, we will use the rasterio package to read the Red, Green and Blue bands, as explained in the Python for Geosciences: Satellite Image Analysis series(here)." }, { "code": null, "e": 5849, "s": 5836, "text": "Code output:" }, { "code": null, "e": 6010, "s": 5849, "text": "Now, we can superimpose both grids using the imshow function from matplotlib and adjusting correctly the extents argument and the alpha to apply a transparency." }, { "code": null, "e": 6074, "s": 6010, "text": "ax.imshow(rgb*4, alpha=0.6, extent=(-0.5, 22.5, 22.5, -0.5))fig" }, { "code": null, "e": 6702, "s": 6074, "text": "In this story we’ve discussed how to estimate the sunglint occurrence based on the solar and viewing angles available en Sentinel’s 2 metadata as proposed by Giglio (2003). With this information it is possible to adjust any remote sensing application that is affected by the sunglint presence. As an example, this simple sunglint prediction is being currently implemented in the waterdetect python package (here)[3] as a way to adjust the maximum thresholds levels when sunglint is expected. It could also be used in cloud detectors, to avoid water as being identified as clouds or in fire detection to prevent false positives." }, { "code": null, "e": 6924, "s": 6702, "text": "If you have any doubts our comments about this subject, don’t hesitate to write it in the comments. And don’t forget to follow me if you want to receive more stories like this. So stay tuned and see you in the next story." }, { "code": null, "e": 6981, "s": 6924, "text": "For more stories like this: https://cordmaur.medium.com/" }, { "code": null, "e": 7187, "s": 6981, "text": "If you liked this article and want to continue reading/learning these and other stories without limits, consider becoming a Medium member. You can also check out my portfolio at https://cordmaur.carrd.co/." }, { "code": null, "e": 7207, "s": 7187, "text": "cordmaur.medium.com" }, { "code": null, "e": 7430, "s": 7207, "text": "[1] Giglio, L.; Descloitres, J.; Justice, C. O.; Kaufman, Y. J. An Enhanced Contextual Fire Detection Algorithm for MODIS. Remote Sensing of Environment 2003, 87 (2), 273–282. https://doi.org/10.1016/S0034-4257(03)00184-6." }, { "code": null, "e": 7710, "s": 7430, "text": "[2] Harmel, T.; Chami, M.; Tormos, T.; Reynaud, N.; Danis, P.-A. Sunglint Correction of the Multi-Spectral Instrument (MSI)-SENTINEL-2 Imagery over Inland and Sea Waters from SWIR Bands. Remote Sensing of Environment 2018, 204, 308–321. https://doi.org/10.1016/j.rse.2017.10.022." } ]
Write a C program to find out the largest and smallest number in a series
Let the user enter four series of integers in the console, find out a number which is smallest and largest in a series To calculate the small and large number, we use if conditions. The logic we use to find the largest and smallest number is − if(minno>q) //checking 1st and 2nd number minno=q; else if(maxno&l;q) maxno=q; if(minno>r) //checking 1st and 3rd number minno=r; Live Demo #include<stdio.h> int main(){ int minno,maxno,p,q,r,s; printf("enter any four numbers:"); scanf("%d%d%d%d",&p,&q,&r,&s); minno=p; maxno=p; if(minno>q) //checking 1st and 2nd number minno=q; else if(maxno<q) maxno=q; if(minno>r) //checking 1st and 3rd number minno=r; else if(maxno<r) maxno=r; if(minno>s) //checking 1st and 4th number minno=s; else if(maxno<s) maxno=s; printf("Largest number from the given 4 numbers is:%d\n",maxno); printf("Smallest numbers from the given 4 numbers is:%d",minno); return 0; } enter any four numbers:34 78 23 12 Largest number from the given 4 numbers is:78 Smallest numbers from the given 4 numbers is:12 The below program finds the smallest and largest element in an array − #include<stdio.h> int main(){ int a[50],i,num,large,small; printf("Enter the number of elements :"); scanf("%d",&num); printf("Input the array elements :\n"); for(i=0;i<num;++i) scanf("%d",&a[i]); large=small=a[0]; for(i=1;i<num;++i){ if(a[i]>large) large=a[i]; if(a[i]<small) small=a[i]; } printf("small= %d\n",small); printf("large= %d\n",large); return 0; } Enter the number of elements :8 Input the array elements : 1 2 6 4 8 9 3 9 small= 1 large= 9
[ { "code": null, "e": 1181, "s": 1062, "text": "Let the user enter four series of integers in the console, find out a number which is smallest and largest in a series" }, { "code": null, "e": 1306, "s": 1181, "text": "To calculate the small and large number, we use if conditions. The logic we use to find the largest and smallest number is −" }, { "code": null, "e": 1445, "s": 1306, "text": "if(minno>q) //checking 1st and 2nd number\n minno=q;\nelse if(maxno&l;q)\n maxno=q;\nif(minno>r) //checking 1st and 3rd number\n minno=r;" }, { "code": null, "e": 1456, "s": 1445, "text": " Live Demo" }, { "code": null, "e": 2046, "s": 1456, "text": "#include<stdio.h>\nint main(){\n int minno,maxno,p,q,r,s;\n printf(\"enter any four numbers:\");\n scanf(\"%d%d%d%d\",&p,&q,&r,&s);\n minno=p;\n maxno=p;\n if(minno>q) //checking 1st and 2nd number\n minno=q;\n else if(maxno<q)\n maxno=q;\n if(minno>r) //checking 1st and 3rd number\n minno=r;\n else if(maxno<r)\n maxno=r;\n if(minno>s) //checking 1st and 4th number\n minno=s;\n else if(maxno<s)\n maxno=s;\n printf(\"Largest number from the given 4 numbers is:%d\\n\",maxno);\n printf(\"Smallest numbers from the given 4 numbers is:%d\",minno);\n return 0;\n}" }, { "code": null, "e": 2175, "s": 2046, "text": "enter any four numbers:34 78 23 12\nLargest number from the given 4 numbers is:78\nSmallest numbers from the given 4 numbers is:12" }, { "code": null, "e": 2246, "s": 2175, "text": "The below program finds the smallest and largest element in an array −" }, { "code": null, "e": 2676, "s": 2246, "text": "#include<stdio.h>\nint main(){\n int a[50],i,num,large,small;\n printf(\"Enter the number of elements :\");\n scanf(\"%d\",&num);\n printf(\"Input the array elements :\\n\");\n for(i=0;i<num;++i)\n scanf(\"%d\",&a[i]);\n large=small=a[0];\n for(i=1;i<num;++i){\n if(a[i]>large)\n large=a[i];\n if(a[i]<small)\n small=a[i];\n }\n printf(\"small= %d\\n\",small);\n printf(\"large= %d\\n\",large);\n return 0;\n}" }, { "code": null, "e": 2769, "s": 2676, "text": "Enter the number of elements :8\nInput the array elements :\n1\n2\n6\n4\n8\n9\n3\n9\nsmall= 1\nlarge= 9" } ]
Why do we use jQuery over JavaScript?
jQuery is a JavaScript library, so it operates on top of JavaScript. It cannot exist on its own, so you can't use one over the other. You can use just JavaScript or JavaScript and jQuery. jQuery was introduced to make development with JavaScript easier. It will reduce the development time. Use it to add animation and even handling on your website. jQuery simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is easier to use compared to JavaScript and its other JavaScript libraries. You need to write fewer lines of code while using jQuery, in comparison with JavaScript. Let us see the following code snippet as an example of jQuery and JavaScript to change the background color: function changeColor(color) { document.body.style.background = color; } Onload=”changeColor('blue');” $ ('body') .css ('background', '#0000FF'); As shown above, both the code snippets are doing the same work of changing the background color. But jQuery takes less code and in this way you can work around other examples, which shows that jQuery minimizes the code and is easier to use.
[ { "code": null, "e": 1412, "s": 1062, "text": "jQuery is a JavaScript library, so it operates on top of JavaScript. It cannot exist on its own, so you can't use one over the other. You can use just JavaScript or JavaScript and jQuery. jQuery was introduced to make development with JavaScript easier. It will reduce the development time. Use it to add animation and even handling on your website." }, { "code": null, "e": 1704, "s": 1412, "text": "jQuery simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is easier to use compared to JavaScript and its other JavaScript libraries. You need to write fewer lines of code while using jQuery, in comparison with JavaScript." }, { "code": null, "e": 1813, "s": 1704, "text": "Let us see the following code snippet as an example of jQuery and JavaScript to change the background color:" }, { "code": null, "e": 1918, "s": 1813, "text": "function changeColor(color) {\n document.body.style.background = color;\n}\nOnload=”changeColor('blue');”" }, { "code": null, "e": 1962, "s": 1918, "text": "$ ('body') .css ('background', '#0000FF');\n" }, { "code": null, "e": 2203, "s": 1962, "text": "As shown above, both the code snippets are doing the same work of changing the background color. But jQuery takes less code and in this way you can work around other examples, which shows that jQuery minimizes the code and is easier to use." } ]
Predict Customer Churn in Python. A step-by-step approach to predict... | by Sree | Towards Data Science
Customer attrition (a.k.a customer churn) is one of the biggest expenditures of any organization. If we could figure out why a customer leaves and when they leave with reasonable accuracy, it would immensely help the organization to strategize their retention initiatives manifold. Let’s make use of a customer transaction dataset from Kaggle to understand the key steps involved in predicting customer attrition in Python. Supervised Machine Learning is nothing but learning a function that maps an input to an output based on example input-output pairs. A supervised machine learning algorithm analyzes the training data and produces an inferred function, which can be used for mapping new examples. Given that we have data on current and prior customer transactions in the telecom dataset, this is a standardized supervised classification problem that tries to predict a binary outcome (Y/N). By the end of this article, let’s attempt to solve some of the key business challenges pertaining to customer attrition like say, (1) what is the likelihood of an active customer leaving an organization? (2) what are key indicators of a customer churn? (3) what retention strategies can be implemented based on the results to diminish prospective customer churn? In real-world, we need to go through seven major stages to successfully predict customer churn: Section A: Data Preprocessing Section B: Data Evaluation Section C: Model Selection Section D: Model Evaluation Section E: Model Improvement Section F: Future Predictions Section G: Model Deployment To understand the business challenge and the proposed solution, I would recommend you to download the dataset and to code with me. Feel free to ask me if you have any questions as you work along. Let’s look into each one of these aforesaid steps in detail here below If you had asked the 20-year-old me, I would have jumped straight into model selection as its coolest thing to do in machine learning. But like in life, wisdom kicks in at a later stage! After witnessing the real-world Machine Learning business challenges, I can’t stress the importance of Data preprocessing and Data Evaluation. Always remember the following golden rule in predictive analytics: “Your model is only as good as your data” Understanding the end-to-end structure of your dataset and reshaping the variables is the gateway to a qualitative predictive modelling initiative. Step 0: Restart the session: It’s a good practice to restart the session and to remove all the temporary variables from the interactive development environment before we start coding. So let's restart the session, clear the cache and start afresh! try: from IPython import get_ipython get_ipython().magic('clear') get_ipython().magic('reset -f')except: pass Step 1: Import relevant libraries: Import all the relevant python libraries for building supervised machine learning algorithms. #Standard libraries for data analysis: import numpy as npimport matplotlib.pyplot as pltimport pandas as pdfrom scipy.stats import norm, skewfrom scipy import statsimport statsmodels.api as sm# sklearn modules for data preprocessing:from sklearn.impute import SimpleImputerfrom sklearn.preprocessing import LabelEncoder, OneHotEncoderfrom sklearn.compose import ColumnTransformerfrom sklearn.preprocessing import OneHotEncoderfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import StandardScaler#sklearn modules for Model Selection:from sklearn import svm, tree, linear_model, neighborsfrom sklearn import naive_bayes, ensemble, discriminant_analysis, gaussian_processfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysisfrom xgboost import XGBClassifierfrom sklearn.linear_model import LogisticRegressionfrom sklearn.svm import SVCfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.naive_bayes import GaussianNBfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.ensemble import RandomForestClassifier#sklearn modules for Model Evaluation & Improvement: from sklearn.metrics import confusion_matrix, accuracy_score from sklearn.metrics import f1_score, precision_score, recall_score, fbeta_scorefrom statsmodels.stats.outliers_influence import variance_inflation_factorfrom sklearn.model_selection import cross_val_scorefrom sklearn.model_selection import GridSearchCVfrom sklearn.model_selection import ShuffleSplitfrom sklearn.model_selection import KFoldfrom sklearn import feature_selectionfrom sklearn import model_selectionfrom sklearn import metricsfrom sklearn.metrics import classification_report, precision_recall_curvefrom sklearn.metrics import auc, roc_auc_score, roc_curvefrom sklearn.metrics import make_scorer, recall_score, log_lossfrom sklearn.metrics import average_precision_score#Standard libraries for data visualization:import seaborn as snfrom matplotlib import pyplotimport matplotlib.pyplot as pltimport matplotlib.pylab as pylabimport matplotlib %matplotlib inlinecolor = sn.color_palette()import matplotlib.ticker as mtickfrom IPython.display import displaypd.options.display.max_columns = Nonefrom pandas.plotting import scatter_matrixfrom sklearn.metrics import roc_curve#Miscellaneous Utilitiy Libraries: import randomimport osimport reimport sysimport timeitimport stringimport timefrom datetime import datetimefrom time import timefrom dateutil.parser import parseimport joblib Step 2: Set up the current working directory: os.chdir(r”C:/Users/srees/Propensity Scoring Models/Predict Customer Churn/”) Step 3: Import the dataset: Let’s load the input dataset into the python notebook in the current working directory. dataset = pd.read_csv('1.Input/customer_churn_data.csv') Step 4: Evaluate data structure: In this section, we need to look at the dataset in general and each column in detail to get a better understanding of the input data so as to aggregate the fields when needed. From the head & column methods, we get an idea that this is a telco customer churn dataset where each record entails the nature of subscription, tenure, frequency of payment and churn (signifying their current status). dataset.head() dataset.columns A quick describe method reveals that the telecom customers are staying on average for 32 months and are paying $64 per month. However, this could potentially be because different customers have different contracts. dataset.describe() From the look of it, we can presume that the dataset contains several numerical and categorical columns providing various information on the customer transactions. dataset.dtypes Re-validate column data types and missing values: Always keep an eye onto the missing values in a dataset. The missing values could mess up model building and accuracy. Hence we need to take care of missing values (if any) before we compare and select a model. dataset.columns.to_series().groupby(dataset.dtypes).groups The dataset contains 7043 rows and 21 columns and there seem to be no missing values in the dataset. dataset.info() dataset.isna().any() Identify unique values: ‘Payment Methods’ and ‘Contract’ are the two categorical variables in the dataset. When we look into the unique values in each categorical variables, we get an insight that the customers are either on a month-to-month rolling contract or on a fixed contract for one/two years. Also, they are paying bills via credit card, bank transfer or electronic checks. #Unique values in each categorical variable:dataset["PaymentMethod"].nunique()dataset["PaymentMethod"].unique()dataset["Contract"].nunique()dataset["Contract"].unique() Step 5: Check target variable distribution: Let’s look at the distribution of churn values. This is quite a simple yet crucial step to see if the dataset upholds any class imbalance issues. As you can see below, the data set is imbalanced with a high proportion of active customers compared to their churned counterparts. dataset["Churn"].value_counts() Step 6: Clean the dataset: dataset['TotalCharges'] = pd.to_numeric(dataset['TotalCharges'],errors='coerce')dataset['TotalCharges'] = dataset['TotalCharges'].astype("float") Step 7: Take care of missing data: As we saw earlier, the data provided has no missing values and hence this step is not required for the chosen dataset. I would like to showcase the steps here for any future references. dataset.info() dataset.isna().any() Find the average and fill missing values programmatically: If we had any missing values in the numeric columns of the dataset, then we should find the average of each one of those columns and fill their missing values. Here’s a snippet of code to do the same step programmatically. na_cols = dataset.isna().any()na_cols = na_cols[na_cols == True].reset_index()na_cols = na_cols["index"].tolist()for col in dataset.columns[1:]: if col in na_cols: if dataset[col].dtype != 'object': dataset[col] = dataset[col].fillna(dataset[col].mean()).round(0) Revalidate NA’s: It’s always a good practice to revalidate and ensure that we don’t have any more null values in the dataset. dataset.isna().any() Step 8: Label Encode Binary data: Machine Learning algorithms can typically only have numerical values as their independent variables. Hence label encoding is quite pivotal as they encode categorical labels with appropriate numerical values. Here we are label encoding all categorical variables that have only two unique values. Any categorical variable that has more than two unique values are dealt with Label Encoding and one-hot Encoding in the subsequent sections. #Create a label encoder objectle = LabelEncoder()# Label Encoding will be used for columns with 2 or less unique valuesle_count = 0for col in dataset.columns[1:]: if dataset[col].dtype == 'object': if len(list(dataset[col].unique())) <= 2: le.fit(dataset[col]) dataset[col] = le.transform(dataset[col]) le_count += 1print('{} columns were label encoded.'.format(le_count)) Step 9: Exploratory Data Analysis: Let’s try to explore and visualize our data set by doing distribution of independent variables to better understand the patterns in the data and to potentially form some hypothesis. Step 9.1. Plot histogram of numeric Columns: dataset2 = dataset[['gender', 'SeniorCitizen', 'Partner','Dependents','tenure', 'PhoneService', 'PaperlessBilling','MonthlyCharges', 'TotalCharges']]#Histogram: fig = plt.figure(figsize=(15, 12))plt.suptitle('Histograms of Numerical Columns\n',horizontalalignment="center",fontstyle = "normal", fontsize = 24, fontfamily = "sans-serif")for i in range(dataset2.shape[1]): plt.subplot(6, 3, i + 1) f = plt.gca() f.set_title(dataset2.columns.values[i])vals = np.size(dataset2.iloc[:, i].unique()) if vals >= 100: vals = 100 plt.hist(dataset2.iloc[:, i], bins=vals, color = '#ec838a')plt.tight_layout(rect=[0, 0.03, 1, 0.95]) A few observations can be made based on the histograms for numerical variables: Gender distribution shows that the dataset features a relatively equal proportion of male and female customers. Almost half of the customers in our dataset are female whilst the other half are male. Most of the customers in the dataset are younger people. Not many customers seem to have dependents whilst almost half of the customers have a partner. There are a lot of new customers in the organization (less than 10 months old) followed by a loyal customer segment that stays for more than 70 months on average. Most of the customers seem to have phone service and 3/4th of them have opted for paperless Billing Monthly charges span anywhere between $18 to $118 per customer with a huge proportion of customers on $20 segment. Step 9.2. Analyze the distribution of categorical variables: 9.2.1. Distribution of contract type: Most of the customers seem to have a prepaid connection with the telecom company. On the other hand, there are a more or less equal proportion of customers in the 1-year and 2-year contracts. contract_split = dataset[[ "customerID", "Contract"]]sectors = contract_split .groupby ("Contract")contract_split = pd.DataFrame(sectors["customerID"].count())contract_split.rename(columns={'customerID':'No. of customers'}, inplace=True)ax = contract_split[["No. of customers"]].plot.bar(title = 'Customers by Contract Type',legend =True, table = False, grid = False, subplots = False,figsize =(12, 7), color ='#ec838a', fontsize = 15, stacked=False)plt.ylabel('No. of Customers\n',horizontalalignment="center",fontstyle = "normal", fontsize = "large", fontfamily = "sans-serif")plt.xlabel('\n Contract Type',horizontalalignment="center",fontstyle = "normal", fontsize = "large", fontfamily = "sans-serif")plt.title('Customers by Contract Type \n',horizontalalignment="center",fontstyle = "normal", fontsize = "22", fontfamily = "sans-serif")plt.legend(loc='top right', fontsize = "medium")plt.xticks(rotation=0, horizontalalignment="center")plt.yticks(rotation=0, horizontalalignment="right")x_labels = np.array(contract_split[["No. of customers"]])def add_value_labels(ax, spacing=5): for rect in ax.patches: y_value = rect.get_height() x_value = rect.get_x() + rect.get_width() / 2 space = spacing va = 'bottom' if y_value < 0: space *= -1 va = 'top' label = "{:.0f}".format(y_value) ax.annotate( label, (x_value, y_value), xytext=(0, space), textcoords="offset points", ha='center', va=va) add_value_labels(ax) 9.2.2. Distribution of payment method type: The dataset indicates that customers prefer to pay their bills electronically the most followed by bank transfer, credit card and mailed checks. payment_method_split = dataset[[ "customerID", "PaymentMethod"]]sectors = payment_method_split .groupby ("PaymentMethod")payment_method_split = pd.DataFrame(sectors["customerID"].count())payment_method_split.rename(columns={'customerID':'No. of customers'}, inplace=True)ax = payment_method_split [["No. of customers"]].plot.bar(title = 'Customers by Payment Method', legend =True, table = False, grid = False, subplots = False, figsize =(15, 10),color ='#ec838a', fontsize = 15, stacked=False)plt.ylabel('No. of Customers\n',horizontalalignment="center",fontstyle = "normal", fontsize = "large", fontfamily = "sans-serif")plt.xlabel('\n Contract Type',horizontalalignment="center",fontstyle = "normal", fontsize = "large", fontfamily = "sans-serif")plt.title('Customers by Payment Method \n',horizontalalignment="center", fontstyle = "normal", fontsize = "22", fontfamily = "sans-serif")plt.legend(loc='top right', fontsize = "medium")plt.xticks(rotation=0, horizontalalignment="center")plt.yticks(rotation=0, horizontalalignment="right")x_labels = np.array(payment_method_split [["No. of customers"]])def add_value_labels(ax, spacing=5): for rect in ax.patches: y_value = rect.get_height() x_value = rect.get_x() + rect.get_width() / 2 space = spacing va = 'bottom' if y_value < 0: space *= -1 va = 'top' label = "{:.0f}".format(y_value) ax.annotate(label, (x_value, y_value), xytext=(0, space),textcoords="offset points", ha='center',va=va)add_value_labels(ax) 9.2.3. Distribution of label encoded categorical variables: services= ['PhoneService','MultipleLines','InternetService','OnlineSecurity', 'OnlineBackup','DeviceProtection','TechSupport','StreamingTV','StreamingMovies']fig, axes = plt.subplots(nrows = 3,ncols = 3,figsize = (15,12))for i, item in enumerate(services): if i < 3: ax = dataset[item].value_counts().plot( kind = 'bar',ax=axes[i,0], rot = 0, color ='#f3babc' ) elif i >=3 and i < 6: ax = dataset[item].value_counts().plot( kind = 'bar',ax=axes[i-3,1], rot = 0,color ='#9b9c9a') elif i < 9: ax = dataset[item].value_counts().plot( kind = 'bar',ax=axes[i-6,2],rot = 0, color = '#ec838a')ax.set_title(item) Most of the customers have phone service out of which almost half of the customers have multiple lines. 3/4th of the customers have opted for internet service via Fiber Optic and DSL connections with almost half of the internet users subscribing to streaming TV and movies. Customers who have availed Online Backup, Device Protection, Technical Support and Online Security features are a minority. Step 9.3: Analyze the churn rate by categorical variables: 9.3.1. Overall churn rate: A preliminary look at the overall churn rate shows that around 74% of the customers are active. As shown in the chart below, this is an imbalanced classification problem. Machine learning algorithms work well when the number of instances of each class is roughly equal. Since the dataset is skewed, we need to keep that in mind while choosing the metrics for model selection. import matplotlib.ticker as mtickchurn_rate = dataset[["Churn", "customerID"]]churn_rate ["churn_label"] = pd.Series(np.where((churn_rate["Churn"] == 0), "No", "Yes"))sectors = churn_rate .groupby ("churn_label")churn_rate = pd.DataFrame(sectors["customerID"].count())churn_rate ["Churn Rate"] = (churn_rate ["customerID"]/ sum(churn_rate ["customerID"]) )*100ax = churn_rate[["Churn Rate"]].plot.bar(title = 'Overall Churn Rate',legend =True, table = False,grid = False, subplots = False, figsize =(12, 7), color = '#ec838a', fontsize = 15, stacked=False, ylim =(0,100))plt.ylabel('Proportion of Customers',horizontalalignment="center",fontstyle = "normal", fontsize = "large", fontfamily = "sans-serif")plt.xlabel('Churn',horizontalalignment="center",fontstyle = "normal", fontsize = "large", fontfamily = "sans-serif")plt.title('Overall Churn Rate \n',horizontalalignment="center", fontstyle = "normal", fontsize = "22", fontfamily = "sans-serif")plt.legend(loc='top right', fontsize = "medium")plt.xticks(rotation=0, horizontalalignment="center")plt.yticks(rotation=0, horizontalalignment="right")ax.yaxis.set_major_formatter(mtick.PercentFormatter())x_labels = np.array(churn_rate[["customerID"]])def add_value_labels(ax, spacing=5): for rect in ax.patches: y_value = rect.get_height() x_value = rect.get_x() + rect.get_width() / 2 space = spacing va = 'bottom' if y_value < 0: space *= -1 va = 'top' label = "{:.1f}%".format(y_value) ax.annotate(label, (x_value, y_value), xytext=(0, space), textcoords="offset points", ha='center',va=va)add_value_labels(ax)ax.autoscale(enable=False, axis='both', tight=False) 9.3.2. Churn Rate by Contract Type: Customers with a prepaid or rather a month-to-month connection have a very high probability to churn compared to their peers on 1 or 2 years contracts. import matplotlib.ticker as mtickcontract_churn =dataset.groupby(['Contract','Churn']).size().unstack()contract_churn.rename(columns={0:'No', 1:'Yes'}, inplace=True)colors = ['#ec838a','#9b9c9a']ax = (contract_churn.T*100.0 / contract_churn.T.sum()).T.plot(kind='bar',width = 0.3,stacked = True,rot = 0,figsize = (12,7),color = colors)plt.ylabel('Proportion of Customers\n',horizontalalignment="center",fontstyle = "normal", fontsize = "large", fontfamily = "sans-serif")plt.xlabel('Contract Type\n',horizontalalignment="center",fontstyle = "normal", fontsize = "large", fontfamily = "sans-serif")plt.title('Churn Rate by Contract type \n',horizontalalignment="center", fontstyle = "normal", fontsize = "22", fontfamily = "sans-serif")plt.legend(loc='top right', fontsize = "medium")plt.xticks(rotation=0, horizontalalignment="center")plt.yticks(rotation=0, horizontalalignment="right")ax.yaxis.set_major_formatter(mtick.PercentFormatter())for p in ax.patches: width, height = p.get_width(), p.get_height() x, y = p.get_xy() ax.text(x+width/2, y+height/2, '{:.1f}%'.format(height), horizontalalignment='center', verticalalignment='center')ax.autoscale(enable=False, axis='both', tight=False) 9.3.3. Churn Rate by Payment Method Type: Customers who pay via bank transfers seem to have the lowest churn rate among all the payment method segments. import matplotlib.ticker as mtickcontract_churn = dataset.groupby(['Contract','PaymentMethod']).size().unstack()contract_churn.rename(columns={0:'No', 1:'Yes'}, inplace=True)colors = ['#ec838a','#9b9c9a', '#f3babc' , '#4d4f4c']ax = (contract_churn.T*100.0 / contract_churn.T.sum()).T.plot(kind='bar',width = 0.3,stacked = True,rot = 0,figsize = (12,7),color = colors)plt.ylabel('Proportion of Customers\n',horizontalalignment="center",fontstyle = "normal", fontsize = "large", fontfamily = "sans-serif")plt.xlabel('Contract Type\n',horizontalalignment="center",fontstyle = "normal", fontsize = "large", fontfamily = "sans-serif")plt.title('Churn Rate by Payment Method \n',horizontalalignment="center", fontstyle = "normal", fontsize = "22", fontfamily = "sans-serif")plt.legend(loc='top right', fontsize = "medium")plt.xticks(rotation=0, horizontalalignment="center")plt.yticks(rotation=0, horizontalalignment="right")ax.yaxis.set_major_formatter(mtick.PercentFormatter())for p in ax.patches: width, height = p.get_width(), p.get_height() x, y = p.get_xy() ax.text(x+width/2, y+height/2, '{:.1f}%'.format(height), horizontalalignment='center', verticalalignment='center')ax.autoscale(enable=False, axis='both', tight=False Step 9.4. Find positive and negative correlations: Interestingly, the churn rate increases with monthly charges and age. In contrast Partner, Dependents and Tenure seem to be negatively related to churn. Let’s have a look into the positive and negative correlations graphically in the next step. dataset2 = dataset[['SeniorCitizen', 'Partner', 'Dependents', 'tenure', 'PhoneService', 'PaperlessBilling', 'MonthlyCharges', 'TotalCharges']]correlations = dataset2.corrwith(dataset.Churn)correlations = correlations[correlations!=1]positive_correlations = correlations[correlations >0].sort_values(ascending = False)negative_correlations =correlations[correlations<0].sort_values(ascending = False)print('Most Positive Correlations: \n', positive_correlations)print('\nMost Negative Correlations: \n', negative_correlations) Step 9.5. Plot positive & negative correlations: correlations = dataset2.corrwith(dataset.Churn)correlations = correlations[correlations!=1]correlations.plot.bar( figsize = (18, 10), fontsize = 15, color = '#ec838a', rot = 45, grid = True)plt.title('Correlation with Churn Rate \n',horizontalalignment="center", fontstyle = "normal", fontsize = "22", fontfamily = "sans-serif") Step 9.6. Plot Correlation Matrix of all independent variables: Correlation matrix helps us to discover the bivariate relationship between independent variables in a dataset. #Set and compute the Correlation Matrix:sn.set(style="white")corr = dataset2.corr()#Generate a mask for the upper triangle:mask = np.zeros_like(corr, dtype=np.bool)mask[np.triu_indices_from(mask)] = True#Set up the matplotlib figure and a diverging colormap:f, ax = plt.subplots(figsize=(18, 15))cmap = sn.diverging_palette(220, 10, as_cmap=True)#Draw the heatmap with the mask and correct aspect ratio:sn.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0,square=True, linewidths=.5, cbar_kws={"shrink": .5}) Step 9.7: Check Multicollinearity using VIF: Let's try to look into multicollinearity using Variable Inflation Factors (VIF). Unlike Correlation matrix, VIF determines the strength of the correlation of a variable with a group of other independent variables in a dataset. VIF starts usually at 1 and anywhere exceeding 10 indicates high multicollinearity between the independent variables. def calc_vif(X):# Calculating VIF vif = pd.DataFrame() vif["variables"] = X.columns vif["VIF"] = [variance_inflation_factor(X.values, i) for i in range(X.shape[1])]return(vif)dataset2 = dataset[['gender', 'SeniorCitizen', 'Partner', 'Dependents','tenure', 'PhoneService','PaperlessBilling','MonthlyCharges','TotalCharges']]calc_vif(dataset2) We can see here that the ‘Monthly Charges’ and ‘Total Charges’ have a high VIF value. 'Total Charges' seem to be collinear with 'Monthly Charges'.#Check colinearity: dataset2[['MonthlyCharges', 'TotalCharges']].plot.scatter(figsize = (15, 10), x ='MonthlyCharges',y='TotalCharges', color = '#ec838a')plt.title('Collinearity of Monthly Charges and Total Charges \n',horizontalalignment="center", fontstyle = "normal", fontsize = "22", fontfamily = "sans-serif") Let’s try to drop one of the correlated features to see if it help us in bringing down the multicollinearity between correlated features: #Dropping 'TotalCharges': dataset2 = dataset2.drop(columns = "TotalCharges")#Revalidate Colinearity:dataset2 = dataset[['gender', 'SeniorCitizen', 'Partner', 'Dependents','tenure', 'PhoneService', 'PaperlessBilling','MonthlyCharges']]calc_vif(dataset2)#Applying changes in the main dataset: dataset = dataset.drop(columns = "TotalCharges") In our example, after dropping the ‘Total Charges’ variable, VIF values for all the independent variables have decreased to a considerable extent. Exploratory Data Analysis Concluding Remarks: Let’s try to summarise some of the key findings from this EDA: The dataset does not have any missing or erroneous data values. Strongest positive correlation with the target features is Monthly Charges and Age whilst negative correlation is with Partner, Dependents and Tenure. The dataset is imbalanced with the majority of customers being active. There is multicollinearity between Monthly Charges and Total Charges. Dropping Total Charges have decreased the VIF values considerably. Most of the customers in the dataset are younger people. There are a lot of new customers in the organization (less than 10 months old) followed by a loyal customer base that’s above 70 months old. Most of the customers seem to have phone service with Monthly charges spanning between $18 to $118 per customer. Customers with a month-to-month connection have a very high probability to churn that too if they have subscribed to pay via electronic checks. Step 10: Encode Categorical data: Any categorical variable that has more than two unique values have been dealt with Label Encoding and one-hot Encoding using get_dummies method in pandas here. #Incase if user_id is an object: identity = dataset["customerID"]dataset = dataset.drop(columns="customerID")#Convert rest of categorical variable into dummy:dataset= pd.get_dummies(dataset)#Rejoin userid to dataset:dataset = pd.concat([dataset, identity], axis = 1) Step 11: Split the dataset into dependent and independent variables: Now we need to separate the dataset into X and y values. y would be the ‘Churn’ column whilst X would be the remaining list of independent variables in the dataset. #Identify response variable: response = dataset["Churn"]dataset = dataset.drop(columns="Churn") Step 12: Generate training and test datasets: Let’s decouple the master dataset into training and test set with an 80%-20% ratio. X_train, X_test, y_train, y_test = train_test_split(dataset, response,stratify=response, test_size = 0.2, #use 0.9 if data is huge.random_state = 0)#to resolve any class imbalance - use stratify parameter.print("Number transactions X_train dataset: ", X_train.shape)print("Number transactions y_train dataset: ", y_train.shape)print("Number transactions X_test dataset: ", X_test.shape)print("Number transactions y_test dataset: ", y_test.shape) Step 13: Remove Identifiers: Separate ‘customerID’ from training and test data frames. train_identity = X_train['customerID']X_train = X_train.drop(columns = ['customerID'])test_identity = X_test['customerID']X_test = X_test.drop(columns = ['customerID']) Step 14: Conduct Feature Scaling: It’s quite important to normalize the variables before conducting any machine learning (classification) algorithms so that all the training and test variables are scaled within a range of 0 to 1. sc_X = StandardScaler()X_train2 = pd.DataFrame(sc_X.fit_transform(X_train))X_train2.columns = X_train.columns.valuesX_train2.index = X_train.index.valuesX_train = X_train2X_test2 = pd.DataFrame(sc_X.transform(X_test))X_test2.columns = X_test.columns.valuesX_test2.index = X_test.index.valuesX_test = X_test2 Step 15.1: Compare Baseline Classification Algorithms (1st Iteration): Let’s model each classification algorithm over the training dataset and evaluate their accuracy and standard deviation scores. Classification Accuracy is one of the most common classification evaluation metrics to compare baseline algorithms as its the number of correct predictions made as a ratio of total predictions. However, it's not the ideal metric when we have class imbalance issue. Hence, let us sort the results based on the ‘Mean AUC’ value which is nothing but the model’s ability to discriminate between positive and negative classes. models = []models.append(('Logistic Regression', LogisticRegression(solver='liblinear', random_state = 0, class_weight='balanced')))models.append(('SVC', SVC(kernel = 'linear', random_state = 0)))models.append(('Kernel SVM', SVC(kernel = 'rbf', random_state = 0)))models.append(('KNN', KNeighborsClassifier(n_neighbors = 5, metric = 'minkowski', p = 2)))models.append(('Gaussian NB', GaussianNB()))models.append(('Decision Tree Classifier', DecisionTreeClassifier(criterion = 'entropy', random_state = 0)))models.append(('Random Forest', RandomForestClassifier( n_estimators=100, criterion = 'entropy', random_state = 0)))#Evaluating Model Results:acc_results = []auc_results = []names = []# set table to table to populate with performance resultscol = ['Algorithm', 'ROC AUC Mean', 'ROC AUC STD', 'Accuracy Mean', 'Accuracy STD']model_results = pd.DataFrame(columns=col)i = 0# Evaluate each model using k-fold cross-validation:for name, model in models: kfold = model_selection.KFold( n_splits=10, random_state=0)# accuracy scoring:cv_acc_results = model_selection.cross_val_score( model, X_train, y_train, cv=kfold, scoring='accuracy')# roc_auc scoring:cv_auc_results = model_selection.cross_val_score( model, X_train, y_train, cv=kfold, scoring='roc_auc')acc_results.append(cv_acc_results) auc_results.append(cv_auc_results) names.append(name) model_results.loc[i] = [name, round(cv_auc_results.mean()*100, 2), round(cv_auc_results.std()*100, 2), round(cv_acc_results.mean()*100, 2), round(cv_acc_results.std()*100, 2) ] i += 1 model_results.sort_values(by=['ROC AUC Mean'], ascending=False) Step 15.2. Visualize Classification Algorithms Accuracy Comparisons: Using Accuracy Mean: fig = plt.figure(figsize=(15, 7))ax = fig.add_subplot(111)plt.boxplot(acc_results)ax.set_xticklabels(names)#plt.ylabel('ROC AUC Score\n',horizontalalignment="center",fontstyle = "normal", fontsize = "large", fontfamily = "sans-serif")#plt.xlabel('\n Baseline Classification Algorithms\n',horizontalalignment="center",fontstyle = "normal", fontsize = "large", fontfamily = "sans-serif")plt.title('Accuracy Score Comparison \n',horizontalalignment="center", fontstyle = "normal", fontsize = "22", fontfamily = "sans-serif")#plt.legend(loc='top right', fontsize = "medium")plt.xticks(rotation=0, horizontalalignment="center")plt.yticks(rotation=0, horizontalalignment="right")plt.show() Using Area under ROC Curve: From the first iteration of baseline classification algorithms, we can see that Logistic Regression and SVC have outperformed the other five models for the chosen dataset with the highest mean AUC Scores. Let’s reconfirm our results in the second iteration as shown in the next steps. fig = plt.figure(figsize=(15, 7))ax = fig.add_subplot(111)plt.boxplot(auc_results)ax.set_xticklabels(names)#plt.ylabel('ROC AUC Score\n',horizontalalignment="center",fontstyle = "normal",fontsize = "large", fontfamily = "sans-serif")#plt.xlabel('\n Baseline Classification Algorithms\n',horizontalalignment="center",fontstyle = "normal", fontsize = "large", fontfamily = "sans-serif")plt.title('ROC AUC Comparison \n',horizontalalignment="center", fontstyle = "normal", fontsize = "22", fontfamily = "sans-serif")#plt.legend(loc='top right', fontsize = "medium")plt.xticks(rotation=0, horizontalalignment="center")plt.yticks(rotation=0, horizontalalignment="right")plt.show() Step 15.3. Get the right parameters for the baseline models: Before doing the second iteration, let’s optimize the parameters and finalize the evaluation metrics for model selection. Identify the optimal number of K neighbors for KNN Model: In the first iteration, we assumed that K = 3, but in reality, we don’t know what is the optimal K value that gives maximum accuracy for the chosen training dataset. Therefore, let us write a for loop that iterates 20 to 30 times and gives the accuracy at each iteration so as to figure out the optimal number of K neighbors for the KNN Model. score_array = []for each in range(1,25): knn_loop = KNeighborsClassifier(n_neighbors = each) #set K neighbor as 3 knn_loop.fit(X_train,y_train) score_array.append(knn_loop.score(X_test,y_test))fig = plt.figure(figsize=(15, 7))plt.plot(range(1,25),score_array, color = '#ec838a')plt.ylabel('Range\n',horizontalalignment="center",fontstyle = "normal", fontsize = "large", fontfamily = "sans-serif")plt.xlabel('Score\n',horizontalalignment="center",fontstyle = "normal", fontsize = "large", fontfamily = "sans-serif")plt.title('Optimal Number of K Neighbors \n',horizontalalignment="center", fontstyle = "normal", fontsize = "22", fontfamily = "sans-serif")#plt.legend(loc='top right', fontsize = "medium")plt.xticks(rotation=0, horizontalalignment="center")plt.yticks(rotation=0, horizontalalignment="right")plt.show() As we can see from the above iterations, if we use K = 22, then we will get the maximum score of 78%. Identify the optimal number of trees for Random Forest Model: Quite similar to the iterations in the KNN model, here we are trying to find the optimal number of decision trees to compose the best random forest. score_array = []for each in range(1,100): rf_loop = RandomForestClassifier(n_estimators = each, random_state = 1) rf_loop.fit(X_train,y_train) score_array.append(rf_loop.score(X_test,y_test)) fig = plt.figure(figsize=(15, 7))plt.plot(range(1,100),score_array, color = '#ec838a')plt.ylabel('Range\n',horizontalalignment="center",fontstyle = "normal", fontsize = "large", fontfamily = "sans-serif")plt.xlabel('Score\n',horizontalalignment="center",fontstyle = "normal", fontsize = "large", fontfamily = "sans-serif")plt.title('Optimal Number of Trees for Random Forest Model \n',horizontalalignment="center", fontstyle = "normal", fontsize = "22", fontfamily = "sans-serif")#plt.legend(loc='top right', fontsize = "medium")plt.xticks(rotation=0, horizontalalignment="center")plt.yticks(rotation=0, horizontalalignment="right")plt.show() As we could see from the iterations above, the random forest model would attain the highest accuracy score when its n_estimators = 72. Step 15.4. Compare Baseline Classification Algorithms (2nd Iteration): In the second iteration of comparing baseline classification algorithms, we would be using the optimised parameters for KNN and Random Forest models. Also, we know that false negatives are more costly than false positives in a churn and hence let’s use precision, recall and F2 scores as the ideal metric for the model selection. Step 15.4.1. Logistic Regression: # Fitting Logistic Regression to the Training setclassifier = LogisticRegression(random_state = 0)classifier.fit(X_train, y_train)# Predicting the Test set resultsy_pred = classifier.predict(X_test)#Evaluate resultsacc = accuracy_score(y_test, y_pred )prec = precision_score(y_test, y_pred )rec = recall_score(y_test, y_pred )f1 = f1_score(y_test, y_pred )f2 = fbeta_score(y_test, y_pred, beta=2.0)results = pd.DataFrame([['Logistic Regression', acc, prec, rec, f1, f2]], columns = ['Model', 'Accuracy', 'Precision', 'Recall', 'F1 Score', 'F2 Score'])results = results.sort_values(["Precision", "Recall", "F2 Score"], ascending = False)print (results) Step 15.4.2. Support Vector Machine (linear classifier): # Fitting SVM (SVC class) to the Training setclassifier = SVC(kernel = 'linear', random_state = 0)classifier.fit(X_train, y_train)# Predicting the Test set results y_pred = classifier.predict(X_test)#Evaluate resultsacc = accuracy_score(y_test, y_pred )prec = precision_score(y_test, y_pred )rec = recall_score(y_test, y_pred)f1 = f1_score(y_test, y_pred )f2 = fbeta_score(y_test, y_pred, beta=2.0)model_results = pd.DataFrame([['SVM (Linear)', acc, prec, rec, f1, f2]],columns = ['Model', 'Accuracy', 'Precision', 'Recall', 'F1 Score', 'F2 Score'])results = results.append(model_results, ignore_index = True)results = results.sort_values(["Precision", "Recall", "F2 Score"], ascending = False)print (results) Step 15.4.3. K-Nearest Neighbors: # Fitting KNN to the Training set:classifier = KNeighborsClassifier(n_neighbors = 22, metric = 'minkowski', p = 2)classifier.fit(X_train, y_train)# Predicting the Test set results y_pred = classifier.predict(X_test)#Evaluate resultsacc = accuracy_score(y_test, y_pred )prec = precision_score(y_test, y_pred )rec = recall_score(y_test, y_pred )f1 = f1_score(y_test, y_pred )f2 = fbeta_score(y_test, y_pred, beta=2.0)model_results = pd.DataFrame([['K-Nearest Neighbours', acc, prec, rec, f1, f2]], columns = ['Model', 'Accuracy', 'Precision', 'Recall', 'F1 Score', 'F2 Score'])results = results.append(model_results, ignore_index = True)results = results.sort_values(["Precision", "Recall", "F2 Score"], ascending = False)print (results) Step 15.4.4. Kernel SVM: # Fitting Kernel SVM to the Training set:classifier = SVC(kernel = 'rbf', random_state = 0)classifier.fit(X_train, y_train)# Predicting the Test set results y_pred = classifier.predict(X_test)#Evaluate resultsacc = accuracy_score(y_test, y_pred )prec = precision_score(y_test, y_pred )rec = recall_score(y_test, y_pred )f1 = f1_score(y_test, y_pred )f2 = fbeta_score(y_test, y_pred, beta=2.0)model_results = pd.DataFrame([['Kernel SVM', acc, prec, rec, f1, f2]],columns = ['Model', 'Accuracy', 'Precision', 'Recall', 'F1 Score', 'F2 Score'])results = results.append(model_results, ignore_index = True)results = results.sort_values(["Precision", "Recall", "F2 Score"], ascending = False)print (results) Step 15.4.5. Naive Byes: # Fitting Naive Byes to the Training set:classifier = GaussianNB()classifier.fit(X_train, y_train)# Predicting the Test set results y_pred = classifier.predict(X_test)#Evaluate resultsacc = accuracy_score(y_test, y_pred )prec = precision_score(y_test, y_pred )rec = recall_score(y_test, y_pred )f1 = f1_score(y_test, y_pred )f2 = fbeta_score(y_test, y_pred, beta=2.0)model_results = pd.DataFrame([['Naive Byes', acc, prec, rec, f1, f2]],columns = ['Model', 'Accuracy', 'Precision','Recall', 'F1 Score', 'F2 Score'])results = results.append(model_results, ignore_index = True)results = results.sort_values(["Precision", "Recall", "F2 Score"], ascending = False)print (results) Step 15.4.6. Decision Tree: # Fitting Decision Tree to the Training set:classifier = DecisionTreeClassifier(criterion = 'entropy', random_state = 0)classifier.fit(X_train, y_train)# Predicting the Test set results y_pred = classifier.predict(X_test)#Evaluate resultsacc = accuracy_score(y_test, y_pred )prec = precision_score(y_test, y_pred )rec = recall_score(y_test, y_pred )f1 = f1_score(y_test, y_pred )f2 = fbeta_score(y_test, y_pred, beta=2.0)model_results = pd.DataFrame([['Decision Tree', acc, prec, rec, f1, f2]], columns = ['Model', 'Accuracy', 'Precision', 'Recall', 'F1 Score', 'F2 Score'])results = results.append(model_results, ignore_index = True)results = results.sort_values(["Precision", "Recall", "F2 Score"], ascending = False)print (results) Step 15.4.7. Random Forest: # Fitting Random Forest to the Training set: classifier = RandomForestClassifier(n_estimators = 72, criterion = 'entropy', random_state = 0)classifier.fit(X_train, y_train)# Predicting the Test set results y_pred = classifier.predict(X_test)#Evaluate resultsfrom sklearn.metrics import confusion_matrix, accuracy_score, f1_score, precision_score, recall_scoreacc = accuracy_score(y_test, y_pred )prec = precision_score(y_test, y_pred )rec = recall_score(y_test, y_pred )f1 = f1_score(y_test, y_pred )f2 = fbeta_score(y_test, y_pred, beta=2.0)model_results = pd.DataFrame([['Random Forest', acc, prec, rec, f1, f2]],columns = ['Model', 'Accuracy', 'Precision', 'Recall', 'F1 Score', 'F2 Score'])results = results.append(model_results, ignore_index = True)results = results.sort_values(["Precision", "Recall", "F2 Score"], ascending = False)print (results) From the 2nd iteration, we can definitely conclude that logistic regression is an optimal model of choice for the given dataset as it has relatively the highest combination of precision, recall and F2 scores; giving most number of correct positive predictions while minimizing the false negatives. Hence, let's try to use Logistic Regression and evaluate its performance in the forthcoming sections. Step 16: Train & evaluate Chosen Model: Let’s fit the selected model (Logistic Regression in this case) on the training dataset and evaluate the results. classifier = LogisticRegression(random_state = 0,penalty = 'l2')classifier.fit(X_train, y_train)# Predict the Test set resultsy_pred = classifier.predict(X_test)#Evaluate Model Results on Test Set:acc = accuracy_score(y_test, y_pred )prec = precision_score(y_test, y_pred )rec = recall_score(y_test, y_pred )f1 = f1_score(y_test, y_pred )f2 = fbeta_score(y_test, y_pred, beta=2.0)results = pd.DataFrame([['Logistic Regression',acc, prec, rec, f1, f2]],columns = ['Model', 'Accuracy', 'Precision', 'Recall', 'F1 Score', 'F2 Score'])print (results) k-Fold Cross-Validation: Model evaluation is most commonly done through ‘K- fold Cross-Validation’ technique that primarily helps us to fix the variance. Variance problem occurs when we get good accuracy while running the model on a training set and a test set but then the accuracy looks different when the model is run on another test set. So, in order to fix the variance problem, k-fold cross-validation basically split the training set into 10 folds and train the model on 9 folds (9 subsets of the training dataset) before testing it on the test fold. This gives us the flexibility to train our model on all ten combinations of 9 folds; giving ample room to finalize the variance. accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10)print("Logistic Regression Classifier Accuracy: %0.2f (+/- %0.2f)" % (accuracies.mean(), accuracies.std() * 2)) Therefore, our k-fold Cross Validation results indicate that we would have an accuracy anywhere between 76% to 84% while running this model on any test set. Visualize results on a Confusion Matrix: The Confusion matrix indicates that we have 208+924 correct predictions and 166+111 incorrect predictions. Accuracy rate = number of correct predictions/ total predictions * 100Error rate = Number of wrong predictions / total predictions * 100 We have got an accuracy of 80%; signalling the characteristics of a reasonably good model. cm = confusion_matrix(y_test, y_pred) df_cm = pd.DataFrame(cm, index = (0, 1), columns = (0, 1))plt.figure(figsize = (28,20))fig, ax = plt.subplots()sn.set(font_scale=1.4)sn.heatmap(df_cm, annot=True, fmt='g'#,cmap="YlGnBu" )class_names=[0,1]tick_marks = np.arange(len(class_names))plt.tight_layout()plt.title('Confusion matrix\n', y=1.1)plt.xticks(tick_marks, class_names)plt.yticks(tick_marks, class_names)ax.xaxis.set_label_position("top")plt.ylabel('Actual label\n')plt.xlabel('Predicted label\n') Evaluate the model using ROC Graph: It’s good to re-evaluate the model using ROC Graph. ROC Graph shows us the capability of a model to distinguish between the classes based on the AUC Mean score. The orange line represents the ROC curve of a random classifier while a good classifier tries to remain as far away from that line as possible. As shown in the graph below, the fine-tuned Logistic Regression model showcased a higher AUC score. classifier.fit(X_train, y_train) probs = classifier.predict_proba(X_test) probs = probs[:, 1] classifier_roc_auc = accuracy_score(y_test, y_pred )rf_fpr, rf_tpr, rf_thresholds = roc_curve(y_test, classifier.predict_proba(X_test)[:,1])plt.figure(figsize=(14, 6))# Plot Logistic Regression ROCplt.plot(rf_fpr, rf_tpr, label='Logistic Regression (area = %0.2f)' % classifier_roc_auc)# Plot Base Rate ROCplt.plot([0,1], [0,1],label='Base Rate' 'k--')plt.xlim([0.0, 1.0])plt.ylim([0.0, 1.05])plt.ylabel('True Positive Rate \n',horizontalalignment="center",fontstyle = "normal", fontsize = "medium", fontfamily = "sans-serif")plt.xlabel('\nFalse Positive Rate \n',horizontalalignment="center",fontstyle = "normal", fontsize = "medium", fontfamily = "sans-serif")plt.title('ROC Graph \n',horizontalalignment="center", fontstyle = "normal", fontsize = "22", fontfamily = "sans-serif")plt.legend(loc="lower right", fontsize = "medium")plt.xticks(rotation=0, horizontalalignment="center")plt.yticks(rotation=0, horizontalalignment="right")plt.show() Step 17:Predict Feature Importance: Logistic Regression allows us to determine the key features that have significance in predicting the target attribute (“Churn” in this project). The logistic regression model predicts that the churn rate would increase positively with month to month contract, optic fibre internet service, electronic checks, absence of payment security and tech support. On the other hand, the model predicts a negative correlation with churn if any customer has subscribed to online security, one-year contract or if they have opted for mailed checks as their payment medium. # Analyzing Coefficientsfeature_importances = pd.concat([pd.DataFrame(dataset.drop(columns = 'customerID').columns, columns = ["features"]),pd.DataFrame(np.transpose(classifier.coef_), columns = ["coef"])],axis = 1)feature_importances.sort_values("coef", ascending = False) Model improvement basically involves choosing the best parameters for the machine learning model that we have come up with. There are two types of parameters in any machine learning model — the first type are the kind of parameters that the model learns; the optimal values automatically found by running the model. The second type of parameters is the ones that user get to choose while running the model. Such parameters are called the hyperparameters; a set of configurable values external to a model that cannot be determined by the data, and that we are trying to optimize through Parameter Tuning techniques like Random Search or Grid Search. Hyperparameter tuning might not improve the model every time. For instance, when we tried to tune the model further, we ended up getting an accuracy score lower than the default one. I’m just demonstrating the steps involved in hyperparameter tuning here for future references. Step 18:Hyper parameter Tuning via Grid Search: # Round 1: # Select Regularization Method import timepenalty = ['l1', 'l2']# Create regularization hyperparameter spaceC = [0.001, 0.01, 0.1, 1, 10, 100, 1000]# Combine Parametersparameters = dict(C=C, penalty=penalty)lr_classifier = GridSearchCV(estimator = classifier, param_grid = parameters, scoring = "balanced_accuracy", cv = 10, n_jobs = -1)t0 = time.time()lr_classifier = lr_classifier .fit(X_train, y_train)t1 = time.time()print("Took %0.2f seconds" % (t1 - t0))lr_best_accuracy = lr_classifier.best_score_lr_best_parameters = lr_classifier.best_params_lr_best_accuracy, lr_best_parameters # Round 2:# Select Regularization Methodimport timepenalty = ['l2']# Create regularization hyperparameter spaceC = [ 0.0001, 0.001, 0.01, 0.02, 0.05]# Combine Parametersparameters = dict(C=C, penalty=penalty)lr_classifier = GridSearchCV(estimator = classifier, param_grid = parameters, scoring = "balanced_accuracy", cv = 10, n_jobs = -1)t0 = time.time()lr_classifier = lr_classifier .fit(X_train, y_train)t1 = time.time()print("Took %0.2f seconds" % (t1 - t0))lr_best_accuracy = lr_classifier.best_score_lr_best_parameters = lr_classifier.best_params_lr_best_accuracy, lr_best_parameters Step 18.2: Final Hyperparameter tuning and selection: lr_classifier = LogisticRegression(random_state = 0, penalty = 'l2')lr_classifier.fit(X_train, y_train)# Predict the Test set resultsy_pred = lr_classifier.predict(X_test)#probability scorey_pred_probs = lr_classifier.predict_proba(X_test)y_pred_probs = y_pred_probs [:, 1] Step 19: Compare predictions against the test set: #Revalidate final results with Confusion Matrix:cm = confusion_matrix(y_test, y_pred) print (cm)#Confusion Matrix as a quick Crosstab: pd.crosstab(y_test,pd.Series(y_pred),rownames=['ACTUAL'],colnames=['PRED'])#visualize Confusion Matrix:cm = confusion_matrix(y_test, y_pred) df_cm = pd.DataFrame(cm, index = (0, 1), columns = (0, 1))plt.figure(figsize = (28,20))fig, ax = plt.subplots()sn.set(font_scale=1.4)sn.heatmap(df_cm, annot=True, fmt='g'#,cmap="YlGnBu" )class_names=[0,1]tick_marks = np.arange(len(class_names))plt.tight_layout()plt.title('Confusion matrix\n', y=1.1)plt.xticks(tick_marks, class_names)plt.yticks(tick_marks, class_names)ax.xaxis.set_label_position("top")plt.ylabel('Actual label\n')plt.xlabel('Predicted label\n')print("Test Data Accuracy: %0.4f" % accuracy_score(y_test, y_pred)) Step 20: Format Final Results: Unpredictability and risk are the close companions of any predictive models. Therefore in the real world, its always a good practice to build a propensity score besides an absolute predicted outcome. Instead of just retrieving a binary estimated target outcome (0 or 1), every ‘Customer ID’ could get an additional layer of propensity score highlighting their percentage of probability to take the target action. final_results = pd.concat([test_identity, y_test], axis = 1).dropna()final_results['predictions'] = y_predfinal_results["propensity_to_churn(%)"] = y_pred_probsfinal_results["propensity_to_churn(%)"] = final_results["propensity_to_churn(%)"]*100final_results["propensity_to_churn(%)"]=final_results["propensity_to_churn(%)"].round(2)final_results = final_results[['customerID', 'Churn', 'predictions', 'propensity_to_churn(%)']]final_results ['Ranking'] = pd.qcut(final_results['propensity_to_churn(%)'].rank(method = 'first'),10,labels=range(10,0,-1))print (final_results) Lastly, deploy the model to a server using ‘joblib’ library so that we can productionize the end-to-end machine learning framework. Later we can run the model over any new dataset to predict the probability of any customer to churn in months to come. Step 21: Save the model: filename = 'final_model.model'i = [lr_classifier]joblib.dump(i,filename) Conclusion So, in a nutshell, we made use of a customer churn dataset from Kaggle to build a machine learning classifier that predicts the propensity of any customer to churn in months to come with a reasonable accuracy score of 76% to 84%. What’s Next? Share key insights about the customer demographics and churn rate that you have garnered from the exploratory data analysis sections to the sales and marketing team of the organization. Let the sales team know the features that have positive and negative correlations with churn so that they could strategize the retention initiatives accordingly. Further, classify the upcoming customers based on the propensity score as high risk (for customers with propensity score > 80%), medium risk (for customers with a propensity score between 60–80%) and lastly low-risk category (for customers with propensity score <60%). Focus on each segment of customers upfront and ensure that there needs are well taken care of. Lastly, measure the return on investment (ROI) of this assignment by computing the attrition rate for the current financial quarter. Compare the quarter results with the same quarter last year or the year before and share the outcome with the senior management of your organization. GitHub Repository I have learned (and continue to learn) from many folks in Github. Hence sharing my entire python script and supporting files in a public GitHub Repository in case if it benefits any seekers online. Also, feel free to reach out to me if you need any help in understanding the fundamentals of supervised machine learning algorithms in Python. Happy to share what I know:) Hope this helps! About the Author
[ { "code": null, "e": 596, "s": 172, "text": "Customer attrition (a.k.a customer churn) is one of the biggest expenditures of any organization. If we could figure out why a customer leaves and when they leave with reasonable accuracy, it would immensely help the organization to strategize their retention initiatives manifold. Let’s make use of a customer transaction dataset from Kaggle to understand the key steps involved in predicting customer attrition in Python." }, { "code": null, "e": 1068, "s": 596, "text": "Supervised Machine Learning is nothing but learning a function that maps an input to an output based on example input-output pairs. A supervised machine learning algorithm analyzes the training data and produces an inferred function, which can be used for mapping new examples. Given that we have data on current and prior customer transactions in the telecom dataset, this is a standardized supervised classification problem that tries to predict a binary outcome (Y/N)." }, { "code": null, "e": 1431, "s": 1068, "text": "By the end of this article, let’s attempt to solve some of the key business challenges pertaining to customer attrition like say, (1) what is the likelihood of an active customer leaving an organization? (2) what are key indicators of a customer churn? (3) what retention strategies can be implemented based on the results to diminish prospective customer churn?" }, { "code": null, "e": 1527, "s": 1431, "text": "In real-world, we need to go through seven major stages to successfully predict customer churn:" }, { "code": null, "e": 1557, "s": 1527, "text": "Section A: Data Preprocessing" }, { "code": null, "e": 1584, "s": 1557, "text": "Section B: Data Evaluation" }, { "code": null, "e": 1611, "s": 1584, "text": "Section C: Model Selection" }, { "code": null, "e": 1639, "s": 1611, "text": "Section D: Model Evaluation" }, { "code": null, "e": 1668, "s": 1639, "text": "Section E: Model Improvement" }, { "code": null, "e": 1698, "s": 1668, "text": "Section F: Future Predictions" }, { "code": null, "e": 1726, "s": 1698, "text": "Section G: Model Deployment" }, { "code": null, "e": 1993, "s": 1726, "text": "To understand the business challenge and the proposed solution, I would recommend you to download the dataset and to code with me. Feel free to ask me if you have any questions as you work along. Let’s look into each one of these aforesaid steps in detail here below" }, { "code": null, "e": 2323, "s": 1993, "text": "If you had asked the 20-year-old me, I would have jumped straight into model selection as its coolest thing to do in machine learning. But like in life, wisdom kicks in at a later stage! After witnessing the real-world Machine Learning business challenges, I can’t stress the importance of Data preprocessing and Data Evaluation." }, { "code": null, "e": 2390, "s": 2323, "text": "Always remember the following golden rule in predictive analytics:" }, { "code": null, "e": 2432, "s": 2390, "text": "“Your model is only as good as your data”" }, { "code": null, "e": 2580, "s": 2432, "text": "Understanding the end-to-end structure of your dataset and reshaping the variables is the gateway to a qualitative predictive modelling initiative." }, { "code": null, "e": 2828, "s": 2580, "text": "Step 0: Restart the session: It’s a good practice to restart the session and to remove all the temporary variables from the interactive development environment before we start coding. So let's restart the session, clear the cache and start afresh!" }, { "code": null, "e": 2950, "s": 2828, "text": "try: from IPython import get_ipython get_ipython().magic('clear') get_ipython().magic('reset -f')except: pass" }, { "code": null, "e": 3079, "s": 2950, "text": "Step 1: Import relevant libraries: Import all the relevant python libraries for building supervised machine learning algorithms." }, { "code": null, "e": 5616, "s": 3079, "text": "#Standard libraries for data analysis: import numpy as npimport matplotlib.pyplot as pltimport pandas as pdfrom scipy.stats import norm, skewfrom scipy import statsimport statsmodels.api as sm# sklearn modules for data preprocessing:from sklearn.impute import SimpleImputerfrom sklearn.preprocessing import LabelEncoder, OneHotEncoderfrom sklearn.compose import ColumnTransformerfrom sklearn.preprocessing import OneHotEncoderfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import StandardScaler#sklearn modules for Model Selection:from sklearn import svm, tree, linear_model, neighborsfrom sklearn import naive_bayes, ensemble, discriminant_analysis, gaussian_processfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysisfrom xgboost import XGBClassifierfrom sklearn.linear_model import LogisticRegressionfrom sklearn.svm import SVCfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.naive_bayes import GaussianNBfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.ensemble import RandomForestClassifier#sklearn modules for Model Evaluation & Improvement: from sklearn.metrics import confusion_matrix, accuracy_score from sklearn.metrics import f1_score, precision_score, recall_score, fbeta_scorefrom statsmodels.stats.outliers_influence import variance_inflation_factorfrom sklearn.model_selection import cross_val_scorefrom sklearn.model_selection import GridSearchCVfrom sklearn.model_selection import ShuffleSplitfrom sklearn.model_selection import KFoldfrom sklearn import feature_selectionfrom sklearn import model_selectionfrom sklearn import metricsfrom sklearn.metrics import classification_report, precision_recall_curvefrom sklearn.metrics import auc, roc_auc_score, roc_curvefrom sklearn.metrics import make_scorer, recall_score, log_lossfrom sklearn.metrics import average_precision_score#Standard libraries for data visualization:import seaborn as snfrom matplotlib import pyplotimport matplotlib.pyplot as pltimport matplotlib.pylab as pylabimport matplotlib %matplotlib inlinecolor = sn.color_palette()import matplotlib.ticker as mtickfrom IPython.display import displaypd.options.display.max_columns = Nonefrom pandas.plotting import scatter_matrixfrom sklearn.metrics import roc_curve#Miscellaneous Utilitiy Libraries: import randomimport osimport reimport sysimport timeitimport stringimport timefrom datetime import datetimefrom time import timefrom dateutil.parser import parseimport joblib" }, { "code": null, "e": 5662, "s": 5616, "text": "Step 2: Set up the current working directory:" }, { "code": null, "e": 5740, "s": 5662, "text": "os.chdir(r”C:/Users/srees/Propensity Scoring Models/Predict Customer Churn/”)" }, { "code": null, "e": 5856, "s": 5740, "text": "Step 3: Import the dataset: Let’s load the input dataset into the python notebook in the current working directory." }, { "code": null, "e": 5913, "s": 5856, "text": "dataset = pd.read_csv('1.Input/customer_churn_data.csv')" }, { "code": null, "e": 6122, "s": 5913, "text": "Step 4: Evaluate data structure: In this section, we need to look at the dataset in general and each column in detail to get a better understanding of the input data so as to aggregate the fields when needed." }, { "code": null, "e": 6341, "s": 6122, "text": "From the head & column methods, we get an idea that this is a telco customer churn dataset where each record entails the nature of subscription, tenure, frequency of payment and churn (signifying their current status)." }, { "code": null, "e": 6356, "s": 6341, "text": "dataset.head()" }, { "code": null, "e": 6372, "s": 6356, "text": "dataset.columns" }, { "code": null, "e": 6587, "s": 6372, "text": "A quick describe method reveals that the telecom customers are staying on average for 32 months and are paying $64 per month. However, this could potentially be because different customers have different contracts." }, { "code": null, "e": 6606, "s": 6587, "text": "dataset.describe()" }, { "code": null, "e": 6770, "s": 6606, "text": "From the look of it, we can presume that the dataset contains several numerical and categorical columns providing various information on the customer transactions." }, { "code": null, "e": 6785, "s": 6770, "text": "dataset.dtypes" }, { "code": null, "e": 7046, "s": 6785, "text": "Re-validate column data types and missing values: Always keep an eye onto the missing values in a dataset. The missing values could mess up model building and accuracy. Hence we need to take care of missing values (if any) before we compare and select a model." }, { "code": null, "e": 7105, "s": 7046, "text": "dataset.columns.to_series().groupby(dataset.dtypes).groups" }, { "code": null, "e": 7206, "s": 7105, "text": "The dataset contains 7043 rows and 21 columns and there seem to be no missing values in the dataset." }, { "code": null, "e": 7221, "s": 7206, "text": "dataset.info()" }, { "code": null, "e": 7242, "s": 7221, "text": "dataset.isna().any()" }, { "code": null, "e": 7624, "s": 7242, "text": "Identify unique values: ‘Payment Methods’ and ‘Contract’ are the two categorical variables in the dataset. When we look into the unique values in each categorical variables, we get an insight that the customers are either on a month-to-month rolling contract or on a fixed contract for one/two years. Also, they are paying bills via credit card, bank transfer or electronic checks." }, { "code": null, "e": 7793, "s": 7624, "text": "#Unique values in each categorical variable:dataset[\"PaymentMethod\"].nunique()dataset[\"PaymentMethod\"].unique()dataset[\"Contract\"].nunique()dataset[\"Contract\"].unique()" }, { "code": null, "e": 8115, "s": 7793, "text": "Step 5: Check target variable distribution: Let’s look at the distribution of churn values. This is quite a simple yet crucial step to see if the dataset upholds any class imbalance issues. As you can see below, the data set is imbalanced with a high proportion of active customers compared to their churned counterparts." }, { "code": null, "e": 8147, "s": 8115, "text": "dataset[\"Churn\"].value_counts()" }, { "code": null, "e": 8174, "s": 8147, "text": "Step 6: Clean the dataset:" }, { "code": null, "e": 8320, "s": 8174, "text": "dataset['TotalCharges'] = pd.to_numeric(dataset['TotalCharges'],errors='coerce')dataset['TotalCharges'] = dataset['TotalCharges'].astype(\"float\")" }, { "code": null, "e": 8541, "s": 8320, "text": "Step 7: Take care of missing data: As we saw earlier, the data provided has no missing values and hence this step is not required for the chosen dataset. I would like to showcase the steps here for any future references." }, { "code": null, "e": 8556, "s": 8541, "text": "dataset.info()" }, { "code": null, "e": 8577, "s": 8556, "text": "dataset.isna().any()" }, { "code": null, "e": 8859, "s": 8577, "text": "Find the average and fill missing values programmatically: If we had any missing values in the numeric columns of the dataset, then we should find the average of each one of those columns and fill their missing values. Here’s a snippet of code to do the same step programmatically." }, { "code": null, "e": 9147, "s": 8859, "text": "na_cols = dataset.isna().any()na_cols = na_cols[na_cols == True].reset_index()na_cols = na_cols[\"index\"].tolist()for col in dataset.columns[1:]: if col in na_cols: if dataset[col].dtype != 'object': dataset[col] = dataset[col].fillna(dataset[col].mean()).round(0)" }, { "code": null, "e": 9273, "s": 9147, "text": "Revalidate NA’s: It’s always a good practice to revalidate and ensure that we don’t have any more null values in the dataset." }, { "code": null, "e": 9294, "s": 9273, "text": "dataset.isna().any()" }, { "code": null, "e": 9764, "s": 9294, "text": "Step 8: Label Encode Binary data: Machine Learning algorithms can typically only have numerical values as their independent variables. Hence label encoding is quite pivotal as they encode categorical labels with appropriate numerical values. Here we are label encoding all categorical variables that have only two unique values. Any categorical variable that has more than two unique values are dealt with Label Encoding and one-hot Encoding in the subsequent sections." }, { "code": null, "e": 10180, "s": 9764, "text": "#Create a label encoder objectle = LabelEncoder()# Label Encoding will be used for columns with 2 or less unique valuesle_count = 0for col in dataset.columns[1:]: if dataset[col].dtype == 'object': if len(list(dataset[col].unique())) <= 2: le.fit(dataset[col]) dataset[col] = le.transform(dataset[col]) le_count += 1print('{} columns were label encoded.'.format(le_count))" }, { "code": null, "e": 10397, "s": 10180, "text": "Step 9: Exploratory Data Analysis: Let’s try to explore and visualize our data set by doing distribution of independent variables to better understand the patterns in the data and to potentially form some hypothesis." }, { "code": null, "e": 10442, "s": 10397, "text": "Step 9.1. Plot histogram of numeric Columns:" }, { "code": null, "e": 11089, "s": 10442, "text": "dataset2 = dataset[['gender', 'SeniorCitizen', 'Partner','Dependents','tenure', 'PhoneService', 'PaperlessBilling','MonthlyCharges', 'TotalCharges']]#Histogram: fig = plt.figure(figsize=(15, 12))plt.suptitle('Histograms of Numerical Columns\\n',horizontalalignment=\"center\",fontstyle = \"normal\", fontsize = 24, fontfamily = \"sans-serif\")for i in range(dataset2.shape[1]): plt.subplot(6, 3, i + 1) f = plt.gca() f.set_title(dataset2.columns.values[i])vals = np.size(dataset2.iloc[:, i].unique()) if vals >= 100: vals = 100 plt.hist(dataset2.iloc[:, i], bins=vals, color = '#ec838a')plt.tight_layout(rect=[0, 0.03, 1, 0.95])" }, { "code": null, "e": 11169, "s": 11089, "text": "A few observations can be made based on the histograms for numerical variables:" }, { "code": null, "e": 11368, "s": 11169, "text": "Gender distribution shows that the dataset features a relatively equal proportion of male and female customers. Almost half of the customers in our dataset are female whilst the other half are male." }, { "code": null, "e": 11425, "s": 11368, "text": "Most of the customers in the dataset are younger people." }, { "code": null, "e": 11520, "s": 11425, "text": "Not many customers seem to have dependents whilst almost half of the customers have a partner." }, { "code": null, "e": 11683, "s": 11520, "text": "There are a lot of new customers in the organization (less than 10 months old) followed by a loyal customer segment that stays for more than 70 months on average." }, { "code": null, "e": 11783, "s": 11683, "text": "Most of the customers seem to have phone service and 3/4th of them have opted for paperless Billing" }, { "code": null, "e": 11898, "s": 11783, "text": "Monthly charges span anywhere between $18 to $118 per customer with a huge proportion of customers on $20 segment." }, { "code": null, "e": 11959, "s": 11898, "text": "Step 9.2. Analyze the distribution of categorical variables:" }, { "code": null, "e": 12189, "s": 11959, "text": "9.2.1. Distribution of contract type: Most of the customers seem to have a prepaid connection with the telecom company. On the other hand, there are a more or less equal proportion of customers in the 1-year and 2-year contracts." }, { "code": null, "e": 13891, "s": 12189, "text": "contract_split = dataset[[ \"customerID\", \"Contract\"]]sectors = contract_split .groupby (\"Contract\")contract_split = pd.DataFrame(sectors[\"customerID\"].count())contract_split.rename(columns={'customerID':'No. of customers'}, inplace=True)ax = contract_split[[\"No. of customers\"]].plot.bar(title = 'Customers by Contract Type',legend =True, table = False, grid = False, subplots = False,figsize =(12, 7), color ='#ec838a', fontsize = 15, stacked=False)plt.ylabel('No. of Customers\\n',horizontalalignment=\"center\",fontstyle = \"normal\", fontsize = \"large\", fontfamily = \"sans-serif\")plt.xlabel('\\n Contract Type',horizontalalignment=\"center\",fontstyle = \"normal\", fontsize = \"large\", fontfamily = \"sans-serif\")plt.title('Customers by Contract Type \\n',horizontalalignment=\"center\",fontstyle = \"normal\", fontsize = \"22\", fontfamily = \"sans-serif\")plt.legend(loc='top right', fontsize = \"medium\")plt.xticks(rotation=0, horizontalalignment=\"center\")plt.yticks(rotation=0, horizontalalignment=\"right\")x_labels = np.array(contract_split[[\"No. of customers\"]])def add_value_labels(ax, spacing=5): for rect in ax.patches: y_value = rect.get_height() x_value = rect.get_x() + rect.get_width() / 2 space = spacing va = 'bottom' if y_value < 0: space *= -1 va = 'top' label = \"{:.0f}\".format(y_value) ax.annotate( label, (x_value, y_value), xytext=(0, space), textcoords=\"offset points\", ha='center', va=va) add_value_labels(ax)" }, { "code": null, "e": 14080, "s": 13891, "text": "9.2.2. Distribution of payment method type: The dataset indicates that customers prefer to pay their bills electronically the most followed by bank transfer, credit card and mailed checks." }, { "code": null, "e": 15732, "s": 14080, "text": "payment_method_split = dataset[[ \"customerID\", \"PaymentMethod\"]]sectors = payment_method_split .groupby (\"PaymentMethod\")payment_method_split = pd.DataFrame(sectors[\"customerID\"].count())payment_method_split.rename(columns={'customerID':'No. of customers'}, inplace=True)ax = payment_method_split [[\"No. of customers\"]].plot.bar(title = 'Customers by Payment Method', legend =True, table = False, grid = False, subplots = False, figsize =(15, 10),color ='#ec838a', fontsize = 15, stacked=False)plt.ylabel('No. of Customers\\n',horizontalalignment=\"center\",fontstyle = \"normal\", fontsize = \"large\", fontfamily = \"sans-serif\")plt.xlabel('\\n Contract Type',horizontalalignment=\"center\",fontstyle = \"normal\", fontsize = \"large\", fontfamily = \"sans-serif\")plt.title('Customers by Payment Method \\n',horizontalalignment=\"center\", fontstyle = \"normal\", fontsize = \"22\", fontfamily = \"sans-serif\")plt.legend(loc='top right', fontsize = \"medium\")plt.xticks(rotation=0, horizontalalignment=\"center\")plt.yticks(rotation=0, horizontalalignment=\"right\")x_labels = np.array(payment_method_split [[\"No. of customers\"]])def add_value_labels(ax, spacing=5): for rect in ax.patches: y_value = rect.get_height() x_value = rect.get_x() + rect.get_width() / 2 space = spacing va = 'bottom' if y_value < 0: space *= -1 va = 'top' label = \"{:.0f}\".format(y_value) ax.annotate(label, (x_value, y_value), xytext=(0, space),textcoords=\"offset points\", ha='center',va=va)add_value_labels(ax)" }, { "code": null, "e": 15792, "s": 15732, "text": "9.2.3. Distribution of label encoded categorical variables:" }, { "code": null, "e": 16450, "s": 15792, "text": "services= ['PhoneService','MultipleLines','InternetService','OnlineSecurity', 'OnlineBackup','DeviceProtection','TechSupport','StreamingTV','StreamingMovies']fig, axes = plt.subplots(nrows = 3,ncols = 3,figsize = (15,12))for i, item in enumerate(services): if i < 3: ax = dataset[item].value_counts().plot( kind = 'bar',ax=axes[i,0], rot = 0, color ='#f3babc' ) elif i >=3 and i < 6: ax = dataset[item].value_counts().plot( kind = 'bar',ax=axes[i-3,1], rot = 0,color ='#9b9c9a') elif i < 9: ax = dataset[item].value_counts().plot( kind = 'bar',ax=axes[i-6,2],rot = 0, color = '#ec838a')ax.set_title(item)" }, { "code": null, "e": 16554, "s": 16450, "text": "Most of the customers have phone service out of which almost half of the customers have multiple lines." }, { "code": null, "e": 16724, "s": 16554, "text": "3/4th of the customers have opted for internet service via Fiber Optic and DSL connections with almost half of the internet users subscribing to streaming TV and movies." }, { "code": null, "e": 16848, "s": 16724, "text": "Customers who have availed Online Backup, Device Protection, Technical Support and Online Security features are a minority." }, { "code": null, "e": 16907, "s": 16848, "text": "Step 9.3: Analyze the churn rate by categorical variables:" }, { "code": null, "e": 17310, "s": 16907, "text": "9.3.1. Overall churn rate: A preliminary look at the overall churn rate shows that around 74% of the customers are active. As shown in the chart below, this is an imbalanced classification problem. Machine learning algorithms work well when the number of instances of each class is roughly equal. Since the dataset is skewed, we need to keep that in mind while choosing the metrics for model selection." }, { "code": null, "e": 19122, "s": 17310, "text": "import matplotlib.ticker as mtickchurn_rate = dataset[[\"Churn\", \"customerID\"]]churn_rate [\"churn_label\"] = pd.Series(np.where((churn_rate[\"Churn\"] == 0), \"No\", \"Yes\"))sectors = churn_rate .groupby (\"churn_label\")churn_rate = pd.DataFrame(sectors[\"customerID\"].count())churn_rate [\"Churn Rate\"] = (churn_rate [\"customerID\"]/ sum(churn_rate [\"customerID\"]) )*100ax = churn_rate[[\"Churn Rate\"]].plot.bar(title = 'Overall Churn Rate',legend =True, table = False,grid = False, subplots = False, figsize =(12, 7), color = '#ec838a', fontsize = 15, stacked=False, ylim =(0,100))plt.ylabel('Proportion of Customers',horizontalalignment=\"center\",fontstyle = \"normal\", fontsize = \"large\", fontfamily = \"sans-serif\")plt.xlabel('Churn',horizontalalignment=\"center\",fontstyle = \"normal\", fontsize = \"large\", fontfamily = \"sans-serif\")plt.title('Overall Churn Rate \\n',horizontalalignment=\"center\", fontstyle = \"normal\", fontsize = \"22\", fontfamily = \"sans-serif\")plt.legend(loc='top right', fontsize = \"medium\")plt.xticks(rotation=0, horizontalalignment=\"center\")plt.yticks(rotation=0, horizontalalignment=\"right\")ax.yaxis.set_major_formatter(mtick.PercentFormatter())x_labels = np.array(churn_rate[[\"customerID\"]])def add_value_labels(ax, spacing=5): for rect in ax.patches: y_value = rect.get_height() x_value = rect.get_x() + rect.get_width() / 2 space = spacing va = 'bottom' if y_value < 0: space *= -1 va = 'top' label = \"{:.1f}%\".format(y_value) ax.annotate(label, (x_value, y_value), xytext=(0, space), textcoords=\"offset points\", ha='center',va=va)add_value_labels(ax)ax.autoscale(enable=False, axis='both', tight=False)" }, { "code": null, "e": 19310, "s": 19122, "text": "9.3.2. Churn Rate by Contract Type: Customers with a prepaid or rather a month-to-month connection have a very high probability to churn compared to their peers on 1 or 2 years contracts." }, { "code": null, "e": 20561, "s": 19310, "text": "import matplotlib.ticker as mtickcontract_churn =dataset.groupby(['Contract','Churn']).size().unstack()contract_churn.rename(columns={0:'No', 1:'Yes'}, inplace=True)colors = ['#ec838a','#9b9c9a']ax = (contract_churn.T*100.0 / contract_churn.T.sum()).T.plot(kind='bar',width = 0.3,stacked = True,rot = 0,figsize = (12,7),color = colors)plt.ylabel('Proportion of Customers\\n',horizontalalignment=\"center\",fontstyle = \"normal\", fontsize = \"large\", fontfamily = \"sans-serif\")plt.xlabel('Contract Type\\n',horizontalalignment=\"center\",fontstyle = \"normal\", fontsize = \"large\", fontfamily = \"sans-serif\")plt.title('Churn Rate by Contract type \\n',horizontalalignment=\"center\", fontstyle = \"normal\", fontsize = \"22\", fontfamily = \"sans-serif\")plt.legend(loc='top right', fontsize = \"medium\")plt.xticks(rotation=0, horizontalalignment=\"center\")plt.yticks(rotation=0, horizontalalignment=\"right\")ax.yaxis.set_major_formatter(mtick.PercentFormatter())for p in ax.patches: width, height = p.get_width(), p.get_height() x, y = p.get_xy() ax.text(x+width/2, y+height/2, '{:.1f}%'.format(height), horizontalalignment='center', verticalalignment='center')ax.autoscale(enable=False, axis='both', tight=False)" }, { "code": null, "e": 20714, "s": 20561, "text": "9.3.3. Churn Rate by Payment Method Type: Customers who pay via bank transfers seem to have the lowest churn rate among all the payment method segments." }, { "code": null, "e": 21997, "s": 20714, "text": "import matplotlib.ticker as mtickcontract_churn = dataset.groupby(['Contract','PaymentMethod']).size().unstack()contract_churn.rename(columns={0:'No', 1:'Yes'}, inplace=True)colors = ['#ec838a','#9b9c9a', '#f3babc' , '#4d4f4c']ax = (contract_churn.T*100.0 / contract_churn.T.sum()).T.plot(kind='bar',width = 0.3,stacked = True,rot = 0,figsize = (12,7),color = colors)plt.ylabel('Proportion of Customers\\n',horizontalalignment=\"center\",fontstyle = \"normal\", fontsize = \"large\", fontfamily = \"sans-serif\")plt.xlabel('Contract Type\\n',horizontalalignment=\"center\",fontstyle = \"normal\", fontsize = \"large\", fontfamily = \"sans-serif\")plt.title('Churn Rate by Payment Method \\n',horizontalalignment=\"center\", fontstyle = \"normal\", fontsize = \"22\", fontfamily = \"sans-serif\")plt.legend(loc='top right', fontsize = \"medium\")plt.xticks(rotation=0, horizontalalignment=\"center\")plt.yticks(rotation=0, horizontalalignment=\"right\")ax.yaxis.set_major_formatter(mtick.PercentFormatter())for p in ax.patches: width, height = p.get_width(), p.get_height() x, y = p.get_xy() ax.text(x+width/2, y+height/2, '{:.1f}%'.format(height), horizontalalignment='center', verticalalignment='center')ax.autoscale(enable=False, axis='both', tight=False" }, { "code": null, "e": 22293, "s": 21997, "text": "Step 9.4. Find positive and negative correlations: Interestingly, the churn rate increases with monthly charges and age. In contrast Partner, Dependents and Tenure seem to be negatively related to churn. Let’s have a look into the positive and negative correlations graphically in the next step." }, { "code": null, "e": 22832, "s": 22293, "text": "dataset2 = dataset[['SeniorCitizen', 'Partner', 'Dependents', 'tenure', 'PhoneService', 'PaperlessBilling', 'MonthlyCharges', 'TotalCharges']]correlations = dataset2.corrwith(dataset.Churn)correlations = correlations[correlations!=1]positive_correlations = correlations[correlations >0].sort_values(ascending = False)negative_correlations =correlations[correlations<0].sort_values(ascending = False)print('Most Positive Correlations: \\n', positive_correlations)print('\\nMost Negative Correlations: \\n', negative_correlations)" }, { "code": null, "e": 22881, "s": 22832, "text": "Step 9.5. Plot positive & negative correlations:" }, { "code": null, "e": 23240, "s": 22881, "text": "correlations = dataset2.corrwith(dataset.Churn)correlations = correlations[correlations!=1]correlations.plot.bar( figsize = (18, 10), fontsize = 15, color = '#ec838a', rot = 45, grid = True)plt.title('Correlation with Churn Rate \\n',horizontalalignment=\"center\", fontstyle = \"normal\", fontsize = \"22\", fontfamily = \"sans-serif\")" }, { "code": null, "e": 23415, "s": 23240, "text": "Step 9.6. Plot Correlation Matrix of all independent variables: Correlation matrix helps us to discover the bivariate relationship between independent variables in a dataset." }, { "code": null, "e": 23928, "s": 23415, "text": "#Set and compute the Correlation Matrix:sn.set(style=\"white\")corr = dataset2.corr()#Generate a mask for the upper triangle:mask = np.zeros_like(corr, dtype=np.bool)mask[np.triu_indices_from(mask)] = True#Set up the matplotlib figure and a diverging colormap:f, ax = plt.subplots(figsize=(18, 15))cmap = sn.diverging_palette(220, 10, as_cmap=True)#Draw the heatmap with the mask and correct aspect ratio:sn.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0,square=True, linewidths=.5, cbar_kws={\"shrink\": .5})" }, { "code": null, "e": 24318, "s": 23928, "text": "Step 9.7: Check Multicollinearity using VIF: Let's try to look into multicollinearity using Variable Inflation Factors (VIF). Unlike Correlation matrix, VIF determines the strength of the correlation of a variable with a group of other independent variables in a dataset. VIF starts usually at 1 and anywhere exceeding 10 indicates high multicollinearity between the independent variables." }, { "code": null, "e": 24673, "s": 24318, "text": "def calc_vif(X):# Calculating VIF vif = pd.DataFrame() vif[\"variables\"] = X.columns vif[\"VIF\"] = [variance_inflation_factor(X.values, i) for i in range(X.shape[1])]return(vif)dataset2 = dataset[['gender', 'SeniorCitizen', 'Partner', 'Dependents','tenure', 'PhoneService','PaperlessBilling','MonthlyCharges','TotalCharges']]calc_vif(dataset2)" }, { "code": null, "e": 24759, "s": 24673, "text": "We can see here that the ‘Monthly Charges’ and ‘Total Charges’ have a high VIF value." }, { "code": null, "e": 25138, "s": 24759, "text": "'Total Charges' seem to be collinear with 'Monthly Charges'.#Check colinearity: dataset2[['MonthlyCharges', 'TotalCharges']].plot.scatter(figsize = (15, 10), x ='MonthlyCharges',y='TotalCharges', color = '#ec838a')plt.title('Collinearity of Monthly Charges and Total Charges \\n',horizontalalignment=\"center\", fontstyle = \"normal\", fontsize = \"22\", fontfamily = \"sans-serif\")" }, { "code": null, "e": 25276, "s": 25138, "text": "Let’s try to drop one of the correlated features to see if it help us in bringing down the multicollinearity between correlated features:" }, { "code": null, "e": 25622, "s": 25276, "text": "#Dropping 'TotalCharges': dataset2 = dataset2.drop(columns = \"TotalCharges\")#Revalidate Colinearity:dataset2 = dataset[['gender', 'SeniorCitizen', 'Partner', 'Dependents','tenure', 'PhoneService', 'PaperlessBilling','MonthlyCharges']]calc_vif(dataset2)#Applying changes in the main dataset: dataset = dataset.drop(columns = \"TotalCharges\")" }, { "code": null, "e": 25769, "s": 25622, "text": "In our example, after dropping the ‘Total Charges’ variable, VIF values for all the independent variables have decreased to a considerable extent." }, { "code": null, "e": 25815, "s": 25769, "text": "Exploratory Data Analysis Concluding Remarks:" }, { "code": null, "e": 25878, "s": 25815, "text": "Let’s try to summarise some of the key findings from this EDA:" }, { "code": null, "e": 25942, "s": 25878, "text": "The dataset does not have any missing or erroneous data values." }, { "code": null, "e": 26093, "s": 25942, "text": "Strongest positive correlation with the target features is Monthly Charges and Age whilst negative correlation is with Partner, Dependents and Tenure." }, { "code": null, "e": 26164, "s": 26093, "text": "The dataset is imbalanced with the majority of customers being active." }, { "code": null, "e": 26301, "s": 26164, "text": "There is multicollinearity between Monthly Charges and Total Charges. Dropping Total Charges have decreased the VIF values considerably." }, { "code": null, "e": 26358, "s": 26301, "text": "Most of the customers in the dataset are younger people." }, { "code": null, "e": 26499, "s": 26358, "text": "There are a lot of new customers in the organization (less than 10 months old) followed by a loyal customer base that’s above 70 months old." }, { "code": null, "e": 26612, "s": 26499, "text": "Most of the customers seem to have phone service with Monthly charges spanning between $18 to $118 per customer." }, { "code": null, "e": 26756, "s": 26612, "text": "Customers with a month-to-month connection have a very high probability to churn that too if they have subscribed to pay via electronic checks." }, { "code": null, "e": 26950, "s": 26756, "text": "Step 10: Encode Categorical data: Any categorical variable that has more than two unique values have been dealt with Label Encoding and one-hot Encoding using get_dummies method in pandas here." }, { "code": null, "e": 27220, "s": 26950, "text": "#Incase if user_id is an object: identity = dataset[\"customerID\"]dataset = dataset.drop(columns=\"customerID\")#Convert rest of categorical variable into dummy:dataset= pd.get_dummies(dataset)#Rejoin userid to dataset:dataset = pd.concat([dataset, identity], axis = 1)" }, { "code": null, "e": 27454, "s": 27220, "text": "Step 11: Split the dataset into dependent and independent variables: Now we need to separate the dataset into X and y values. y would be the ‘Churn’ column whilst X would be the remaining list of independent variables in the dataset." }, { "code": null, "e": 27553, "s": 27454, "text": "#Identify response variable: response = dataset[\"Churn\"]dataset = dataset.drop(columns=\"Churn\")" }, { "code": null, "e": 27683, "s": 27553, "text": "Step 12: Generate training and test datasets: Let’s decouple the master dataset into training and test set with an 80%-20% ratio." }, { "code": null, "e": 28129, "s": 27683, "text": "X_train, X_test, y_train, y_test = train_test_split(dataset, response,stratify=response, test_size = 0.2, #use 0.9 if data is huge.random_state = 0)#to resolve any class imbalance - use stratify parameter.print(\"Number transactions X_train dataset: \", X_train.shape)print(\"Number transactions y_train dataset: \", y_train.shape)print(\"Number transactions X_test dataset: \", X_test.shape)print(\"Number transactions y_test dataset: \", y_test.shape)" }, { "code": null, "e": 28216, "s": 28129, "text": "Step 13: Remove Identifiers: Separate ‘customerID’ from training and test data frames." }, { "code": null, "e": 28385, "s": 28216, "text": "train_identity = X_train['customerID']X_train = X_train.drop(columns = ['customerID'])test_identity = X_test['customerID']X_test = X_test.drop(columns = ['customerID'])" }, { "code": null, "e": 28615, "s": 28385, "text": "Step 14: Conduct Feature Scaling: It’s quite important to normalize the variables before conducting any machine learning (classification) algorithms so that all the training and test variables are scaled within a range of 0 to 1." }, { "code": null, "e": 28923, "s": 28615, "text": "sc_X = StandardScaler()X_train2 = pd.DataFrame(sc_X.fit_transform(X_train))X_train2.columns = X_train.columns.valuesX_train2.index = X_train.index.valuesX_train = X_train2X_test2 = pd.DataFrame(sc_X.transform(X_test))X_test2.columns = X_test.columns.valuesX_test2.index = X_test.index.valuesX_test = X_test2" }, { "code": null, "e": 29121, "s": 28923, "text": "Step 15.1: Compare Baseline Classification Algorithms (1st Iteration): Let’s model each classification algorithm over the training dataset and evaluate their accuracy and standard deviation scores." }, { "code": null, "e": 29543, "s": 29121, "text": "Classification Accuracy is one of the most common classification evaluation metrics to compare baseline algorithms as its the number of correct predictions made as a ratio of total predictions. However, it's not the ideal metric when we have class imbalance issue. Hence, let us sort the results based on the ‘Mean AUC’ value which is nothing but the model’s ability to discriminate between positive and negative classes." }, { "code": null, "e": 31365, "s": 29543, "text": "models = []models.append(('Logistic Regression', LogisticRegression(solver='liblinear', random_state = 0, class_weight='balanced')))models.append(('SVC', SVC(kernel = 'linear', random_state = 0)))models.append(('Kernel SVM', SVC(kernel = 'rbf', random_state = 0)))models.append(('KNN', KNeighborsClassifier(n_neighbors = 5, metric = 'minkowski', p = 2)))models.append(('Gaussian NB', GaussianNB()))models.append(('Decision Tree Classifier', DecisionTreeClassifier(criterion = 'entropy', random_state = 0)))models.append(('Random Forest', RandomForestClassifier( n_estimators=100, criterion = 'entropy', random_state = 0)))#Evaluating Model Results:acc_results = []auc_results = []names = []# set table to table to populate with performance resultscol = ['Algorithm', 'ROC AUC Mean', 'ROC AUC STD', 'Accuracy Mean', 'Accuracy STD']model_results = pd.DataFrame(columns=col)i = 0# Evaluate each model using k-fold cross-validation:for name, model in models: kfold = model_selection.KFold( n_splits=10, random_state=0)# accuracy scoring:cv_acc_results = model_selection.cross_val_score( model, X_train, y_train, cv=kfold, scoring='accuracy')# roc_auc scoring:cv_auc_results = model_selection.cross_val_score( model, X_train, y_train, cv=kfold, scoring='roc_auc')acc_results.append(cv_acc_results) auc_results.append(cv_auc_results) names.append(name) model_results.loc[i] = [name, round(cv_auc_results.mean()*100, 2), round(cv_auc_results.std()*100, 2), round(cv_acc_results.mean()*100, 2), round(cv_acc_results.std()*100, 2) ] i += 1 model_results.sort_values(by=['ROC AUC Mean'], ascending=False)" }, { "code": null, "e": 31434, "s": 31365, "text": "Step 15.2. Visualize Classification Algorithms Accuracy Comparisons:" }, { "code": null, "e": 31455, "s": 31434, "text": "Using Accuracy Mean:" }, { "code": null, "e": 32139, "s": 31455, "text": "fig = plt.figure(figsize=(15, 7))ax = fig.add_subplot(111)plt.boxplot(acc_results)ax.set_xticklabels(names)#plt.ylabel('ROC AUC Score\\n',horizontalalignment=\"center\",fontstyle = \"normal\", fontsize = \"large\", fontfamily = \"sans-serif\")#plt.xlabel('\\n Baseline Classification Algorithms\\n',horizontalalignment=\"center\",fontstyle = \"normal\", fontsize = \"large\", fontfamily = \"sans-serif\")plt.title('Accuracy Score Comparison \\n',horizontalalignment=\"center\", fontstyle = \"normal\", fontsize = \"22\", fontfamily = \"sans-serif\")#plt.legend(loc='top right', fontsize = \"medium\")plt.xticks(rotation=0, horizontalalignment=\"center\")plt.yticks(rotation=0, horizontalalignment=\"right\")plt.show()" }, { "code": null, "e": 32452, "s": 32139, "text": "Using Area under ROC Curve: From the first iteration of baseline classification algorithms, we can see that Logistic Regression and SVC have outperformed the other five models for the chosen dataset with the highest mean AUC Scores. Let’s reconfirm our results in the second iteration as shown in the next steps." }, { "code": null, "e": 33128, "s": 32452, "text": "fig = plt.figure(figsize=(15, 7))ax = fig.add_subplot(111)plt.boxplot(auc_results)ax.set_xticklabels(names)#plt.ylabel('ROC AUC Score\\n',horizontalalignment=\"center\",fontstyle = \"normal\",fontsize = \"large\", fontfamily = \"sans-serif\")#plt.xlabel('\\n Baseline Classification Algorithms\\n',horizontalalignment=\"center\",fontstyle = \"normal\", fontsize = \"large\", fontfamily = \"sans-serif\")plt.title('ROC AUC Comparison \\n',horizontalalignment=\"center\", fontstyle = \"normal\", fontsize = \"22\", fontfamily = \"sans-serif\")#plt.legend(loc='top right', fontsize = \"medium\")plt.xticks(rotation=0, horizontalalignment=\"center\")plt.yticks(rotation=0, horizontalalignment=\"right\")plt.show()" }, { "code": null, "e": 33311, "s": 33128, "text": "Step 15.3. Get the right parameters for the baseline models: Before doing the second iteration, let’s optimize the parameters and finalize the evaluation metrics for model selection." }, { "code": null, "e": 33713, "s": 33311, "text": "Identify the optimal number of K neighbors for KNN Model: In the first iteration, we assumed that K = 3, but in reality, we don’t know what is the optimal K value that gives maximum accuracy for the chosen training dataset. Therefore, let us write a for loop that iterates 20 to 30 times and gives the accuracy at each iteration so as to figure out the optimal number of K neighbors for the KNN Model." }, { "code": null, "e": 34539, "s": 33713, "text": "score_array = []for each in range(1,25): knn_loop = KNeighborsClassifier(n_neighbors = each) #set K neighbor as 3 knn_loop.fit(X_train,y_train) score_array.append(knn_loop.score(X_test,y_test))fig = plt.figure(figsize=(15, 7))plt.plot(range(1,25),score_array, color = '#ec838a')plt.ylabel('Range\\n',horizontalalignment=\"center\",fontstyle = \"normal\", fontsize = \"large\", fontfamily = \"sans-serif\")plt.xlabel('Score\\n',horizontalalignment=\"center\",fontstyle = \"normal\", fontsize = \"large\", fontfamily = \"sans-serif\")plt.title('Optimal Number of K Neighbors \\n',horizontalalignment=\"center\", fontstyle = \"normal\", fontsize = \"22\", fontfamily = \"sans-serif\")#plt.legend(loc='top right', fontsize = \"medium\")plt.xticks(rotation=0, horizontalalignment=\"center\")plt.yticks(rotation=0, horizontalalignment=\"right\")plt.show()" }, { "code": null, "e": 34641, "s": 34539, "text": "As we can see from the above iterations, if we use K = 22, then we will get the maximum score of 78%." }, { "code": null, "e": 34852, "s": 34641, "text": "Identify the optimal number of trees for Random Forest Model: Quite similar to the iterations in the KNN model, here we are trying to find the optimal number of decision trees to compose the best random forest." }, { "code": null, "e": 35697, "s": 34852, "text": "score_array = []for each in range(1,100): rf_loop = RandomForestClassifier(n_estimators = each, random_state = 1) rf_loop.fit(X_train,y_train) score_array.append(rf_loop.score(X_test,y_test)) fig = plt.figure(figsize=(15, 7))plt.plot(range(1,100),score_array, color = '#ec838a')plt.ylabel('Range\\n',horizontalalignment=\"center\",fontstyle = \"normal\", fontsize = \"large\", fontfamily = \"sans-serif\")plt.xlabel('Score\\n',horizontalalignment=\"center\",fontstyle = \"normal\", fontsize = \"large\", fontfamily = \"sans-serif\")plt.title('Optimal Number of Trees for Random Forest Model \\n',horizontalalignment=\"center\", fontstyle = \"normal\", fontsize = \"22\", fontfamily = \"sans-serif\")#plt.legend(loc='top right', fontsize = \"medium\")plt.xticks(rotation=0, horizontalalignment=\"center\")plt.yticks(rotation=0, horizontalalignment=\"right\")plt.show()" }, { "code": null, "e": 35832, "s": 35697, "text": "As we could see from the iterations above, the random forest model would attain the highest accuracy score when its n_estimators = 72." }, { "code": null, "e": 35903, "s": 35832, "text": "Step 15.4. Compare Baseline Classification Algorithms (2nd Iteration):" }, { "code": null, "e": 36233, "s": 35903, "text": "In the second iteration of comparing baseline classification algorithms, we would be using the optimised parameters for KNN and Random Forest models. Also, we know that false negatives are more costly than false positives in a churn and hence let’s use precision, recall and F2 scores as the ideal metric for the model selection." }, { "code": null, "e": 36267, "s": 36233, "text": "Step 15.4.1. Logistic Regression:" }, { "code": null, "e": 36919, "s": 36267, "text": "# Fitting Logistic Regression to the Training setclassifier = LogisticRegression(random_state = 0)classifier.fit(X_train, y_train)# Predicting the Test set resultsy_pred = classifier.predict(X_test)#Evaluate resultsacc = accuracy_score(y_test, y_pred )prec = precision_score(y_test, y_pred )rec = recall_score(y_test, y_pred )f1 = f1_score(y_test, y_pred )f2 = fbeta_score(y_test, y_pred, beta=2.0)results = pd.DataFrame([['Logistic Regression', acc, prec, rec, f1, f2]], columns = ['Model', 'Accuracy', 'Precision', 'Recall', 'F1 Score', 'F2 Score'])results = results.sort_values([\"Precision\", \"Recall\", \"F2 Score\"], ascending = False)print (results)" }, { "code": null, "e": 36976, "s": 36919, "text": "Step 15.4.2. Support Vector Machine (linear classifier):" }, { "code": null, "e": 37686, "s": 36976, "text": "# Fitting SVM (SVC class) to the Training setclassifier = SVC(kernel = 'linear', random_state = 0)classifier.fit(X_train, y_train)# Predicting the Test set results y_pred = classifier.predict(X_test)#Evaluate resultsacc = accuracy_score(y_test, y_pred )prec = precision_score(y_test, y_pred )rec = recall_score(y_test, y_pred)f1 = f1_score(y_test, y_pred )f2 = fbeta_score(y_test, y_pred, beta=2.0)model_results = pd.DataFrame([['SVM (Linear)', acc, prec, rec, f1, f2]],columns = ['Model', 'Accuracy', 'Precision', 'Recall', 'F1 Score', 'F2 Score'])results = results.append(model_results, ignore_index = True)results = results.sort_values([\"Precision\", \"Recall\", \"F2 Score\"], ascending = False)print (results)" }, { "code": null, "e": 37720, "s": 37686, "text": "Step 15.4.3. K-Nearest Neighbors:" }, { "code": null, "e": 38457, "s": 37720, "text": "# Fitting KNN to the Training set:classifier = KNeighborsClassifier(n_neighbors = 22, metric = 'minkowski', p = 2)classifier.fit(X_train, y_train)# Predicting the Test set results y_pred = classifier.predict(X_test)#Evaluate resultsacc = accuracy_score(y_test, y_pred )prec = precision_score(y_test, y_pred )rec = recall_score(y_test, y_pred )f1 = f1_score(y_test, y_pred )f2 = fbeta_score(y_test, y_pred, beta=2.0)model_results = pd.DataFrame([['K-Nearest Neighbours', acc, prec, rec, f1, f2]], columns = ['Model', 'Accuracy', 'Precision', 'Recall', 'F1 Score', 'F2 Score'])results = results.append(model_results, ignore_index = True)results = results.sort_values([\"Precision\", \"Recall\", \"F2 Score\"], ascending = False)print (results)" }, { "code": null, "e": 38482, "s": 38457, "text": "Step 15.4.4. Kernel SVM:" }, { "code": null, "e": 39184, "s": 38482, "text": "# Fitting Kernel SVM to the Training set:classifier = SVC(kernel = 'rbf', random_state = 0)classifier.fit(X_train, y_train)# Predicting the Test set results y_pred = classifier.predict(X_test)#Evaluate resultsacc = accuracy_score(y_test, y_pred )prec = precision_score(y_test, y_pred )rec = recall_score(y_test, y_pred )f1 = f1_score(y_test, y_pred )f2 = fbeta_score(y_test, y_pred, beta=2.0)model_results = pd.DataFrame([['Kernel SVM', acc, prec, rec, f1, f2]],columns = ['Model', 'Accuracy', 'Precision', 'Recall', 'F1 Score', 'F2 Score'])results = results.append(model_results, ignore_index = True)results = results.sort_values([\"Precision\", \"Recall\", \"F2 Score\"], ascending = False)print (results)" }, { "code": null, "e": 39209, "s": 39184, "text": "Step 15.4.5. Naive Byes:" }, { "code": null, "e": 39885, "s": 39209, "text": "# Fitting Naive Byes to the Training set:classifier = GaussianNB()classifier.fit(X_train, y_train)# Predicting the Test set results y_pred = classifier.predict(X_test)#Evaluate resultsacc = accuracy_score(y_test, y_pred )prec = precision_score(y_test, y_pred )rec = recall_score(y_test, y_pred )f1 = f1_score(y_test, y_pred )f2 = fbeta_score(y_test, y_pred, beta=2.0)model_results = pd.DataFrame([['Naive Byes', acc, prec, rec, f1, f2]],columns = ['Model', 'Accuracy', 'Precision','Recall', 'F1 Score', 'F2 Score'])results = results.append(model_results, ignore_index = True)results = results.sort_values([\"Precision\", \"Recall\", \"F2 Score\"], ascending = False)print (results)" }, { "code": null, "e": 39913, "s": 39885, "text": "Step 15.4.6. Decision Tree:" }, { "code": null, "e": 40648, "s": 39913, "text": "# Fitting Decision Tree to the Training set:classifier = DecisionTreeClassifier(criterion = 'entropy', random_state = 0)classifier.fit(X_train, y_train)# Predicting the Test set results y_pred = classifier.predict(X_test)#Evaluate resultsacc = accuracy_score(y_test, y_pred )prec = precision_score(y_test, y_pred )rec = recall_score(y_test, y_pred )f1 = f1_score(y_test, y_pred )f2 = fbeta_score(y_test, y_pred, beta=2.0)model_results = pd.DataFrame([['Decision Tree', acc, prec, rec, f1, f2]], columns = ['Model', 'Accuracy', 'Precision', 'Recall', 'F1 Score', 'F2 Score'])results = results.append(model_results, ignore_index = True)results = results.sort_values([\"Precision\", \"Recall\", \"F2 Score\"], ascending = False)print (results)" }, { "code": null, "e": 40676, "s": 40648, "text": "Step 15.4.7. Random Forest:" }, { "code": null, "e": 41534, "s": 40676, "text": "# Fitting Random Forest to the Training set: classifier = RandomForestClassifier(n_estimators = 72, criterion = 'entropy', random_state = 0)classifier.fit(X_train, y_train)# Predicting the Test set results y_pred = classifier.predict(X_test)#Evaluate resultsfrom sklearn.metrics import confusion_matrix, accuracy_score, f1_score, precision_score, recall_scoreacc = accuracy_score(y_test, y_pred )prec = precision_score(y_test, y_pred )rec = recall_score(y_test, y_pred )f1 = f1_score(y_test, y_pred )f2 = fbeta_score(y_test, y_pred, beta=2.0)model_results = pd.DataFrame([['Random Forest', acc, prec, rec, f1, f2]],columns = ['Model', 'Accuracy', 'Precision', 'Recall', 'F1 Score', 'F2 Score'])results = results.append(model_results, ignore_index = True)results = results.sort_values([\"Precision\", \"Recall\", \"F2 Score\"], ascending = False)print (results)" }, { "code": null, "e": 41934, "s": 41534, "text": "From the 2nd iteration, we can definitely conclude that logistic regression is an optimal model of choice for the given dataset as it has relatively the highest combination of precision, recall and F2 scores; giving most number of correct positive predictions while minimizing the false negatives. Hence, let's try to use Logistic Regression and evaluate its performance in the forthcoming sections." }, { "code": null, "e": 42088, "s": 41934, "text": "Step 16: Train & evaluate Chosen Model: Let’s fit the selected model (Logistic Regression in this case) on the training dataset and evaluate the results." }, { "code": null, "e": 42635, "s": 42088, "text": "classifier = LogisticRegression(random_state = 0,penalty = 'l2')classifier.fit(X_train, y_train)# Predict the Test set resultsy_pred = classifier.predict(X_test)#Evaluate Model Results on Test Set:acc = accuracy_score(y_test, y_pred )prec = precision_score(y_test, y_pred )rec = recall_score(y_test, y_pred )f1 = f1_score(y_test, y_pred )f2 = fbeta_score(y_test, y_pred, beta=2.0)results = pd.DataFrame([['Logistic Regression',acc, prec, rec, f1, f2]],columns = ['Model', 'Accuracy', 'Precision', 'Recall', 'F1 Score', 'F2 Score'])print (results)" }, { "code": null, "e": 42977, "s": 42635, "text": "k-Fold Cross-Validation: Model evaluation is most commonly done through ‘K- fold Cross-Validation’ technique that primarily helps us to fix the variance. Variance problem occurs when we get good accuracy while running the model on a training set and a test set but then the accuracy looks different when the model is run on another test set." }, { "code": null, "e": 43322, "s": 42977, "text": "So, in order to fix the variance problem, k-fold cross-validation basically split the training set into 10 folds and train the model on 9 folds (9 subsets of the training dataset) before testing it on the test fold. This gives us the flexibility to train our model on all ten combinations of 9 folds; giving ample room to finalize the variance." }, { "code": null, "e": 43522, "s": 43322, "text": "accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10)print(\"Logistic Regression Classifier Accuracy: %0.2f (+/- %0.2f)\" % (accuracies.mean(), accuracies.std() * 2))" }, { "code": null, "e": 43679, "s": 43522, "text": "Therefore, our k-fold Cross Validation results indicate that we would have an accuracy anywhere between 76% to 84% while running this model on any test set." }, { "code": null, "e": 43827, "s": 43679, "text": "Visualize results on a Confusion Matrix: The Confusion matrix indicates that we have 208+924 correct predictions and 166+111 incorrect predictions." }, { "code": null, "e": 43964, "s": 43827, "text": "Accuracy rate = number of correct predictions/ total predictions * 100Error rate = Number of wrong predictions / total predictions * 100" }, { "code": null, "e": 44055, "s": 43964, "text": "We have got an accuracy of 80%; signalling the characteristics of a reasonably good model." }, { "code": null, "e": 44568, "s": 44055, "text": "cm = confusion_matrix(y_test, y_pred) df_cm = pd.DataFrame(cm, index = (0, 1), columns = (0, 1))plt.figure(figsize = (28,20))fig, ax = plt.subplots()sn.set(font_scale=1.4)sn.heatmap(df_cm, annot=True, fmt='g'#,cmap=\"YlGnBu\" )class_names=[0,1]tick_marks = np.arange(len(class_names))plt.tight_layout()plt.title('Confusion matrix\\n', y=1.1)plt.xticks(tick_marks, class_names)plt.yticks(tick_marks, class_names)ax.xaxis.set_label_position(\"top\")plt.ylabel('Actual label\\n')plt.xlabel('Predicted label\\n')" }, { "code": null, "e": 45009, "s": 44568, "text": "Evaluate the model using ROC Graph: It’s good to re-evaluate the model using ROC Graph. ROC Graph shows us the capability of a model to distinguish between the classes based on the AUC Mean score. The orange line represents the ROC curve of a random classifier while a good classifier tries to remain as far away from that line as possible. As shown in the graph below, the fine-tuned Logistic Regression model showcased a higher AUC score." }, { "code": null, "e": 46049, "s": 45009, "text": "classifier.fit(X_train, y_train) probs = classifier.predict_proba(X_test) probs = probs[:, 1] classifier_roc_auc = accuracy_score(y_test, y_pred )rf_fpr, rf_tpr, rf_thresholds = roc_curve(y_test, classifier.predict_proba(X_test)[:,1])plt.figure(figsize=(14, 6))# Plot Logistic Regression ROCplt.plot(rf_fpr, rf_tpr, label='Logistic Regression (area = %0.2f)' % classifier_roc_auc)# Plot Base Rate ROCplt.plot([0,1], [0,1],label='Base Rate' 'k--')plt.xlim([0.0, 1.0])plt.ylim([0.0, 1.05])plt.ylabel('True Positive Rate \\n',horizontalalignment=\"center\",fontstyle = \"normal\", fontsize = \"medium\", fontfamily = \"sans-serif\")plt.xlabel('\\nFalse Positive Rate \\n',horizontalalignment=\"center\",fontstyle = \"normal\", fontsize = \"medium\", fontfamily = \"sans-serif\")plt.title('ROC Graph \\n',horizontalalignment=\"center\", fontstyle = \"normal\", fontsize = \"22\", fontfamily = \"sans-serif\")plt.legend(loc=\"lower right\", fontsize = \"medium\")plt.xticks(rotation=0, horizontalalignment=\"center\")plt.yticks(rotation=0, horizontalalignment=\"right\")plt.show()" }, { "code": null, "e": 46230, "s": 46049, "text": "Step 17:Predict Feature Importance: Logistic Regression allows us to determine the key features that have significance in predicting the target attribute (“Churn” in this project)." }, { "code": null, "e": 46440, "s": 46230, "text": "The logistic regression model predicts that the churn rate would increase positively with month to month contract, optic fibre internet service, electronic checks, absence of payment security and tech support." }, { "code": null, "e": 46646, "s": 46440, "text": "On the other hand, the model predicts a negative correlation with churn if any customer has subscribed to online security, one-year contract or if they have opted for mailed checks as their payment medium." }, { "code": null, "e": 46920, "s": 46646, "text": "# Analyzing Coefficientsfeature_importances = pd.concat([pd.DataFrame(dataset.drop(columns = 'customerID').columns, columns = [\"features\"]),pd.DataFrame(np.transpose(classifier.coef_), columns = [\"coef\"])],axis = 1)feature_importances.sort_values(\"coef\", ascending = False)" }, { "code": null, "e": 47569, "s": 46920, "text": "Model improvement basically involves choosing the best parameters for the machine learning model that we have come up with. There are two types of parameters in any machine learning model — the first type are the kind of parameters that the model learns; the optimal values automatically found by running the model. The second type of parameters is the ones that user get to choose while running the model. Such parameters are called the hyperparameters; a set of configurable values external to a model that cannot be determined by the data, and that we are trying to optimize through Parameter Tuning techniques like Random Search or Grid Search." }, { "code": null, "e": 47847, "s": 47569, "text": "Hyperparameter tuning might not improve the model every time. For instance, when we tried to tune the model further, we ended up getting an accuracy score lower than the default one. I’m just demonstrating the steps involved in hyperparameter tuning here for future references." }, { "code": null, "e": 47895, "s": 47847, "text": "Step 18:Hyper parameter Tuning via Grid Search:" }, { "code": null, "e": 48601, "s": 47895, "text": "# Round 1: # Select Regularization Method import timepenalty = ['l1', 'l2']# Create regularization hyperparameter spaceC = [0.001, 0.01, 0.1, 1, 10, 100, 1000]# Combine Parametersparameters = dict(C=C, penalty=penalty)lr_classifier = GridSearchCV(estimator = classifier, param_grid = parameters, scoring = \"balanced_accuracy\", cv = 10, n_jobs = -1)t0 = time.time()lr_classifier = lr_classifier .fit(X_train, y_train)t1 = time.time()print(\"Took %0.2f seconds\" % (t1 - t0))lr_best_accuracy = lr_classifier.best_score_lr_best_parameters = lr_classifier.best_params_lr_best_accuracy, lr_best_parameters" }, { "code": null, "e": 49295, "s": 48601, "text": "# Round 2:# Select Regularization Methodimport timepenalty = ['l2']# Create regularization hyperparameter spaceC = [ 0.0001, 0.001, 0.01, 0.02, 0.05]# Combine Parametersparameters = dict(C=C, penalty=penalty)lr_classifier = GridSearchCV(estimator = classifier, param_grid = parameters, scoring = \"balanced_accuracy\", cv = 10, n_jobs = -1)t0 = time.time()lr_classifier = lr_classifier .fit(X_train, y_train)t1 = time.time()print(\"Took %0.2f seconds\" % (t1 - t0))lr_best_accuracy = lr_classifier.best_score_lr_best_parameters = lr_classifier.best_params_lr_best_accuracy, lr_best_parameters" }, { "code": null, "e": 49349, "s": 49295, "text": "Step 18.2: Final Hyperparameter tuning and selection:" }, { "code": null, "e": 49624, "s": 49349, "text": "lr_classifier = LogisticRegression(random_state = 0, penalty = 'l2')lr_classifier.fit(X_train, y_train)# Predict the Test set resultsy_pred = lr_classifier.predict(X_test)#probability scorey_pred_probs = lr_classifier.predict_proba(X_test)y_pred_probs = y_pred_probs [:, 1]" }, { "code": null, "e": 49675, "s": 49624, "text": "Step 19: Compare predictions against the test set:" }, { "code": null, "e": 50496, "s": 49675, "text": "#Revalidate final results with Confusion Matrix:cm = confusion_matrix(y_test, y_pred) print (cm)#Confusion Matrix as a quick Crosstab: pd.crosstab(y_test,pd.Series(y_pred),rownames=['ACTUAL'],colnames=['PRED'])#visualize Confusion Matrix:cm = confusion_matrix(y_test, y_pred) df_cm = pd.DataFrame(cm, index = (0, 1), columns = (0, 1))plt.figure(figsize = (28,20))fig, ax = plt.subplots()sn.set(font_scale=1.4)sn.heatmap(df_cm, annot=True, fmt='g'#,cmap=\"YlGnBu\" )class_names=[0,1]tick_marks = np.arange(len(class_names))plt.tight_layout()plt.title('Confusion matrix\\n', y=1.1)plt.xticks(tick_marks, class_names)plt.yticks(tick_marks, class_names)ax.xaxis.set_label_position(\"top\")plt.ylabel('Actual label\\n')plt.xlabel('Predicted label\\n')print(\"Test Data Accuracy: %0.4f\" % accuracy_score(y_test, y_pred))" }, { "code": null, "e": 50940, "s": 50496, "text": "Step 20: Format Final Results: Unpredictability and risk are the close companions of any predictive models. Therefore in the real world, its always a good practice to build a propensity score besides an absolute predicted outcome. Instead of just retrieving a binary estimated target outcome (0 or 1), every ‘Customer ID’ could get an additional layer of propensity score highlighting their percentage of probability to take the target action." }, { "code": null, "e": 51514, "s": 50940, "text": "final_results = pd.concat([test_identity, y_test], axis = 1).dropna()final_results['predictions'] = y_predfinal_results[\"propensity_to_churn(%)\"] = y_pred_probsfinal_results[\"propensity_to_churn(%)\"] = final_results[\"propensity_to_churn(%)\"]*100final_results[\"propensity_to_churn(%)\"]=final_results[\"propensity_to_churn(%)\"].round(2)final_results = final_results[['customerID', 'Churn', 'predictions', 'propensity_to_churn(%)']]final_results ['Ranking'] = pd.qcut(final_results['propensity_to_churn(%)'].rank(method = 'first'),10,labels=range(10,0,-1))print (final_results)" }, { "code": null, "e": 51765, "s": 51514, "text": "Lastly, deploy the model to a server using ‘joblib’ library so that we can productionize the end-to-end machine learning framework. Later we can run the model over any new dataset to predict the probability of any customer to churn in months to come." }, { "code": null, "e": 51790, "s": 51765, "text": "Step 21: Save the model:" }, { "code": null, "e": 51863, "s": 51790, "text": "filename = 'final_model.model'i = [lr_classifier]joblib.dump(i,filename)" }, { "code": null, "e": 51874, "s": 51863, "text": "Conclusion" }, { "code": null, "e": 52104, "s": 51874, "text": "So, in a nutshell, we made use of a customer churn dataset from Kaggle to build a machine learning classifier that predicts the propensity of any customer to churn in months to come with a reasonable accuracy score of 76% to 84%." }, { "code": null, "e": 52117, "s": 52104, "text": "What’s Next?" }, { "code": null, "e": 52465, "s": 52117, "text": "Share key insights about the customer demographics and churn rate that you have garnered from the exploratory data analysis sections to the sales and marketing team of the organization. Let the sales team know the features that have positive and negative correlations with churn so that they could strategize the retention initiatives accordingly." }, { "code": null, "e": 52829, "s": 52465, "text": "Further, classify the upcoming customers based on the propensity score as high risk (for customers with propensity score > 80%), medium risk (for customers with a propensity score between 60–80%) and lastly low-risk category (for customers with propensity score <60%). Focus on each segment of customers upfront and ensure that there needs are well taken care of." }, { "code": null, "e": 53112, "s": 52829, "text": "Lastly, measure the return on investment (ROI) of this assignment by computing the attrition rate for the current financial quarter. Compare the quarter results with the same quarter last year or the year before and share the outcome with the senior management of your organization." }, { "code": null, "e": 53130, "s": 53112, "text": "GitHub Repository" }, { "code": null, "e": 53517, "s": 53130, "text": "I have learned (and continue to learn) from many folks in Github. Hence sharing my entire python script and supporting files in a public GitHub Repository in case if it benefits any seekers online. Also, feel free to reach out to me if you need any help in understanding the fundamentals of supervised machine learning algorithms in Python. Happy to share what I know:) Hope this helps!" } ]
Difference between Algorithm, Pseudocode and Program - GeeksforGeeks
07 Dec, 2021 In this post, we will discuss the most common misconception that an algorithm and a pseudocode is one of the same things. No, they are not! Let us take a look at definitions first, Algorithm : Systematic logical approach which is a well-defined, step-by-step procedure that allows a computer to solve a problem. Pseudocode : It is a simpler version of a programming code in plain English which uses short phrases to write code for a program before it is implemented in a specific programming language. Program : It is exact code written for problem following all the rules of the programming language. Algorithm: An algorithm is used to provide a solution to a particular problem in form of well-defined steps. Whenever you use a computer to solve a particular problem, the steps which lead to the solution should be properly communicated to the computer. While executing an algorithm on a computer, several operations such as additions and subtractions are combined to perform more complex mathematical operations. Algorithms can be expressed using natural language, flowcharts, etc. Let’s take a look at an example for a better understanding. As a programmer, we are all aware of the Linear Search program. (Linear Search)Algorithm of linear search : 1. Start from the leftmost element of arr[] and one by one compare x with each element of arr[]. 2. If x matches with an element, return the index. 3. If x doesn’t match with any of elements, return -1. Here, we can see how the steps of a linear search program are explained in a simple, English language. Pseudocode:It is one of the methods which can be used to represent an algorithm for a program. It does not have a specific syntax like any of the programming languages and thus cannot be executed on a computer. There are several formats which are used to write pseudo-codes and most of them take down the structures from languages such as C, Lisp, FORTRAN, etc.Many time algorithms are presented using pseudocode since they can be read and understood by programmers who are familiar with different programming languages. Pseudocode allows you to include several control structures such as While, If-then-else, Repeat-until, for and case, which is present in many high-level languages. Note: Pseudocode is not an actual programming language. Pseudocode for Linear Search : FUNCTION linearSearch(list, searchTerm): FOR index FROM 0 -> length(list): IF list[index] == searchTerm THEN RETURN index ENDIF ENDLOOP RETURN -1 END FUNCTION In here, we haven’t used any specific programming language but wrote the steps of a linear search in a simpler form which can be further modified into a proper program. Program:A program is a set of instructions for the computer to follow. The machine can’t read a program directly, because it only understands machine code. But you can write stuff in a computer language, and then a compiler or interpreter can make it understandable to the computer.Program for Linear Search : Cpp Python3 // C++ code for linearly search x in arr[]. If x// is present then return its location, otherwise// return -1int search(int arr[], int n, int x){ int i; for (i = 0; i < n; i++) if (arr[i] == x) return i; return -1;} # Python3 code for linearly search x in arr. If x# is present then return its location, otherwise# return -1def search( arr, n, x): for i in range(n): if (arr[i] == x): return i return -1 Algorithm vs Pseudocode vs Program: An algorithm is defined as a well-defined sequence of steps that provides a solution for a given problem, whereas a pseudocode is one of the methods that can be used to represent an algorithm. While algorithms are generally written in a natural language or plain English language, pseudocode is written in a format that is similar to the structure of a high-level programming language. Program on the other hand allows us to write a code in a particular programming language. An algorithm is defined as a well-defined sequence of steps that provides a solution for a given problem, whereas a pseudocode is one of the methods that can be used to represent an algorithm. While algorithms are generally written in a natural language or plain English language, pseudocode is written in a format that is similar to the structure of a high-level programming language. Program on the other hand allows us to write a code in a particular programming language. So, as depicted above you can clearly see how the algorithm is used to generate the pseudocode which is further expanded by following a particular syntax of a programming language to create the code of the program. surinderdawra388 amartyaghoshgfg CBSE - Class 11 Picked Programming Basics school-programming Algorithms Difference Between School Programming Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SDE SHEET - A Complete Guide for SDE Preparation Top 50 Array Coding Problems for Interviews DSA Sheet by Love Babbar Difference between BFS and DFS A* Search Algorithm Difference between BFS and DFS Class method vs Static method in Python Differences between TCP and UDP Difference between var, let and const keywords in JavaScript Difference between Process and Thread
[ { "code": null, "e": 34594, "s": 34566, "text": "\n07 Dec, 2021" }, { "code": null, "e": 35197, "s": 34594, "text": "In this post, we will discuss the most common misconception that an algorithm and a pseudocode is one of the same things. No, they are not! Let us take a look at definitions first, Algorithm : Systematic logical approach which is a well-defined, step-by-step procedure that allows a computer to solve a problem. Pseudocode : It is a simpler version of a programming code in plain English which uses short phrases to write code for a program before it is implemented in a specific programming language. Program : It is exact code written for problem following all the rules of the programming language. " }, { "code": null, "e": 35208, "s": 35197, "text": "Algorithm:" }, { "code": null, "e": 35849, "s": 35208, "text": "An algorithm is used to provide a solution to a particular problem in form of well-defined steps. Whenever you use a computer to solve a particular problem, the steps which lead to the solution should be properly communicated to the computer. While executing an algorithm on a computer, several operations such as additions and subtractions are combined to perform more complex mathematical operations. Algorithms can be expressed using natural language, flowcharts, etc. Let’s take a look at an example for a better understanding. As a programmer, we are all aware of the Linear Search program. (Linear Search)Algorithm of linear search : " }, { "code": null, "e": 36056, "s": 35849, "text": "1. Start from the leftmost element of arr[] and \none by one compare x with each element of arr[]. \n2. If x matches with an element, return the index. \n3. If x doesn’t match with any of elements, return -1. " }, { "code": null, "e": 36160, "s": 36056, "text": "Here, we can see how the steps of a linear search program are explained in a simple, English language. " }, { "code": null, "e": 36934, "s": 36160, "text": "Pseudocode:It is one of the methods which can be used to represent an algorithm for a program. It does not have a specific syntax like any of the programming languages and thus cannot be executed on a computer. There are several formats which are used to write pseudo-codes and most of them take down the structures from languages such as C, Lisp, FORTRAN, etc.Many time algorithms are presented using pseudocode since they can be read and understood by programmers who are familiar with different programming languages. Pseudocode allows you to include several control structures such as While, If-then-else, Repeat-until, for and case, which is present in many high-level languages. Note: Pseudocode is not an actual programming language. Pseudocode for Linear Search : " }, { "code": null, "e": 37142, "s": 36934, "text": "FUNCTION linearSearch(list, searchTerm):\n FOR index FROM 0 -> length(list):\n IF list[index] == searchTerm THEN\n RETURN index\n ENDIF\n ENDLOOP\n RETURN -1\nEND FUNCTION " }, { "code": null, "e": 37313, "s": 37142, "text": "In here, we haven’t used any specific programming language but wrote the steps of a linear search in a simpler form which can be further modified into a proper program. " }, { "code": null, "e": 37624, "s": 37313, "text": "Program:A program is a set of instructions for the computer to follow. The machine can’t read a program directly, because it only understands machine code. But you can write stuff in a computer language, and then a compiler or interpreter can make it understandable to the computer.Program for Linear Search : " }, { "code": null, "e": 37628, "s": 37624, "text": "Cpp" }, { "code": null, "e": 37636, "s": 37628, "text": "Python3" }, { "code": "// C++ code for linearly search x in arr[]. If x// is present then return its location, otherwise// return -1int search(int arr[], int n, int x){ int i; for (i = 0; i < n; i++) if (arr[i] == x) return i; return -1;}", "e": 37880, "s": 37636, "text": null }, { "code": "# Python3 code for linearly search x in arr. If x# is present then return its location, otherwise# return -1def search( arr, n, x): for i in range(n): if (arr[i] == x): return i return -1", "e": 38098, "s": 37880, "text": null }, { "code": null, "e": 38134, "s": 38098, "text": "Algorithm vs Pseudocode vs Program:" }, { "code": null, "e": 38613, "s": 38134, "text": "An algorithm is defined as a well-defined sequence of steps that provides a solution for a given problem, whereas a pseudocode is one of the methods that can be used to represent an algorithm. While algorithms are generally written in a natural language or plain English language, pseudocode is written in a format that is similar to the structure of a high-level programming language. Program on the other hand allows us to write a code in a particular programming language. " }, { "code": null, "e": 38808, "s": 38613, "text": "An algorithm is defined as a well-defined sequence of steps that provides a solution for a given problem, whereas a pseudocode is one of the methods that can be used to represent an algorithm. " }, { "code": null, "e": 39093, "s": 38808, "text": "While algorithms are generally written in a natural language or plain English language, pseudocode is written in a format that is similar to the structure of a high-level programming language. Program on the other hand allows us to write a code in a particular programming language. " }, { "code": null, "e": 39309, "s": 39093, "text": "So, as depicted above you can clearly see how the algorithm is used to generate the pseudocode which is further expanded by following a particular syntax of a programming language to create the code of the program. " }, { "code": null, "e": 39326, "s": 39309, "text": "surinderdawra388" }, { "code": null, "e": 39342, "s": 39326, "text": "amartyaghoshgfg" }, { "code": null, "e": 39358, "s": 39342, "text": "CBSE - Class 11" }, { "code": null, "e": 39365, "s": 39358, "text": "Picked" }, { "code": null, "e": 39384, "s": 39365, "text": "Programming Basics" }, { "code": null, "e": 39403, "s": 39384, "text": "school-programming" }, { "code": null, "e": 39414, "s": 39403, "text": "Algorithms" }, { "code": null, "e": 39433, "s": 39414, "text": "Difference Between" }, { "code": null, "e": 39452, "s": 39433, "text": "School Programming" }, { "code": null, "e": 39463, "s": 39452, "text": "Algorithms" }, { "code": null, "e": 39561, "s": 39463, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39610, "s": 39561, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 39654, "s": 39610, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 39679, "s": 39654, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 39710, "s": 39679, "text": "Difference between BFS and DFS" }, { "code": null, "e": 39730, "s": 39710, "text": "A* Search Algorithm" }, { "code": null, "e": 39761, "s": 39730, "text": "Difference between BFS and DFS" }, { "code": null, "e": 39801, "s": 39761, "text": "Class method vs Static method in Python" }, { "code": null, "e": 39833, "s": 39801, "text": "Differences between TCP and UDP" }, { "code": null, "e": 39894, "s": 39833, "text": "Difference between var, let and const keywords in JavaScript" } ]
Dart Programming - Exceptions
An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally. Built-in Dart exceptions include − DeferredLoadException Thrown when a deferred library fails to load. FormatException Exception thrown when a string or some other data does not have an expected format and cannot be parsed or processed. IntegerDivisionByZeroException Thrown when a number is divided by zero. IOException Base class for all Inupt-Output related exceptions. IsolateSpawnException Thrown when an isolate cannot be created. Timeout Thrown when a scheduled timeout happens while waiting for an async result. Every exception in Dart is a subtype of the pre-defined class Exception. Exceptions must be handled to prevent the application from terminating abruptly. The try block embeds code that might possibly result in an exception. The on block is used when the exception type needs to be specified. The catch block is used when the handler needs the exception object. The try block must be followed by either exactly one on / catch block or one finally block (or one of both). When an exception occurs in the try block, the control is transferred to the catch. The syntax for handling an exception is as given below − try { // code that might throw an exception } on Exception1 { // code for handling exception } catch Exception2 { // code for handling exception } Following are some points to remember − A code snippet can have more than one on / catch blocks to handle multiple exceptions. A code snippet can have more than one on / catch blocks to handle multiple exceptions. The on block and the catch block are mutually inclusive, i.e. a try block can be associated with both- the on block and the catch block. The on block and the catch block are mutually inclusive, i.e. a try block can be associated with both- the on block and the catch block. The following code illustrates exception handling in Dart − The following program divides two numbers represented by the variables x and y respectively. The code throws an exception since it attempts division by zero. The on block contains the code to handle this exception. main() { int x = 12; int y = 0; int res; try { res = x ~/ y; } on IntegerDivisionByZeroException { print('Cannot divide by zero'); } } It should produce the following output − Cannot divide by zero In the following example, we have used the same code as above. The only difference is that the catch block (instead of the ON block) here contains the code to handle the exception. The parameter of catch contains the exception object thrown at runtime. main() { int x = 12; int y = 0; int res; try { res = x ~/ y; } catch(e) { print(e); } } It should produce the following output − IntegerDivisionByZeroException The following example shows how to use the on...catch block. main() { int x = 12; int y = 0; int res; try { res = x ~/ y; } on IntegerDivisionByZeroException catch(e) { print(e); } } It should produce the following output − IntegerDivisionByZeroException The finally block includes code that should be executed irrespective of an exception’s occurrence. The optional finally block executes unconditionally after try/on/catch. The syntax for using the finally block is as follows − try { // code that might throw an exception } on Exception1 { // exception handling code } catch Exception2 { // exception handling } finally { // code that should always execute; irrespective of the exception } The following example illustrates the use of finally block. main() { int x = 12; int y = 0; int res; try { res = x ~/ y; } on IntegerDivisionByZeroException { print('Cannot divide by zero'); } finally { print('Finally block executed'); } } It should produce the following output − Cannot divide by zero Finally block executed The throw keyword is used to explicitly raise an exception. A raised exception should be handled to prevent the program from exiting abruptly. The syntax for raising an exception explicitly is − throw new Exception_name() The following example shows how to use the throw keyword to throw an exception − main() { try { test_age(-2); } catch(e) { print('Age cannot be negative'); } } void test_age(int age) { if(age<0) { throw new FormatException(); } } It should produce the following output − Age cannot be negative As specified above, every exception type in Dart is a subtype of the built-in class Exception. Dart enables creating custom exceptions by extending the existing ones. The syntax for defining a custom exception is as given below − class Custom_exception_Name implements Exception { // can contain constructors, variables and methods } Custom Exceptions should be raised explicitly and the same should be handled in the code. The following example shows how to define and handle a custom exception. class AmtException implements Exception { String errMsg() => 'Amount should be greater than zero'; } void main() { try { withdraw_amt(-1); } catch(e) { print(e.errMsg()); } finally { print('Ending requested operation.....'); } } void withdraw_amt(int amt) { if (amt <= 0) { throw new AmtException(); } } In the above code, we are defining a custom exception, AmtException. The code raises the exception if the amount passed is not within the excepted range. The main function encloses the function invocation in the try...catch block. The code should produce the following output − Amount should be greater than zero Ending requested operation.... 44 Lectures 4.5 hours Sriyank Siddhartha 34 Lectures 4 hours Sriyank Siddhartha 69 Lectures 4 hours Frahaan Hussain 117 Lectures 10 hours Frahaan Hussain 22 Lectures 1.5 hours Pranjal Srivastava 34 Lectures 3 hours Pranjal Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2741, "s": 2525, "text": "An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally." }, { "code": null, "e": 2776, "s": 2741, "text": "Built-in Dart exceptions include −" }, { "code": null, "e": 2798, "s": 2776, "text": "DeferredLoadException" }, { "code": null, "e": 2844, "s": 2798, "text": "Thrown when a deferred library fails to load." }, { "code": null, "e": 2860, "s": 2844, "text": "FormatException" }, { "code": null, "e": 2978, "s": 2860, "text": "Exception thrown when a string or some other data does not have an expected format and cannot be parsed or processed." }, { "code": null, "e": 3009, "s": 2978, "text": "IntegerDivisionByZeroException" }, { "code": null, "e": 3050, "s": 3009, "text": "Thrown when a number is divided by zero." }, { "code": null, "e": 3062, "s": 3050, "text": "IOException" }, { "code": null, "e": 3114, "s": 3062, "text": "Base class for all Inupt-Output related exceptions." }, { "code": null, "e": 3136, "s": 3114, "text": "IsolateSpawnException" }, { "code": null, "e": 3178, "s": 3136, "text": "Thrown when an isolate cannot be created." }, { "code": null, "e": 3186, "s": 3178, "text": "Timeout" }, { "code": null, "e": 3261, "s": 3186, "text": "Thrown when a scheduled timeout happens while waiting for an async result." }, { "code": null, "e": 3415, "s": 3261, "text": "Every exception in Dart is a subtype of the pre-defined class Exception. Exceptions must be handled to prevent the application from terminating abruptly." }, { "code": null, "e": 3622, "s": 3415, "text": "The try block embeds code that might possibly result in an exception. The on block is used when the exception type needs to be specified. The catch block is used when the handler needs the exception object." }, { "code": null, "e": 3815, "s": 3622, "text": "The try block must be followed by either exactly one on / catch block or one finally block (or one of both). When an exception occurs in the try block, the control is transferred to the catch." }, { "code": null, "e": 3872, "s": 3815, "text": "The syntax for handling an exception is as given below −" }, { "code": null, "e": 4040, "s": 3872, "text": "try { \n // code that might throw an exception \n} \non Exception1 { \n // code for handling exception \n} \ncatch Exception2 { \n // code for handling exception \n} \n" }, { "code": null, "e": 4080, "s": 4040, "text": "Following are some points to remember −" }, { "code": null, "e": 4167, "s": 4080, "text": "A code snippet can have more than one on / catch blocks to handle multiple exceptions." }, { "code": null, "e": 4254, "s": 4167, "text": "A code snippet can have more than one on / catch blocks to handle multiple exceptions." }, { "code": null, "e": 4391, "s": 4254, "text": "The on block and the catch block are mutually inclusive, i.e. a try block can be associated with both- the on block and the catch block." }, { "code": null, "e": 4528, "s": 4391, "text": "The on block and the catch block are mutually inclusive, i.e. a try block can be associated with both- the on block and the catch block." }, { "code": null, "e": 4588, "s": 4528, "text": "The following code illustrates exception handling in Dart −" }, { "code": null, "e": 4803, "s": 4588, "text": "The following program divides two numbers represented by the variables x and y respectively. The code throws an exception since it attempts division by zero. The on block contains the code to handle this exception." }, { "code": null, "e": 4986, "s": 4803, "text": "main() { \n int x = 12; \n int y = 0; \n int res; \n \n try {\n res = x ~/ y; \n } \n on IntegerDivisionByZeroException { \n print('Cannot divide by zero'); \n } \n} " }, { "code": null, "e": 5027, "s": 4986, "text": "It should produce the following output −" }, { "code": null, "e": 5050, "s": 5027, "text": "Cannot divide by zero\n" }, { "code": null, "e": 5303, "s": 5050, "text": "In the following example, we have used the same code as above. The only difference is that the catch block (instead of the ON block) here contains the code to handle the exception. The parameter of catch contains the exception object thrown at runtime." }, { "code": null, "e": 5442, "s": 5303, "text": "main() { \n int x = 12; \n int y = 0; \n int res; \n \n try { \n res = x ~/ y; \n } \n catch(e) { \n print(e); \n } \n} " }, { "code": null, "e": 5483, "s": 5442, "text": "It should produce the following output −" }, { "code": null, "e": 5515, "s": 5483, "text": "IntegerDivisionByZeroException\n" }, { "code": null, "e": 5576, "s": 5515, "text": "The following example shows how to use the on...catch block." }, { "code": null, "e": 5748, "s": 5576, "text": "main() { \n int x = 12; \n int y = 0; \n int res; \n \n try { \n res = x ~/ y; \n } \n on IntegerDivisionByZeroException catch(e) { \n print(e); \n } \n} " }, { "code": null, "e": 5789, "s": 5748, "text": "It should produce the following output −" }, { "code": null, "e": 5821, "s": 5789, "text": "IntegerDivisionByZeroException\n" }, { "code": null, "e": 5992, "s": 5821, "text": "The finally block includes code that should be executed irrespective of an exception’s occurrence. The optional finally block executes unconditionally after try/on/catch." }, { "code": null, "e": 6047, "s": 5992, "text": "The syntax for using the finally block is as follows −" }, { "code": null, "e": 6287, "s": 6047, "text": "try { \n // code that might throw an exception \n} \non Exception1 { \n // exception handling code \n} \ncatch Exception2 { \n // exception handling \n} \nfinally { \n // code that should always execute; irrespective of the exception \n}\n" }, { "code": null, "e": 6347, "s": 6287, "text": "The following example illustrates the use of finally block." }, { "code": null, "e": 6590, "s": 6347, "text": "main() { \n int x = 12; \n int y = 0; \n int res; \n \n try { \n res = x ~/ y; \n } \n on IntegerDivisionByZeroException { \n print('Cannot divide by zero'); \n } \n finally { \n print('Finally block executed'); \n } \n}" }, { "code": null, "e": 6631, "s": 6590, "text": "It should produce the following output −" }, { "code": null, "e": 6678, "s": 6631, "text": "Cannot divide by zero \nFinally block executed\n" }, { "code": null, "e": 6821, "s": 6678, "text": "The throw keyword is used to explicitly raise an exception. A raised exception should be handled to prevent the program from exiting abruptly." }, { "code": null, "e": 6873, "s": 6821, "text": "The syntax for raising an exception explicitly is −" }, { "code": null, "e": 6901, "s": 6873, "text": "throw new Exception_name()\n" }, { "code": null, "e": 6982, "s": 6901, "text": "The following example shows how to use the throw keyword to throw an exception −" }, { "code": null, "e": 7180, "s": 6982, "text": "main() { \n try { \n test_age(-2); \n } \n catch(e) { \n print('Age cannot be negative'); \n } \n} \nvoid test_age(int age) { \n if(age<0) { \n throw new FormatException(); \n } \n}" }, { "code": null, "e": 7221, "s": 7180, "text": "It should produce the following output −" }, { "code": null, "e": 7245, "s": 7221, "text": "Age cannot be negative\n" }, { "code": null, "e": 7475, "s": 7245, "text": "As specified above, every exception type in Dart is a subtype of the built-in class Exception. Dart enables creating custom exceptions by extending the existing ones. The syntax for defining a custom exception is as given below −" }, { "code": null, "e": 7586, "s": 7475, "text": "class Custom_exception_Name implements Exception { \n // can contain constructors, variables and methods \n} \n" }, { "code": null, "e": 7676, "s": 7586, "text": "Custom Exceptions should be raised explicitly and the same should be handled in the code." }, { "code": null, "e": 7749, "s": 7676, "text": "The following example shows how to define and handle a custom exception." }, { "code": null, "e": 8127, "s": 7749, "text": "class AmtException implements Exception { \n String errMsg() => 'Amount should be greater than zero'; \n} \nvoid main() { \n try { \n withdraw_amt(-1); \n } \n catch(e) { \n print(e.errMsg()); \n } \n finally { \n print('Ending requested operation.....'); \n } \n} \nvoid withdraw_amt(int amt) { \n if (amt <= 0) { \n throw new AmtException(); \n } \n} " }, { "code": null, "e": 8358, "s": 8127, "text": "In the above code, we are defining a custom exception, AmtException. The code raises the exception if the amount passed is not within the excepted range. The main function encloses the function invocation in the try...catch block." }, { "code": null, "e": 8405, "s": 8358, "text": "The code should produce the following output −" }, { "code": null, "e": 8474, "s": 8405, "text": "Amount should be greater than zero \nEnding requested operation.... \n" }, { "code": null, "e": 8509, "s": 8474, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 8529, "s": 8509, "text": " Sriyank Siddhartha" }, { "code": null, "e": 8562, "s": 8529, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 8582, "s": 8562, "text": " Sriyank Siddhartha" }, { "code": null, "e": 8615, "s": 8582, "text": "\n 69 Lectures \n 4 hours \n" }, { "code": null, "e": 8632, "s": 8615, "text": " Frahaan Hussain" }, { "code": null, "e": 8667, "s": 8632, "text": "\n 117 Lectures \n 10 hours \n" }, { "code": null, "e": 8684, "s": 8667, "text": " Frahaan Hussain" }, { "code": null, "e": 8719, "s": 8684, "text": "\n 22 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8739, "s": 8719, "text": " Pranjal Srivastava" }, { "code": null, "e": 8772, "s": 8739, "text": "\n 34 Lectures \n 3 hours \n" }, { "code": null, "e": 8792, "s": 8772, "text": " Pranjal Srivastava" }, { "code": null, "e": 8799, "s": 8792, "text": " Print" }, { "code": null, "e": 8810, "s": 8799, "text": " Add Notes" } ]
HTML | <details> open Attribute - GeeksforGeeks
17 Oct, 2019 The HTML <details> open attribute is used to indicate whether the details will be display on page load. It is a boolean attribute. If this attribute is present then the detail will be visible. Syntax: <details open> Contents... </details> Example: This example illustrates the use of open attribute in <details> element. <!-- HTML program to illustrate details open Attribute --> <!DOCTYPE html> <html> <head> <title>HTML details open Attribute</title> </head> <body> <h1 style="text-align:center;"> GeeksForGeeks </h1> <h2 style = "color: green; text-align: center;"> HTML <Details>open Attribute </h2> <!-- Below details tag has "open" attribute --> <details open> <summary>Geeks classes</summary> <p> An extensive classroom programme to build and enhance Data Structures and Algorithm concepts. </p> </details> </body> </html> Output : Supported Browsers: The browser supported by HTML <details> open attribute are listed below: Google Chrome 12.0 Firefox 49.0 Safari 6.0 Opera 15.0 Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. shubham_singh HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Types of CSS (Cascading Style Sheet) How to Insert Form Data into Database using PHP ? REST API (Introduction) Design a web page using HTML and CSS Form validation using HTML and JavaScript Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript
[ { "code": null, "e": 25115, "s": 25087, "text": "\n17 Oct, 2019" }, { "code": null, "e": 25308, "s": 25115, "text": "The HTML <details> open attribute is used to indicate whether the details will be display on page load. It is a boolean attribute. If this attribute is present then the detail will be visible." }, { "code": null, "e": 25316, "s": 25308, "text": "Syntax:" }, { "code": null, "e": 25354, "s": 25316, "text": "<details open> Contents... </details>" }, { "code": null, "e": 25436, "s": 25354, "text": "Example: This example illustrates the use of open attribute in <details> element." }, { "code": "<!-- HTML program to illustrate details open Attribute --> <!DOCTYPE html> <html> <head> <title>HTML details open Attribute</title> </head> <body> <h1 style=\"text-align:center;\"> GeeksForGeeks </h1> <h2 style = \"color: green; text-align: center;\"> HTML <Details>open Attribute </h2> <!-- Below details tag has \"open\" attribute --> <details open> <summary>Geeks classes</summary> <p> An extensive classroom programme to build and enhance Data Structures and Algorithm concepts. </p> </details> </body> </html> ", "e": 26190, "s": 25436, "text": null }, { "code": null, "e": 26199, "s": 26190, "text": "Output :" }, { "code": null, "e": 26292, "s": 26199, "text": "Supported Browsers: The browser supported by HTML <details> open attribute are listed below:" }, { "code": null, "e": 26311, "s": 26292, "text": "Google Chrome 12.0" }, { "code": null, "e": 26324, "s": 26311, "text": "Firefox 49.0" }, { "code": null, "e": 26335, "s": 26324, "text": "Safari 6.0" }, { "code": null, "e": 26346, "s": 26335, "text": "Opera 15.0" }, { "code": null, "e": 26483, "s": 26346, "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": 26497, "s": 26483, "text": "shubham_singh" }, { "code": null, "e": 26513, "s": 26497, "text": "HTML-Attributes" }, { "code": null, "e": 26518, "s": 26513, "text": "HTML" }, { "code": null, "e": 26535, "s": 26518, "text": "Web Technologies" }, { "code": null, "e": 26540, "s": 26535, "text": "HTML" }, { "code": null, "e": 26638, "s": 26540, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26647, "s": 26638, "text": "Comments" }, { "code": null, "e": 26660, "s": 26647, "text": "Old Comments" }, { "code": null, "e": 26697, "s": 26660, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 26747, "s": 26697, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 26771, "s": 26747, "text": "REST API (Introduction)" }, { "code": null, "e": 26808, "s": 26771, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 26850, "s": 26808, "text": "Form validation using HTML and JavaScript" }, { "code": null, "e": 26906, "s": 26850, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 26939, "s": 26906, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26982, "s": 26939, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27043, "s": 26982, "text": "Difference between var, let and const keywords in JavaScript" } ]
TensorFlow 2.0: tf.function and AutoGraph | by Michael Grogan | Towards Data Science
With the advent of TensorFlow (TF) 2.0, the introduction of tf.function has brought about some useful improvements to TF 1.0, most notably the introduction of AutoGraph. Fundamentally, TensorFlow runs by means of computational graphs — i.e. a graph of nodes is used to represent a series of TensorFlow operations. However, compiling TensorFlow graphs can be a cumbersome process, given that the syntax structure differs significantly from Python, and graph code uses more resources than a simple Python structure. The purpose of AutoGraph is to graph code through the transformation of code written in Python’s classic syntax structure into TensorFlow graph-compatible code. This makes using Python and TensorFlow much more intuitive, as it eases the transition from Python code to graph code. More fundamentally, tf.function allows for the intuitive use of both eager execution and AutoGraph, whereby a function can be run using Python syntax initially and then transferred into the equivalent graph code. Let’s take an example. Here is a Python function for calculating the area of a circle. Eager execution is turned on by default in TF 2.0, and the value r (the radius of a circle) is being defined as a tf.Variable. >>> import tensorflow as tf>>> tf.executing_eagerly()>>> r = tf.Variable(10.0, name="r")>>> def area(r):>>> circle=3.14*(r**2.00)>>> return circle>>> area(10)314.0>>> print('Areas of respective circles: %2.2f, %2.2f, %2.2f' % (area(tf.constant(50.0)), area(tf.constant(100.0)), area(tf.constant(150.0))))Areas of respective circles: 7850.00, 31400.00, 70650.00 Now, suppose one wishes to implement this code using AutoGraph. Using TF 1.0 conventions, this would have been possible using tf.Session. Previously, a graph had to be explicitly launched in a Session in order to run. >>> r = tf.Variable(10.0, name="r")>>> def area(r):>>> circle=3.14*(r**2.00)>>> return circle>>> print(tf.autograph.to_code(area))def tf__area(r): do_return = False retval_ = ag__.UndefinedReturnValue() circle = 3.14 * r ** 2.0 do_return = True retval_ = circle cond = ag__.is_undefined_return(retval_) def get_state(): return () def set_state(_): pass def if_true(): retval_ = None return retval_ def if_false(): return retval_ retval_ = ag__.if_stmt(cond, if_true, if_false, get_state, set_state) return retval_ This is a sample of the code in graph format. >>> tf_area = tf.autograph.to_graph(area)>>> tf_area<function __main__.create_converted_entity_factory.<locals>.create_converted_entity.<locals>.tf__area(r)>>>> print(tf_area)<function create_converted_entity_factory.<locals>.create_converted_entity.<locals>.tf__area at 0x7f7b57f8a620>>>> with tf.Graph().as_default(): a1 = tf_area(tf.constant(50.0)) a2 = tf_area(tf.constant(100.0)) a3 = tf_area(tf.constant(150.0)) with tf.compat.v1.Session() as sess: print('Areas of respective circles (graph results): %2.2f, %2.2f, %2.2f\n' % (sess.run(a1), sess.run(a2), sess.run(a3)))Areas of respective circles (graph results): 7850.00, 31400.00, 70650.00 The use of a Session means that the area values for the circles calculated above will only be computed inside the Session itself. Let’s take a look at how this could be implemented using tf.function. >>> r = tf.Variable(10.0, name="r")>>> @tf.function>>> def area(r):>>> circle=3.14*(r**2.00)>>> return circle>>> print(tf.autograph.to_code(area.python_function))def tf__area(r): do_return = False retval_ = ag__.UndefinedReturnValue() circle = 3.14 * r ** 2.0 do_return = True retval_ = circle cond = ag__.is_undefined_return(retval_) def get_state(): return () def set_state(_): pass def if_true(): retval_ = None return retval_ def if_false(): return retval_ retval_ = ag__.if_stmt(cond, if_true, if_false, get_state, set_state) return retval_>>> area(60)<tf.Tensor: id=13, shape=(), dtype=float32, numpy=11304.0>>>> print(area(tf.constant(50.00)), area(tf.constant(100.0)), area(tf.constant(150.0)))tf.Tensor(7850.0005, shape=(), dtype=float32) tf.Tensor(31400.002, shape=(), dtype=float32) tf.Tensor(70650.0, shape=(), dtype=float32) As can be seen from the above, a Session is not needed to compute the area values. Instead, tf.function is used to specify the function which can be directly converted to AutoGraph, and then the area values are calculated as Tensors. In this example, we have seen how TF 2.0 simplifies function implementation in TensorFlow through the use of tf.function and AutoGraph. Many thanks for your time, and you can also find more examples of machine learning using TensorFlow and Keras at michael-grogan.com. Disclaimer: This article is written on an “as is” basis and without warranty. It was written with the intention of providing an overview of data science concepts, and should not be interpreted as professional advice in any way.
[ { "code": null, "e": 341, "s": 171, "text": "With the advent of TensorFlow (TF) 2.0, the introduction of tf.function has brought about some useful improvements to TF 1.0, most notably the introduction of AutoGraph." }, { "code": null, "e": 485, "s": 341, "text": "Fundamentally, TensorFlow runs by means of computational graphs — i.e. a graph of nodes is used to represent a series of TensorFlow operations." }, { "code": null, "e": 685, "s": 485, "text": "However, compiling TensorFlow graphs can be a cumbersome process, given that the syntax structure differs significantly from Python, and graph code uses more resources than a simple Python structure." }, { "code": null, "e": 965, "s": 685, "text": "The purpose of AutoGraph is to graph code through the transformation of code written in Python’s classic syntax structure into TensorFlow graph-compatible code. This makes using Python and TensorFlow much more intuitive, as it eases the transition from Python code to graph code." }, { "code": null, "e": 1178, "s": 965, "text": "More fundamentally, tf.function allows for the intuitive use of both eager execution and AutoGraph, whereby a function can be run using Python syntax initially and then transferred into the equivalent graph code." }, { "code": null, "e": 1201, "s": 1178, "text": "Let’s take an example." }, { "code": null, "e": 1392, "s": 1201, "text": "Here is a Python function for calculating the area of a circle. Eager execution is turned on by default in TF 2.0, and the value r (the radius of a circle) is being defined as a tf.Variable." }, { "code": null, "e": 1761, "s": 1392, "text": ">>> import tensorflow as tf>>> tf.executing_eagerly()>>> r = tf.Variable(10.0, name=\"r\")>>> def area(r):>>> circle=3.14*(r**2.00)>>> return circle>>> area(10)314.0>>> print('Areas of respective circles: %2.2f, %2.2f, %2.2f' % (area(tf.constant(50.0)), area(tf.constant(100.0)), area(tf.constant(150.0))))Areas of respective circles: 7850.00, 31400.00, 70650.00" }, { "code": null, "e": 1979, "s": 1761, "text": "Now, suppose one wishes to implement this code using AutoGraph. Using TF 1.0 conventions, this would have been possible using tf.Session. Previously, a graph had to be explicitly launched in a Session in order to run." }, { "code": null, "e": 2528, "s": 1979, "text": ">>> r = tf.Variable(10.0, name=\"r\")>>> def area(r):>>> circle=3.14*(r**2.00)>>> return circle>>> print(tf.autograph.to_code(area))def tf__area(r): do_return = False retval_ = ag__.UndefinedReturnValue() circle = 3.14 * r ** 2.0 do_return = True retval_ = circle cond = ag__.is_undefined_return(retval_) def get_state(): return () def set_state(_): pass def if_true(): retval_ = None return retval_ def if_false(): return retval_ retval_ = ag__.if_stmt(cond, if_true, if_false, get_state, set_state) return retval_" }, { "code": null, "e": 2574, "s": 2528, "text": "This is a sample of the code in graph format." }, { "code": null, "e": 3241, "s": 2574, "text": ">>> tf_area = tf.autograph.to_graph(area)>>> tf_area<function __main__.create_converted_entity_factory.<locals>.create_converted_entity.<locals>.tf__area(r)>>>> print(tf_area)<function create_converted_entity_factory.<locals>.create_converted_entity.<locals>.tf__area at 0x7f7b57f8a620>>>> with tf.Graph().as_default(): a1 = tf_area(tf.constant(50.0)) a2 = tf_area(tf.constant(100.0)) a3 = tf_area(tf.constant(150.0)) with tf.compat.v1.Session() as sess: print('Areas of respective circles (graph results): %2.2f, %2.2f, %2.2f\\n' % (sess.run(a1), sess.run(a2), sess.run(a3)))Areas of respective circles (graph results): 7850.00, 31400.00, 70650.00" }, { "code": null, "e": 3371, "s": 3241, "text": "The use of a Session means that the area values for the circles calculated above will only be computed inside the Session itself." }, { "code": null, "e": 3441, "s": 3371, "text": "Let’s take a look at how this could be implemented using tf.function." }, { "code": null, "e": 4314, "s": 3441, "text": ">>> r = tf.Variable(10.0, name=\"r\")>>> @tf.function>>> def area(r):>>> circle=3.14*(r**2.00)>>> return circle>>> print(tf.autograph.to_code(area.python_function))def tf__area(r): do_return = False retval_ = ag__.UndefinedReturnValue() circle = 3.14 * r ** 2.0 do_return = True retval_ = circle cond = ag__.is_undefined_return(retval_) def get_state(): return () def set_state(_): pass def if_true(): retval_ = None return retval_ def if_false(): return retval_ retval_ = ag__.if_stmt(cond, if_true, if_false, get_state, set_state) return retval_>>> area(60)<tf.Tensor: id=13, shape=(), dtype=float32, numpy=11304.0>>>> print(area(tf.constant(50.00)), area(tf.constant(100.0)), area(tf.constant(150.0)))tf.Tensor(7850.0005, shape=(), dtype=float32) tf.Tensor(31400.002, shape=(), dtype=float32) tf.Tensor(70650.0, shape=(), dtype=float32)" }, { "code": null, "e": 4548, "s": 4314, "text": "As can be seen from the above, a Session is not needed to compute the area values. Instead, tf.function is used to specify the function which can be directly converted to AutoGraph, and then the area values are calculated as Tensors." }, { "code": null, "e": 4817, "s": 4548, "text": "In this example, we have seen how TF 2.0 simplifies function implementation in TensorFlow through the use of tf.function and AutoGraph. Many thanks for your time, and you can also find more examples of machine learning using TensorFlow and Keras at michael-grogan.com." } ]
Print the corner elements and their sum in a 2-D matrix in C Program.
Given an array of size 2X2 and the challenge is to print the sum of all the corner elements stored in an array. Assume a matrix mat[r][c], with some row “r” and column “c” starting row and column from 0, then its corner elements will be; mat[0][0], mat[0][c-1], mat[r-1][0], mat[r-1][c-1]. Now the task is to get these corner elements and sum those corner elements i.e., mat[0][0] + mat[0][c-1] + mat[r-1][0] + mat[r-1][c-1], and print the result on the screen. Input: Enter the matrix elements : 10 2 10 2 3 4 10 4 10 Output: sum of matrix is : 40 START Step 1-> create macro for rows and column as #define row 3 and #define col 3 Step 2 -> main() Declare int sum=0 and array as a[row][col] and variables int i,j,n Loop For i=0 and i<3 and i++ Loop For j=0 and j<3 and j++ Input a[i][j] End End Print [0][0] + a[0][row-1] +a[col-1][0] + a[col-1][row-1] STOP #include<stdio.h> #define row 3 #define col 3 int main(){ int sum=0,a[row][col],i,j,n; printf("Enter the matrix elements : "); for(i=0;i<3;i++){ for(j=0;j<3;j++){ scanf("%d",&a[i][j]); } } printf("sum of matrix is : %d",a[0][0] + a[0][row-1] +a[col-1][0] + a[col-1][row-1] ); return 0; } if we run above program then it will generate following output Enter the matrix elements : 10 2 10 2 3 4 10 4 10 sum of matrix is : 40
[ { "code": null, "e": 1174, "s": 1062, "text": "Given an array of size 2X2 and the challenge is to print the sum of all the corner elements stored in an array." }, { "code": null, "e": 1524, "s": 1174, "text": "Assume a matrix mat[r][c], with some row “r” and column “c” starting row and column from 0, then its corner elements will be; mat[0][0], mat[0][c-1], mat[r-1][0], mat[r-1][c-1]. Now the task is to get these corner elements and sum those corner elements i.e., mat[0][0] + mat[0][c-1] + mat[r-1][0] + mat[r-1][c-1], and print the result on the screen." }, { "code": null, "e": 1620, "s": 1524, "text": "Input: Enter the matrix elements :\n 10 2 10\n 2 3 4\n 10 4 10\nOutput: sum of matrix is : 40" }, { "code": null, "e": 1963, "s": 1620, "text": "START\nStep 1-> create macro for rows and column as #define row 3 and #define col 3\nStep 2 -> main()\n Declare int sum=0 and array as a[row][col] and variables int i,j,n\n Loop For i=0 and i<3 and i++\n Loop For j=0 and j<3 and j++\n Input a[i][j]\n End\n End\n Print [0][0] + a[0][row-1] +a[col-1][0] + a[col-1][row-1]\nSTOP" }, { "code": null, "e": 2290, "s": 1963, "text": "#include<stdio.h>\n#define row 3\n#define col 3\nint main(){\n int sum=0,a[row][col],i,j,n;\n printf(\"Enter the matrix elements : \");\n for(i=0;i<3;i++){\n for(j=0;j<3;j++){\n scanf(\"%d\",&a[i][j]);\n }\n }\n printf(\"sum of matrix is : %d\",a[0][0] + a[0][row-1] +a[col-1][0] + a[col-1][row-1] );\n return 0;\n}" }, { "code": null, "e": 2353, "s": 2290, "text": "if we run above program then it will generate following output" }, { "code": null, "e": 2425, "s": 2353, "text": "Enter the matrix elements :\n10 2 10\n2 3 4\n10 4 10\nsum of matrix is : 40" } ]
MongoDB query to count the frequency of every element of the array
To count, you can also use aggregate() along with $sum. Let us create a collection with documents − > db.demo184.insertOne({"Names":["Chris","David","Bob"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e3999fb9e4f06af55199805") } > db.demo184.insertOne({"Names":["Chris","Mike"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e399a0d9e4f06af55199806") } > db.demo184.insertOne({"Names":["Chris","Bob","Carol"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e399a209e4f06af55199807") } Display all documents from a collection with the help of find() method − > db.demo184.find(); This will produce the following output − { "_id" : ObjectId("5e3999fb9e4f06af55199805"), "Names" : [ "Chris", "David", "Bob" ] } { "_id" : ObjectId("5e399a0d9e4f06af55199806"), "Names" : [ "Chris", "Mike" ] } { "_id" : ObjectId("5e399a209e4f06af55199807"), "Names" : [ "Chris", "Bob", "Carol" ] } Following is the query to count the frequency of every element − > db.demo184.aggregate([ ... { "$unwind" : "$Names" }, ... { "$group": { "_id": "$Names", "count": { "$sum": 1} } }, ... { "$group": { ... "_id": null, ... "counts": { ... "$push": { ... "k": "$_id", ... "v": "$count" ... } ... } ... } }, ... { "$replaceRoot": { ... "newRoot": { "$arrayToObject": "$counts" } ... } } ...]) This will produce the following output − { "Carol" : 1, "David" : 1, "Chris" : 3, "Bob" : 2, "Mike" : 1 }
[ { "code": null, "e": 1162, "s": 1062, "text": "To count, you can also use aggregate() along with $sum. Let us create a collection with documents −" }, { "code": null, "e": 1587, "s": 1162, "text": "> db.demo184.insertOne({\"Names\":[\"Chris\",\"David\",\"Bob\"]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e3999fb9e4f06af55199805\")\n}\n> db.demo184.insertOne({\"Names\":[\"Chris\",\"Mike\"]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e399a0d9e4f06af55199806\")\n}\n> db.demo184.insertOne({\"Names\":[\"Chris\",\"Bob\",\"Carol\"]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e399a209e4f06af55199807\")\n}" }, { "code": null, "e": 1660, "s": 1587, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1681, "s": 1660, "text": "> db.demo184.find();" }, { "code": null, "e": 1722, "s": 1681, "text": "This will produce the following output −" }, { "code": null, "e": 1978, "s": 1722, "text": "{ \"_id\" : ObjectId(\"5e3999fb9e4f06af55199805\"), \"Names\" : [ \"Chris\", \"David\", \"Bob\" ] }\n{ \"_id\" : ObjectId(\"5e399a0d9e4f06af55199806\"), \"Names\" : [ \"Chris\", \"Mike\" ] }\n{ \"_id\" : ObjectId(\"5e399a209e4f06af55199807\"), \"Names\" : [ \"Chris\", \"Bob\", \"Carol\" ] }" }, { "code": null, "e": 2043, "s": 1978, "text": "Following is the query to count the frequency of every element −" }, { "code": null, "e": 2464, "s": 2043, "text": "> db.demo184.aggregate([\n... { \"$unwind\" : \"$Names\" },\n... { \"$group\": { \"_id\": \"$Names\", \"count\": { \"$sum\": 1} } },\n... { \"$group\": {\n... \"_id\": null,\n... \"counts\": {\n... \"$push\": {\n... \"k\": \"$_id\",\n... \"v\": \"$count\"\n... }\n... }\n... } },\n... { \"$replaceRoot\": {\n... \"newRoot\": { \"$arrayToObject\": \"$counts\" }\n... } }\n...])" }, { "code": null, "e": 2505, "s": 2464, "text": "This will produce the following output −" }, { "code": null, "e": 2570, "s": 2505, "text": "{ \"Carol\" : 1, \"David\" : 1, \"Chris\" : 3, \"Bob\" : 2, \"Mike\" : 1 }" } ]
Get list of files and folders in Google Drive storage using Python - GeeksforGeeks
01 Oct, 2020 In this article, we are going to have a look at how can we get a list of files (or folders) stored in our Google Drive cloud storage using Google Drive API in Python. It is a REST API that allows you to leverage Google Drive storage from within your app or program. So, let’s create a simple Python script that communicates with Google Drive API. Python (2.6 or higher) A Google account with Google Drive enabled Google API client and Google OAuth libraries Install the required libraries by running this command: pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib Now, follow these steps to set up your Google account to work with Google Drive API. Go to Google Cloud console and sign in with your Google account. Create a new project. Create a new project Go to APIs and Services. Go to APIs and Services Enable Google Drive API for this project. Enable API Enable Google Drive API Go to the OAuth Consent screen and configure the Consent screen for your project. Go to OAuth Consent screen Select External and click on Create Enter the name of your application. It will be shown on the consent screen. Enter the application name and select email address Now go to Credentials. Go to Credentials Click on Create credentials, and go to OAuth Client ID. Click on Create Credentials and select OAuth Client ID Enter your application’s name, and click Create. Enter the Application Name and click on Create Your Client ID will be created. Download it to your computer and save it as credentials.json Download json file NOTE: Do not share your CLIENT ID or CLIENT SECRETS with anyone. Now, we are done with the setup and installation. So, let’s write the python script: Python3 # import the required librariesimport pickleimport os.pathfrom googleapiclient.discovery import buildfrom google_auth_oauthlib.flow import InstalledAppFlowfrom google.auth.transport.requests import Request # Define the SCOPES. If modifying it,# delete the token.pickle file.SCOPES = ['https://www.googleapis.com/auth/drive'] # Create a function getFileList with # parameter N which is the length of # the list of files.def getFileList(N): # Variable creds will store the user access token. # If no valid token found, we will create one. creds = None # The file token.pickle stores the # user's access and refresh tokens. It is # created automatically when the authorization # flow completes for the first time. # Check if file token.pickle exists if os.path.exists('token.pickle'): # Read the token from the file and # store it in the variable creds with open('token.pickle', 'rb') as token: creds = pickle.load(token) # If no valid credentials are available, # request the user to log in. if not creds or not creds.valid: # If token is expired, it will be refreshed, # else, we will request a new one. if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the access token in token.pickle # file for future usage with open('token.pickle', 'wb') as token: pickle.dump(creds, token) # Connect to the API service service = build('drive', 'v3', credentials=creds) # request a list of first N files or # folders with name and id from the API. resource = service.files() result = resource.list(pageSize=N, fields="files(id, name)").execute() # return the result dictionary containing # the information about the files return result # Get list of first 5 files or # folders from our Google Drive Storageresult_dict = getFileList(5) # Extract the list from the dictionaryfile_list = result_dict.get('files') # Print every file's namefor file in file_list: print(file['name']) Now, run the script: python3 script.py This will attempt to open a new window in your default browser. If this fails, copy the URL from the console and manually open it in your browser. Now, Log in to your Google account if you aren’t already logged in. If there are multiple accounts, you will be asked to choose one of them. Then, click on the Allow button. After the authentication has been completed, your browser will display a message saying The authentication flow has been completed. You may close this window. Once the authentication has been completed, this will print the names of first N files (or folders) in your Google Drive storage. Note: The file credentials.json should be in the same directory as the Python script. If not so, you have to specify the full path to the file in the program. python-file-handling Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python
[ { "code": null, "e": 24938, "s": 24910, "text": "\n01 Oct, 2020" }, { "code": null, "e": 25204, "s": 24938, "text": "In this article, we are going to have a look at how can we get a list of files (or folders) stored in our Google Drive cloud storage using Google Drive API in Python. It is a REST API that allows you to leverage Google Drive storage from within your app or program." }, { "code": null, "e": 25285, "s": 25204, "text": "So, let’s create a simple Python script that communicates with Google Drive API." }, { "code": null, "e": 25308, "s": 25285, "text": "Python (2.6 or higher)" }, { "code": null, "e": 25351, "s": 25308, "text": "A Google account with Google Drive enabled" }, { "code": null, "e": 25396, "s": 25351, "text": "Google API client and Google OAuth libraries" }, { "code": null, "e": 25452, "s": 25396, "text": "Install the required libraries by running this command:" }, { "code": null, "e": 25542, "s": 25452, "text": "pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib\n" }, { "code": null, "e": 25627, "s": 25542, "text": "Now, follow these steps to set up your Google account to work with Google Drive API." }, { "code": null, "e": 25692, "s": 25627, "text": "Go to Google Cloud console and sign in with your Google account." }, { "code": null, "e": 25714, "s": 25692, "text": "Create a new project." }, { "code": null, "e": 25735, "s": 25714, "text": "Create a new project" }, { "code": null, "e": 25760, "s": 25735, "text": "Go to APIs and Services." }, { "code": null, "e": 25784, "s": 25760, "text": "Go to APIs and Services" }, { "code": null, "e": 25826, "s": 25784, "text": "Enable Google Drive API for this project." }, { "code": null, "e": 25837, "s": 25826, "text": "Enable API" }, { "code": null, "e": 25861, "s": 25837, "text": "Enable Google Drive API" }, { "code": null, "e": 25943, "s": 25861, "text": "Go to the OAuth Consent screen and configure the Consent screen for your project." }, { "code": null, "e": 25970, "s": 25943, "text": "Go to OAuth Consent screen" }, { "code": null, "e": 26006, "s": 25970, "text": "Select External and click on Create" }, { "code": null, "e": 26082, "s": 26006, "text": "Enter the name of your application. It will be shown on the consent screen." }, { "code": null, "e": 26134, "s": 26082, "text": "Enter the application name and select email address" }, { "code": null, "e": 26157, "s": 26134, "text": "Now go to Credentials." }, { "code": null, "e": 26175, "s": 26157, "text": "Go to Credentials" }, { "code": null, "e": 26231, "s": 26175, "text": "Click on Create credentials, and go to OAuth Client ID." }, { "code": null, "e": 26286, "s": 26231, "text": "Click on Create Credentials and select OAuth Client ID" }, { "code": null, "e": 26335, "s": 26286, "text": "Enter your application’s name, and click Create." }, { "code": null, "e": 26382, "s": 26335, "text": "Enter the Application Name and click on Create" }, { "code": null, "e": 26475, "s": 26382, "text": "Your Client ID will be created. Download it to your computer and save it as credentials.json" }, { "code": null, "e": 26494, "s": 26475, "text": "Download json file" }, { "code": null, "e": 26559, "s": 26494, "text": "NOTE: Do not share your CLIENT ID or CLIENT SECRETS with anyone." }, { "code": null, "e": 26644, "s": 26559, "text": "Now, we are done with the setup and installation. So, let’s write the python script:" }, { "code": null, "e": 26652, "s": 26644, "text": "Python3" }, { "code": "# import the required librariesimport pickleimport os.pathfrom googleapiclient.discovery import buildfrom google_auth_oauthlib.flow import InstalledAppFlowfrom google.auth.transport.requests import Request # Define the SCOPES. If modifying it,# delete the token.pickle file.SCOPES = ['https://www.googleapis.com/auth/drive'] # Create a function getFileList with # parameter N which is the length of # the list of files.def getFileList(N): # Variable creds will store the user access token. # If no valid token found, we will create one. creds = None # The file token.pickle stores the # user's access and refresh tokens. It is # created automatically when the authorization # flow completes for the first time. # Check if file token.pickle exists if os.path.exists('token.pickle'): # Read the token from the file and # store it in the variable creds with open('token.pickle', 'rb') as token: creds = pickle.load(token) # If no valid credentials are available, # request the user to log in. if not creds or not creds.valid: # If token is expired, it will be refreshed, # else, we will request a new one. if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the access token in token.pickle # file for future usage with open('token.pickle', 'wb') as token: pickle.dump(creds, token) # Connect to the API service service = build('drive', 'v3', credentials=creds) # request a list of first N files or # folders with name and id from the API. resource = service.files() result = resource.list(pageSize=N, fields=\"files(id, name)\").execute() # return the result dictionary containing # the information about the files return result # Get list of first 5 files or # folders from our Google Drive Storageresult_dict = getFileList(5) # Extract the list from the dictionaryfile_list = result_dict.get('files') # Print every file's namefor file in file_list: print(file['name'])", "e": 28933, "s": 26652, "text": null }, { "code": null, "e": 28954, "s": 28933, "text": "Now, run the script:" }, { "code": null, "e": 28973, "s": 28954, "text": "python3 script.py\n" }, { "code": null, "e": 29120, "s": 28973, "text": "This will attempt to open a new window in your default browser. If this fails, copy the URL from the console and manually open it in your browser." }, { "code": null, "e": 29294, "s": 29120, "text": "Now, Log in to your Google account if you aren’t already logged in. If there are multiple accounts, you will be asked to choose one of them. Then, click on the Allow button." }, { "code": null, "e": 29453, "s": 29294, "text": "After the authentication has been completed, your browser will display a message saying The authentication flow has been completed. You may close this window." }, { "code": null, "e": 29583, "s": 29453, "text": "Once the authentication has been completed, this will print the names of first N files (or folders) in your Google Drive storage." }, { "code": null, "e": 29742, "s": 29583, "text": "Note: The file credentials.json should be in the same directory as the Python script. If not so, you have to specify the full path to the file in the program." }, { "code": null, "e": 29763, "s": 29742, "text": "python-file-handling" }, { "code": null, "e": 29770, "s": 29763, "text": "Python" }, { "code": null, "e": 29868, "s": 29770, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29886, "s": 29868, "text": "Python Dictionary" }, { "code": null, "e": 29921, "s": 29886, "text": "Read a file line by line in Python" }, { "code": null, "e": 29943, "s": 29921, "text": "Enumerate() in Python" }, { "code": null, "e": 29975, "s": 29943, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30005, "s": 29975, "text": "Iterate over a list in Python" }, { "code": null, "e": 30047, "s": 30005, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 30073, "s": 30047, "text": "Python String | replace()" }, { "code": null, "e": 30110, "s": 30073, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 30153, "s": 30110, "text": "Python program to convert a list to string" } ]
Android imageView Zoom-in and Zoom-Out using Kotlin?
This example demonstrates how to implement Android imageView zoom-in and Zoom out using kotlin. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" android:padding="16dp" tools:context=".MainActivity"> <ImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="match_parent" android:src="@drawable/image" /> </LinearLayout> Step 3 − Add the following code to src/MainActivity.kt import android.os.Bundle import android.view.MotionEvent import android.view.ScaleGestureDetector import android.view.ScaleGestureDetector.SimpleOnScaleGestureListener import android.widget.ImageView import androidx.appcompat.app.AppCompatActivity import kotlin.math.max import kotlin.math.min class MainActivity : AppCompatActivity() { private lateinit var scaleGestureDetector: ScaleGestureDetector private var scaleFactor = 1.0f private lateinit var imageView: ImageView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" imageView = findViewById(R.id.imageView) scaleGestureDetector = ScaleGestureDetector(this, ScaleListener()) } override fun onTouchEvent(motionEvent: MotionEvent): Boolean { scaleGestureDetector.onTouchEvent(motionEvent) return true } private inner class ScaleListener : SimpleOnScaleGestureListener() { override fun onScale(scaleGestureDetector: ScaleGestureDetector): Boolean { scaleFactor *= scaleGestureDetector.scaleFactor scaleFactor = max(0.1f, min(scaleFactor, 10.0f)) imageView.scaleX = scaleFactor imageView.scaleY = scaleFactor return true } } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.q11"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
[ { "code": null, "e": 1158, "s": 1062, "text": "This example demonstrates how to implement Android imageView zoom-in and Zoom out using kotlin." }, { "code": null, "e": 1287, "s": 1158, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1352, "s": 1287, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1900, "s": 1352, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\nxmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:gravity=\"center\"\n android:orientation=\"vertical\"\n android:padding=\"16dp\"\n tools:context=\".MainActivity\">\n <ImageView\n android:id=\"@+id/imageView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:src=\"@drawable/image\" />\n</LinearLayout>" }, { "code": null, "e": 1955, "s": 1900, "text": "Step 3 − Add the following code to src/MainActivity.kt" }, { "code": null, "e": 3258, "s": 1955, "text": "import android.os.Bundle\nimport android.view.MotionEvent\nimport android.view.ScaleGestureDetector\nimport android.view.ScaleGestureDetector.SimpleOnScaleGestureListener\nimport android.widget.ImageView\nimport androidx.appcompat.app.AppCompatActivity\nimport kotlin.math.max\nimport kotlin.math.min\nclass MainActivity : AppCompatActivity() {\n private lateinit var scaleGestureDetector: ScaleGestureDetector\n private var scaleFactor = 1.0f\n private lateinit var imageView: ImageView\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n imageView = findViewById(R.id.imageView)\n scaleGestureDetector = ScaleGestureDetector(this, ScaleListener())\n }\n override fun onTouchEvent(motionEvent: MotionEvent): Boolean {\n scaleGestureDetector.onTouchEvent(motionEvent)\n return true\n }\n private inner class ScaleListener : SimpleOnScaleGestureListener() {\n override fun onScale(scaleGestureDetector: ScaleGestureDetector): Boolean {\n scaleFactor *= scaleGestureDetector.scaleFactor\n scaleFactor = max(0.1f, min(scaleFactor, 10.0f))\n imageView.scaleX = scaleFactor\n imageView.scaleY = scaleFactor\n return true\n }\n }\n}" }, { "code": null, "e": 3313, "s": 3258, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3980, "s": 3313, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4328, "s": 3980, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen" } ]
Valid Palindrome in Python
Suppose we have a string with alphanumeric values and symbols. There are lower case and uppercase letters as well. We have to check whether the string is forming a palindrome or not by considering only the lowercase letters (uppercases will be converted into lower case), other symbols like a comma, space will be ignored. Suppose the string is like “A Man, a Plan, a Canal: Panama”, then by considering these rules, it will be “amanaplanacanalpanama”. This is a palindrome. To solve this, follow these steps − define x = “” read each character c in str −if c is lowercase letter or number, then append c into xelse c is an uppercase letter, then simply convert it to lowercase and append after x if c is lowercase letter or number, then append c into x else c is an uppercase letter, then simply convert it to lowercase and append after x if x is a palindrome, then return True, otherwise False Let us see the implementation to get a better understanding Live Demo class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ x = "" diff = ord('a') - ord('A') for i in s: if ord(i)>=ord('a') and ord(i)<=ord('z') or ord(i)>=ord("0") and ord(i)<=ord("9"): x+=i elif ord(i)>=ord('A') and ord(i)<=ord('Z'): i = chr(diff+ord(i)) x+=i #print(s) #print(x) return x == x[::-1] ob1 = Solution() print(ob1.isPalindrome("A Man, a Plan, a Canal: Panama")) s = "A Man, a Plan, a Canal: Panama" true
[ { "code": null, "e": 1385, "s": 1062, "text": "Suppose we have a string with alphanumeric values and symbols. There are lower case and uppercase letters as well. We have to check whether the string is forming a palindrome or not by considering only the lowercase letters (uppercases will be converted into lower case), other symbols like a comma, space will be ignored." }, { "code": null, "e": 1537, "s": 1385, "text": "Suppose the string is like “A Man, a Plan, a Canal: Panama”, then by considering these rules, it will be “amanaplanacanalpanama”. This is a palindrome." }, { "code": null, "e": 1573, "s": 1537, "text": "To solve this, follow these steps −" }, { "code": null, "e": 1587, "s": 1573, "text": "define x = “”" }, { "code": null, "e": 1759, "s": 1587, "text": "read each character c in str −if c is lowercase letter or number, then append c into xelse c is an uppercase letter, then simply convert it to lowercase and append after x" }, { "code": null, "e": 1816, "s": 1759, "text": "if c is lowercase letter or number, then append c into x" }, { "code": null, "e": 1902, "s": 1816, "text": "else c is an uppercase letter, then simply convert it to lowercase and append after x" }, { "code": null, "e": 1958, "s": 1902, "text": "if x is a palindrome, then return True, otherwise False" }, { "code": null, "e": 2018, "s": 1958, "text": "Let us see the implementation to get a better understanding" }, { "code": null, "e": 2029, "s": 2018, "text": " Live Demo" }, { "code": null, "e": 2550, "s": 2029, "text": "class Solution(object):\n def isPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n x = \"\"\n diff = ord('a') - ord('A')\n for i in s:\n if ord(i)>=ord('a') and ord(i)<=ord('z') or ord(i)>=ord(\"0\") and ord(i)<=ord(\"9\"):\n x+=i\n elif ord(i)>=ord('A') and ord(i)<=ord('Z'):\n i = chr(diff+ord(i))\n x+=i\n #print(s)\n #print(x)\n return x == x[::-1]\nob1 = Solution()\nprint(ob1.isPalindrome(\"A Man, a Plan, a Canal: Panama\"))" }, { "code": null, "e": 2587, "s": 2550, "text": "s = \"A Man, a Plan, a Canal: Panama\"" }, { "code": null, "e": 2592, "s": 2587, "text": "true" } ]
How to check total space and available space in Linux using the terminal?
In the Linux/Unix system to check storage details, we use the df command. the df command is used to report file system disk space usage using the terminal in the Linux system. It displays total space, used space, and available space. The general syntax of the df command is as follow: $ df [OPTION]... [FILE]... Brief description of options available in the df command. To check space usage, we use the df command. By default, it is hard to understand the output of the df command. $ df The below snapshot is the output screen after the execution of the df command in the Linux system. We can see that /dev/sda5 (root partition) 9736500 have total size 5813352 have used size and 3408844 have available size but what are these numbers? These numbers don’t have any units so we can’t understand. Make it human readable there is an option available -h or --human-readable that makes it readable. To display output in human readable format, we use -h or --human-readable option with the df command as shown in below. $ df --human-readable Or $ df -h After executing above command, it reports the disk space usage in human readable form then we can easily understand disk space usage. To display output in powers of 1000, we use -H or --si option with the df command in the Linux system using terminal $ df --si Or $ df -H After executing above command, it reports the disk space usage in powers of 1000. Now we can easily understand disk space usage because we are more familiar with GB. For more details about df command and check option description use below command. $ df --help And check the version information of df command use below command. $ df --version
[ { "code": null, "e": 1136, "s": 1062, "text": "In the Linux/Unix system to check storage details, we use the df command." }, { "code": null, "e": 1296, "s": 1136, "text": "the df command is used to report file system disk space usage using the terminal in the Linux system. It displays total space, used space, and available space." }, { "code": null, "e": 1347, "s": 1296, "text": "The general syntax of the df command is as follow:" }, { "code": null, "e": 1374, "s": 1347, "text": "$ df [OPTION]... [FILE]..." }, { "code": null, "e": 1432, "s": 1374, "text": "Brief description of options available in the df command." }, { "code": null, "e": 1544, "s": 1432, "text": "To check space usage, we use the df command. By default, it is hard to understand the output of the df command." }, { "code": null, "e": 1549, "s": 1544, "text": "$ df" }, { "code": null, "e": 1648, "s": 1549, "text": "The below snapshot is the output screen after the execution of the df command in the Linux system." }, { "code": null, "e": 1857, "s": 1648, "text": "We can see that /dev/sda5 (root partition) 9736500 have total size 5813352 have used size and 3408844 have available size but what are these numbers? These numbers don’t have any units so we can’t understand." }, { "code": null, "e": 1956, "s": 1857, "text": "Make it human readable there is an option available -h or --human-readable that makes it readable." }, { "code": null, "e": 2076, "s": 1956, "text": "To display output in human readable format, we use -h or --human-readable option with the df command as shown in below." }, { "code": null, "e": 2098, "s": 2076, "text": "$ df --human-readable" }, { "code": null, "e": 2101, "s": 2098, "text": "Or" }, { "code": null, "e": 2109, "s": 2101, "text": "$ df -h" }, { "code": null, "e": 2243, "s": 2109, "text": "After executing above command, it reports the disk space usage in human readable form then we can easily understand disk space usage." }, { "code": null, "e": 2360, "s": 2243, "text": "To display output in powers of 1000, we use -H or --si option with the df command in the Linux system using terminal" }, { "code": null, "e": 2370, "s": 2360, "text": "$ df --si" }, { "code": null, "e": 2373, "s": 2370, "text": "Or" }, { "code": null, "e": 2381, "s": 2373, "text": "$ df -H" }, { "code": null, "e": 2547, "s": 2381, "text": "After executing above command, it reports the disk space usage in powers of 1000. Now we can easily understand disk space usage because we are more familiar with GB." }, { "code": null, "e": 2629, "s": 2547, "text": "For more details about df command and check option description use below command." }, { "code": null, "e": 2641, "s": 2629, "text": "$ df --help" }, { "code": null, "e": 2708, "s": 2641, "text": "And check the version information of df command use below command." }, { "code": null, "e": 2723, "s": 2708, "text": "$ df --version" } ]
Venn Diagrams — An Underrated Data Visualization | by Sidney Kung | Towards Data Science
The primary goal of a data visualization is to represent a point in a clear, compelling way. As Data Scientists, we’re always aiming to create the coolest, most innovative types of data visualizations. To the point where the actual message is lost. Why over complicate things? Sometimes, a simple message only requires a simple visualization to convey it. In this blog, I’ll be sharing a brief tutorial on how you can easily create a venn diagram with Matplotlib and any kind of data. In my recent project, Twitter Hate Speech Detection, I faced a major challenge with the class imbalance with the data. The entire dataset was 24,802 text tweets, where only 6% was labeled as hate speech. At the end, this class imbalance had an impact on my final model’s results. You can check out the final project’s repository here for more details. When I was creating the presentation for this project, I needed a way to visualize this problem. Additionally, I wanted to find the number of words that were exclusive to the Hate Speech label, and didn’t overlap with plain offensive language. And then it hit me, a venn diagram could display this concept perfectly. Here is the final product. Before I dive into the tutorial, let’s go back to basics for a second. We’ve all learned about this simple visualization in elementary school. A venn diagram is a diagram made out of two or more circles that overlap to show the logical relationships between sets. As we know, a set contains the unique values from a dataset. Therefore, this venn diagram shows the unique words from each label, and those that overlap. Creating venn diagrams in Python is extremely simple. Not many people know this, but the popular data visualization package matplotlib has an extension that can create customizable venn diagrams. You can check out the documentation here. The first step will always be to install the package onto your local machine. pip install matplotlib-venn Since it’s based onmatplotlib, you’ll need to import matplotlib’s dependencies such as numpy and scipy as well. Once the package is installed, you will need to feed in your data as a set. I’m not going to dive into the specifics of my code, but can check it all out in this notebook. First, I separated the tweets in each label, and then used a map function to turn the tokenized words into two separate lists. From there, I used list comprehension to turn those into nested lists to query through. After your data is in a suitable format, we can import the package into the notebook itself. import matplotlib_venn as vennfrom matplotlib_venn import venn2, venn2_circles, venn3, venn3_circlesimport matplotlib.pyplot as plt%matplotlib inline From there, the code to create a venn diagram is as simple as one line of code. venn2([set(label_1), set(label_2)]) However, the beauty of this package is that it’s very customizable. You can add a title and labels by adding this code to that original line. venn2([set(label_1), set(label_2)], set_labels = ('Hate Speech', 'Not Hate Speech'))plt.title('Comparison of Unique Words in Each Corpus Label') The final step would be to save the figure and use it in a presentation! plt.savefig('venn_diagram.png', bbox_inches = "tight", pad_inches=.5) Aside from the title and labels, you can also add more circles, change the color of the circles, add outlines, change the sizes and much more. There are other blogs out there that detail how to do that, and I’ll link those below. How to Create and Customize Venn Diagrams in Python How to Design Professional Venn Diagrams in Python With the exploratory data analysis stage, we are constantly asking questions about the data and drawing upon hidden insights. And the next time you find yourself creating a complex visualization and struggling to communicate those insights, the solution could be to simplify it. We shouldn’t overlook basic visualizations such as venn diagrams!
[ { "code": null, "e": 531, "s": 46, "text": "The primary goal of a data visualization is to represent a point in a clear, compelling way. As Data Scientists, we’re always aiming to create the coolest, most innovative types of data visualizations. To the point where the actual message is lost. Why over complicate things? Sometimes, a simple message only requires a simple visualization to convey it. In this blog, I’ll be sharing a brief tutorial on how you can easily create a venn diagram with Matplotlib and any kind of data." }, { "code": null, "e": 883, "s": 531, "text": "In my recent project, Twitter Hate Speech Detection, I faced a major challenge with the class imbalance with the data. The entire dataset was 24,802 text tweets, where only 6% was labeled as hate speech. At the end, this class imbalance had an impact on my final model’s results. You can check out the final project’s repository here for more details." }, { "code": null, "e": 1227, "s": 883, "text": "When I was creating the presentation for this project, I needed a way to visualize this problem. Additionally, I wanted to find the number of words that were exclusive to the Hate Speech label, and didn’t overlap with plain offensive language. And then it hit me, a venn diagram could display this concept perfectly. Here is the final product." }, { "code": null, "e": 1645, "s": 1227, "text": "Before I dive into the tutorial, let’s go back to basics for a second. We’ve all learned about this simple visualization in elementary school. A venn diagram is a diagram made out of two or more circles that overlap to show the logical relationships between sets. As we know, a set contains the unique values from a dataset. Therefore, this venn diagram shows the unique words from each label, and those that overlap." }, { "code": null, "e": 1961, "s": 1645, "text": "Creating venn diagrams in Python is extremely simple. Not many people know this, but the popular data visualization package matplotlib has an extension that can create customizable venn diagrams. You can check out the documentation here. The first step will always be to install the package onto your local machine." }, { "code": null, "e": 1989, "s": 1961, "text": "pip install matplotlib-venn" }, { "code": null, "e": 2101, "s": 1989, "text": "Since it’s based onmatplotlib, you’ll need to import matplotlib’s dependencies such as numpy and scipy as well." }, { "code": null, "e": 2488, "s": 2101, "text": "Once the package is installed, you will need to feed in your data as a set. I’m not going to dive into the specifics of my code, but can check it all out in this notebook. First, I separated the tweets in each label, and then used a map function to turn the tokenized words into two separate lists. From there, I used list comprehension to turn those into nested lists to query through." }, { "code": null, "e": 2581, "s": 2488, "text": "After your data is in a suitable format, we can import the package into the notebook itself." }, { "code": null, "e": 2731, "s": 2581, "text": "import matplotlib_venn as vennfrom matplotlib_venn import venn2, venn2_circles, venn3, venn3_circlesimport matplotlib.pyplot as plt%matplotlib inline" }, { "code": null, "e": 2811, "s": 2731, "text": "From there, the code to create a venn diagram is as simple as one line of code." }, { "code": null, "e": 2847, "s": 2811, "text": "venn2([set(label_1), set(label_2)])" }, { "code": null, "e": 2989, "s": 2847, "text": "However, the beauty of this package is that it’s very customizable. You can add a title and labels by adding this code to that original line." }, { "code": null, "e": 3134, "s": 2989, "text": "venn2([set(label_1), set(label_2)], set_labels = ('Hate Speech', 'Not Hate Speech'))plt.title('Comparison of Unique Words in Each Corpus Label')" }, { "code": null, "e": 3207, "s": 3134, "text": "The final step would be to save the figure and use it in a presentation!" }, { "code": null, "e": 3277, "s": 3207, "text": "plt.savefig('venn_diagram.png', bbox_inches = \"tight\", pad_inches=.5)" }, { "code": null, "e": 3507, "s": 3277, "text": "Aside from the title and labels, you can also add more circles, change the color of the circles, add outlines, change the sizes and much more. There are other blogs out there that detail how to do that, and I’ll link those below." }, { "code": null, "e": 3559, "s": 3507, "text": "How to Create and Customize Venn Diagrams in Python" }, { "code": null, "e": 3610, "s": 3559, "text": "How to Design Professional Venn Diagrams in Python" } ]
Node.js - Scaling Application
Node.js runs in a single-thread mode, but it uses an event-driven paradigm to handle concurrency. It also facilitates creation of child processes to leverage parallel processing on multi-core CPU based systems. Child processes always have three streams child.stdin, child.stdout, and child.stderr which may be shared with the stdio streams of the parent process. Node provides child_process module which has the following three major ways to create a child process. exec − child_process.exec method runs a command in a shell/console and buffers the output. exec − child_process.exec method runs a command in a shell/console and buffers the output. spawn − child_process.spawn launches a new process with a given command. spawn − child_process.spawn launches a new process with a given command. fork − The child_process.fork method is a special case of the spawn() to create child processes. fork − The child_process.fork method is a special case of the spawn() to create child processes. child_process.exec method runs a command in a shell and buffers the output. It has the following signature − child_process.exec(command[, options], callback) Here is the description of the parameters used − command (String) The command to run, with space-separated arguments command (String) The command to run, with space-separated arguments options (Object) may comprise one or more of the following options − cwd (String) Current working directory of the child process env (Object) Environment key-value pairs encoding (String) (Default: 'utf8') shell (String) Shell to execute the command with (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should understand the -c switch on UNIX or /s /c on Windows. On Windows, command line parsing should be compatible with cmd.exe.) timeout (Number) (Default: 0) maxBuffer (Number) (Default: 200*1024) killSignal (String) (Default: 'SIGTERM') uid (Number) Sets the user identity of the process. gid (Number) Sets the group identity of the process. options (Object) may comprise one or more of the following options − cwd (String) Current working directory of the child process cwd (String) Current working directory of the child process env (Object) Environment key-value pairs env (Object) Environment key-value pairs encoding (String) (Default: 'utf8') encoding (String) (Default: 'utf8') shell (String) Shell to execute the command with (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should understand the -c switch on UNIX or /s /c on Windows. On Windows, command line parsing should be compatible with cmd.exe.) shell (String) Shell to execute the command with (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should understand the -c switch on UNIX or /s /c on Windows. On Windows, command line parsing should be compatible with cmd.exe.) timeout (Number) (Default: 0) timeout (Number) (Default: 0) maxBuffer (Number) (Default: 200*1024) maxBuffer (Number) (Default: 200*1024) killSignal (String) (Default: 'SIGTERM') killSignal (String) (Default: 'SIGTERM') uid (Number) Sets the user identity of the process. uid (Number) Sets the user identity of the process. gid (Number) Sets the group identity of the process. gid (Number) Sets the group identity of the process. callback The function gets three arguments error, stdout, and stderr which are called with the output when the process terminates. callback The function gets three arguments error, stdout, and stderr which are called with the output when the process terminates. The exec() method returns a buffer with a max size and waits for the process to end and tries to return all the buffered data at once. Let us create two js files named support.js and master.js − File: support.js console.log("Child Process " + process.argv[2] + " executed." ); File: master.js const fs = require('fs'); const child_process = require('child_process'); for(var i=0; i<3; i++) { var workerProcess = child_process.exec('node support.js '+i,function (error, stdout, stderr) { if (error) { console.log(error.stack); console.log('Error code: '+error.code); console.log('Signal received: '+error.signal); } console.log('stdout: ' + stdout); console.log('stderr: ' + stderr); }); workerProcess.on('exit', function (code) { console.log('Child process exited with exit code '+code); }); } Now run the master.js to see the result − $ node master.js Verify the Output. Server has started. Child process exited with exit code 0 stdout: Child Process 1 executed. stderr: Child process exited with exit code 0 stdout: Child Process 0 executed. stderr: Child process exited with exit code 0 stdout: Child Process 2 executed. child_process.spawn method launches a new process with a given command. It has the following signature − child_process.spawn(command[, args][, options]) Here is the description of the parameters used − command (String) The command to run command (String) The command to run args (Array) List of string arguments args (Array) List of string arguments options (Object) may comprise one or more of the following options − cwd (String) Current working directory of the child process. env (Object) Environment key-value pairs. stdio (Array) String Child's stdio configuration. customFds (Array) Deprecated File descriptors for the child to use for stdio. detached (Boolean) The child will be a process group leader. uid (Number) Sets the user identity of the process. gid (Number) Sets the group identity of the process. options (Object) may comprise one or more of the following options − cwd (String) Current working directory of the child process. cwd (String) Current working directory of the child process. env (Object) Environment key-value pairs. env (Object) Environment key-value pairs. stdio (Array) String Child's stdio configuration. stdio (Array) String Child's stdio configuration. customFds (Array) Deprecated File descriptors for the child to use for stdio. customFds (Array) Deprecated File descriptors for the child to use for stdio. detached (Boolean) The child will be a process group leader. detached (Boolean) The child will be a process group leader. uid (Number) Sets the user identity of the process. uid (Number) Sets the user identity of the process. gid (Number) Sets the group identity of the process. gid (Number) Sets the group identity of the process. The spawn() method returns streams (stdout &stderr) and it should be used when the process returns a volume amount of data. spawn() starts receiving the response as soon as the process starts executing. Create two js files named support.js and master.js − File: support.js console.log("Child Process " + process.argv[2] + " executed." ); File: master.js const fs = require('fs'); const child_process = require('child_process'); for(var i = 0; i<3; i++) { var workerProcess = child_process.spawn('node', ['support.js', i]); workerProcess.stdout.on('data', function (data) { console.log('stdout: ' + data); }); workerProcess.stderr.on('data', function (data) { console.log('stderr: ' + data); }); workerProcess.on('close', function (code) { console.log('child process exited with code ' + code); }); } Now run the master.js to see the result − $ node master.js Verify the Output. Server has started stdout: Child Process 0 executed. child process exited with code 0 stdout: Child Process 1 executed. stdout: Child Process 2 executed. child process exited with code 0 child process exited with code 0 child_process.fork method is a special case of spawn() to create Node processes. It has the following signature − child_process.fork(modulePath[, args][, options]) Here is the description of the parameters used − modulePath (String) The module to run in the child. modulePath (String) The module to run in the child. args (Array) List of string arguments args (Array) List of string arguments options (Object) may comprise one or more of the following options − cwd (String) Current working directory of the child process. env (Object) Environment key-value pairs. execPath (String) Executable used to create the child process. execArgv (Array) List of string arguments passed to the executable (Default: process.execArgv). silent (Boolean) If true, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent, see the "pipe" and "inherit" options for spawn()'s stdio for more details (default is false). uid (Number) Sets the user identity of the process. gid (Number) Sets the group identity of the process. options (Object) may comprise one or more of the following options − cwd (String) Current working directory of the child process. cwd (String) Current working directory of the child process. env (Object) Environment key-value pairs. env (Object) Environment key-value pairs. execPath (String) Executable used to create the child process. execPath (String) Executable used to create the child process. execArgv (Array) List of string arguments passed to the executable (Default: process.execArgv). execArgv (Array) List of string arguments passed to the executable (Default: process.execArgv). silent (Boolean) If true, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent, see the "pipe" and "inherit" options for spawn()'s stdio for more details (default is false). silent (Boolean) If true, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent, see the "pipe" and "inherit" options for spawn()'s stdio for more details (default is false). uid (Number) Sets the user identity of the process. uid (Number) Sets the user identity of the process. gid (Number) Sets the group identity of the process. gid (Number) Sets the group identity of the process. The fork method returns an object with a built-in communication channel in addition to having all the methods in a normal ChildProcess instance. Create two js files named support.js and master.js − File: support.js console.log("Child Process " + process.argv[2] + " executed." ); File: master.js const fs = require('fs'); const child_process = require('child_process'); for(var i=0; i<3; i++) { var worker_process = child_process.fork("support.js", [i]); worker_process.on('close', function (code) { console.log('child process exited with code ' + code); }); } Now run the master.js to see the result − $ node master.js Verify the Output. Server has started. Child Process 0 executed. Child Process 1 executed. Child Process 2 executed. child process exited with code 0 child process exited with code 0 child process exited with code 0 44 Lectures 7.5 hours Eduonix Learning Solutions 88 Lectures 17 hours Eduonix Learning Solutions 32 Lectures 1.5 hours Richard Wells 8 Lectures 33 mins Anant Rungta 9 Lectures 2.5 hours SHIVPRASAD KOIRALA 97 Lectures 6 hours Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2229, "s": 2018, "text": "Node.js runs in a single-thread mode, but it uses an event-driven paradigm to handle concurrency. It also facilitates creation of child processes to leverage parallel processing on multi-core CPU based systems." }, { "code": null, "e": 2381, "s": 2229, "text": "Child processes always have three streams child.stdin, child.stdout, and child.stderr which may be shared with the stdio streams of the parent process." }, { "code": null, "e": 2484, "s": 2381, "text": "Node provides child_process module which has the following three major ways to create a child process." }, { "code": null, "e": 2575, "s": 2484, "text": "exec − child_process.exec method runs a command in a shell/console and buffers the output." }, { "code": null, "e": 2666, "s": 2575, "text": "exec − child_process.exec method runs a command in a shell/console and buffers the output." }, { "code": null, "e": 2739, "s": 2666, "text": "spawn − child_process.spawn launches a new process with a given command." }, { "code": null, "e": 2812, "s": 2739, "text": "spawn − child_process.spawn launches a new process with a given command." }, { "code": null, "e": 2909, "s": 2812, "text": "fork − The child_process.fork method is a special case of the spawn() to create child processes." }, { "code": null, "e": 3006, "s": 2909, "text": "fork − The child_process.fork method is a special case of the spawn() to create child processes." }, { "code": null, "e": 3115, "s": 3006, "text": "child_process.exec method runs a command in a shell and buffers the output. It has the following signature −" }, { "code": null, "e": 3165, "s": 3115, "text": "child_process.exec(command[, options], callback)\n" }, { "code": null, "e": 3214, "s": 3165, "text": "Here is the description of the parameters used −" }, { "code": null, "e": 3282, "s": 3214, "text": "command (String) The command to run, with space-separated arguments" }, { "code": null, "e": 3350, "s": 3282, "text": "command (String) The command to run, with space-separated arguments" }, { "code": null, "e": 4015, "s": 3350, "text": "options (Object) may comprise one or more of the following options −\n\ncwd (String) Current working directory of the child process\nenv (Object) Environment key-value pairs\nencoding (String) (Default: 'utf8')\nshell (String) Shell to execute the command with (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should understand the -c switch on UNIX or /s /c on Windows. On Windows, command line parsing should be compatible with cmd.exe.)\ntimeout (Number) (Default: 0)\nmaxBuffer (Number) (Default: 200*1024)\nkillSignal (String) (Default: 'SIGTERM')\nuid (Number) Sets the user identity of the process. \ngid (Number) Sets the group identity of the process.\n\n" }, { "code": null, "e": 4084, "s": 4015, "text": "options (Object) may comprise one or more of the following options −" }, { "code": null, "e": 4144, "s": 4084, "text": "cwd (String) Current working directory of the child process" }, { "code": null, "e": 4204, "s": 4144, "text": "cwd (String) Current working directory of the child process" }, { "code": null, "e": 4245, "s": 4204, "text": "env (Object) Environment key-value pairs" }, { "code": null, "e": 4286, "s": 4245, "text": "env (Object) Environment key-value pairs" }, { "code": null, "e": 4322, "s": 4286, "text": "encoding (String) (Default: 'utf8')" }, { "code": null, "e": 4358, "s": 4322, "text": "encoding (String) (Default: 'utf8')" }, { "code": null, "e": 4598, "s": 4358, "text": "shell (String) Shell to execute the command with (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should understand the -c switch on UNIX or /s /c on Windows. On Windows, command line parsing should be compatible with cmd.exe.)" }, { "code": null, "e": 4838, "s": 4598, "text": "shell (String) Shell to execute the command with (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should understand the -c switch on UNIX or /s /c on Windows. On Windows, command line parsing should be compatible with cmd.exe.)" }, { "code": null, "e": 4868, "s": 4838, "text": "timeout (Number) (Default: 0)" }, { "code": null, "e": 4898, "s": 4868, "text": "timeout (Number) (Default: 0)" }, { "code": null, "e": 4937, "s": 4898, "text": "maxBuffer (Number) (Default: 200*1024)" }, { "code": null, "e": 4976, "s": 4937, "text": "maxBuffer (Number) (Default: 200*1024)" }, { "code": null, "e": 5017, "s": 4976, "text": "killSignal (String) (Default: 'SIGTERM')" }, { "code": null, "e": 5058, "s": 5017, "text": "killSignal (String) (Default: 'SIGTERM')" }, { "code": null, "e": 5111, "s": 5058, "text": "uid (Number) Sets the user identity of the process. " }, { "code": null, "e": 5164, "s": 5111, "text": "uid (Number) Sets the user identity of the process. " }, { "code": null, "e": 5217, "s": 5164, "text": "gid (Number) Sets the group identity of the process." }, { "code": null, "e": 5270, "s": 5217, "text": "gid (Number) Sets the group identity of the process." }, { "code": null, "e": 5401, "s": 5270, "text": "callback The function gets three arguments error, stdout, and stderr which are called with the output when the process terminates." }, { "code": null, "e": 5532, "s": 5401, "text": "callback The function gets three arguments error, stdout, and stderr which are called with the output when the process terminates." }, { "code": null, "e": 5667, "s": 5532, "text": "The exec() method returns a buffer with a max size and waits for the process to end and tries to return all the buffered data at once." }, { "code": null, "e": 5728, "s": 5667, "text": "Let us create two js files named support.js and master.js −\n" }, { "code": null, "e": 5745, "s": 5728, "text": "File: support.js" }, { "code": null, "e": 5811, "s": 5745, "text": "console.log(\"Child Process \" + process.argv[2] + \" executed.\" );\n" }, { "code": null, "e": 5827, "s": 5811, "text": "File: master.js" }, { "code": null, "e": 6413, "s": 5827, "text": "const fs = require('fs');\nconst child_process = require('child_process');\n\nfor(var i=0; i<3; i++) {\n var workerProcess = child_process.exec('node support.js '+i,function \n (error, stdout, stderr) {\n \n if (error) {\n console.log(error.stack);\n console.log('Error code: '+error.code);\n console.log('Signal received: '+error.signal);\n }\n console.log('stdout: ' + stdout);\n console.log('stderr: ' + stderr);\n });\n\n workerProcess.on('exit', function (code) {\n console.log('Child process exited with exit code '+code);\n });\n}" }, { "code": null, "e": 6455, "s": 6413, "text": "Now run the master.js to see the result −" }, { "code": null, "e": 6473, "s": 6455, "text": "$ node master.js\n" }, { "code": null, "e": 6512, "s": 6473, "text": "Verify the Output. Server has started." }, { "code": null, "e": 6747, "s": 6512, "text": "Child process exited with exit code 0\nstdout: Child Process 1 executed.\n\nstderr:\nChild process exited with exit code 0\nstdout: Child Process 0 executed.\n\nstderr:\nChild process exited with exit code 0\nstdout: Child Process 2 executed.\n" }, { "code": null, "e": 6852, "s": 6747, "text": "child_process.spawn method launches a new process with a given command. It has the following signature −" }, { "code": null, "e": 6901, "s": 6852, "text": "child_process.spawn(command[, args][, options])\n" }, { "code": null, "e": 6950, "s": 6901, "text": "Here is the description of the parameters used −" }, { "code": null, "e": 6986, "s": 6950, "text": "command (String) The command to run" }, { "code": null, "e": 7022, "s": 6986, "text": "command (String) The command to run" }, { "code": null, "e": 7060, "s": 7022, "text": "args (Array) List of string arguments" }, { "code": null, "e": 7098, "s": 7060, "text": "args (Array) List of string arguments" }, { "code": null, "e": 7567, "s": 7098, "text": "options (Object) may comprise one or more of the following options −\n\ncwd (String) Current working directory of the child process.\nenv (Object) Environment key-value pairs.\nstdio (Array) String Child's stdio configuration.\ncustomFds (Array) Deprecated File descriptors for the child to use for stdio.\ndetached (Boolean) The child will be a process group leader.\nuid (Number) Sets the user identity of the process.\ngid (Number) Sets the group identity of the process.\n\n" }, { "code": null, "e": 7636, "s": 7567, "text": "options (Object) may comprise one or more of the following options −" }, { "code": null, "e": 7697, "s": 7636, "text": "cwd (String) Current working directory of the child process." }, { "code": null, "e": 7758, "s": 7697, "text": "cwd (String) Current working directory of the child process." }, { "code": null, "e": 7800, "s": 7758, "text": "env (Object) Environment key-value pairs." }, { "code": null, "e": 7842, "s": 7800, "text": "env (Object) Environment key-value pairs." }, { "code": null, "e": 7892, "s": 7842, "text": "stdio (Array) String Child's stdio configuration." }, { "code": null, "e": 7942, "s": 7892, "text": "stdio (Array) String Child's stdio configuration." }, { "code": null, "e": 8020, "s": 7942, "text": "customFds (Array) Deprecated File descriptors for the child to use for stdio." }, { "code": null, "e": 8098, "s": 8020, "text": "customFds (Array) Deprecated File descriptors for the child to use for stdio." }, { "code": null, "e": 8159, "s": 8098, "text": "detached (Boolean) The child will be a process group leader." }, { "code": null, "e": 8220, "s": 8159, "text": "detached (Boolean) The child will be a process group leader." }, { "code": null, "e": 8272, "s": 8220, "text": "uid (Number) Sets the user identity of the process." }, { "code": null, "e": 8324, "s": 8272, "text": "uid (Number) Sets the user identity of the process." }, { "code": null, "e": 8377, "s": 8324, "text": "gid (Number) Sets the group identity of the process." }, { "code": null, "e": 8430, "s": 8377, "text": "gid (Number) Sets the group identity of the process." }, { "code": null, "e": 8633, "s": 8430, "text": "The spawn() method returns streams (stdout &stderr) and it should be used when the process returns a volume amount of data. spawn() starts receiving the response as soon as the process starts executing." }, { "code": null, "e": 8686, "s": 8633, "text": "Create two js files named support.js and master.js −" }, { "code": null, "e": 8703, "s": 8686, "text": "File: support.js" }, { "code": null, "e": 8769, "s": 8703, "text": "console.log(\"Child Process \" + process.argv[2] + \" executed.\" );\n" }, { "code": null, "e": 8785, "s": 8769, "text": "File: master.js" }, { "code": null, "e": 9275, "s": 8785, "text": "const fs = require('fs');\nconst child_process = require('child_process');\n \nfor(var i = 0; i<3; i++) {\n var workerProcess = child_process.spawn('node', ['support.js', i]);\n\n workerProcess.stdout.on('data', function (data) {\n console.log('stdout: ' + data);\n });\n\n workerProcess.stderr.on('data', function (data) {\n console.log('stderr: ' + data);\n });\n\n workerProcess.on('close', function (code) {\n console.log('child process exited with code ' + code);\n });\n}" }, { "code": null, "e": 9317, "s": 9275, "text": "Now run the master.js to see the result −" }, { "code": null, "e": 9335, "s": 9317, "text": "$ node master.js\n" }, { "code": null, "e": 9373, "s": 9335, "text": "Verify the Output. Server has started" }, { "code": null, "e": 9578, "s": 9373, "text": "stdout: Child Process 0 executed.\n\nchild process exited with code 0\nstdout: Child Process 1 executed.\n\nstdout: Child Process 2 executed.\n\nchild process exited with code 0\nchild process exited with code 0\n" }, { "code": null, "e": 9692, "s": 9578, "text": "child_process.fork method is a special case of spawn() to create Node processes. It has the following signature −" }, { "code": null, "e": 9743, "s": 9692, "text": "child_process.fork(modulePath[, args][, options])\n" }, { "code": null, "e": 9792, "s": 9743, "text": "Here is the description of the parameters used −" }, { "code": null, "e": 9844, "s": 9792, "text": "modulePath (String) The module to run in the child." }, { "code": null, "e": 9896, "s": 9844, "text": "modulePath (String) The module to run in the child." }, { "code": null, "e": 9934, "s": 9896, "text": "args (Array) List of string arguments" }, { "code": null, "e": 9972, "s": 9934, "text": "args (Array) List of string arguments" }, { "code": null, "e": 10650, "s": 9972, "text": "options (Object) may comprise one or more of the following options −\n\ncwd (String) Current working directory of the child process.\nenv (Object) Environment key-value pairs.\nexecPath (String) Executable used to create the child process.\nexecArgv (Array) List of string arguments passed to the executable (Default: process.execArgv).\nsilent (Boolean) If true, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent, see the \"pipe\" and \"inherit\" options for spawn()'s stdio for more details (default is false).\nuid (Number) Sets the user identity of the process. \ngid (Number) Sets the group identity of the process.\n\n" }, { "code": null, "e": 10719, "s": 10650, "text": "options (Object) may comprise one or more of the following options −" }, { "code": null, "e": 10780, "s": 10719, "text": "cwd (String) Current working directory of the child process." }, { "code": null, "e": 10841, "s": 10780, "text": "cwd (String) Current working directory of the child process." }, { "code": null, "e": 10883, "s": 10841, "text": "env (Object) Environment key-value pairs." }, { "code": null, "e": 10925, "s": 10883, "text": "env (Object) Environment key-value pairs." }, { "code": null, "e": 10988, "s": 10925, "text": "execPath (String) Executable used to create the child process." }, { "code": null, "e": 11051, "s": 10988, "text": "execPath (String) Executable used to create the child process." }, { "code": null, "e": 11147, "s": 11051, "text": "execArgv (Array) List of string arguments passed to the executable (Default: process.execArgv)." }, { "code": null, "e": 11243, "s": 11147, "text": "execArgv (Array) List of string arguments passed to the executable (Default: process.execArgv)." }, { "code": null, "e": 11481, "s": 11243, "text": "silent (Boolean) If true, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent, see the \"pipe\" and \"inherit\" options for spawn()'s stdio for more details (default is false)." }, { "code": null, "e": 11719, "s": 11481, "text": "silent (Boolean) If true, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent, see the \"pipe\" and \"inherit\" options for spawn()'s stdio for more details (default is false)." }, { "code": null, "e": 11772, "s": 11719, "text": "uid (Number) Sets the user identity of the process. " }, { "code": null, "e": 11825, "s": 11772, "text": "uid (Number) Sets the user identity of the process. " }, { "code": null, "e": 11878, "s": 11825, "text": "gid (Number) Sets the group identity of the process." }, { "code": null, "e": 11931, "s": 11878, "text": "gid (Number) Sets the group identity of the process." }, { "code": null, "e": 12076, "s": 11931, "text": "The fork method returns an object with a built-in communication channel in addition to having all the methods in a normal ChildProcess instance." }, { "code": null, "e": 12129, "s": 12076, "text": "Create two js files named support.js and master.js −" }, { "code": null, "e": 12146, "s": 12129, "text": "File: support.js" }, { "code": null, "e": 12212, "s": 12146, "text": "console.log(\"Child Process \" + process.argv[2] + \" executed.\" );\n" }, { "code": null, "e": 12228, "s": 12212, "text": "File: master.js" }, { "code": null, "e": 12512, "s": 12228, "text": "const fs = require('fs');\nconst child_process = require('child_process');\n \nfor(var i=0; i<3; i++) {\n var worker_process = child_process.fork(\"support.js\", [i]);\t\n\n worker_process.on('close', function (code) {\n console.log('child process exited with code ' + code);\n });\n}" }, { "code": null, "e": 12554, "s": 12512, "text": "Now run the master.js to see the result −" }, { "code": null, "e": 12572, "s": 12554, "text": "$ node master.js\n" }, { "code": null, "e": 12611, "s": 12572, "text": "Verify the Output. Server has started." }, { "code": null, "e": 12789, "s": 12611, "text": "Child Process 0 executed.\nChild Process 1 executed.\nChild Process 2 executed.\nchild process exited with code 0\nchild process exited with code 0\nchild process exited with code 0\n" }, { "code": null, "e": 12824, "s": 12789, "text": "\n 44 Lectures \n 7.5 hours \n" }, { "code": null, "e": 12852, "s": 12824, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 12886, "s": 12852, "text": "\n 88 Lectures \n 17 hours \n" }, { "code": null, "e": 12914, "s": 12886, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 12949, "s": 12914, "text": "\n 32 Lectures \n 1.5 hours \n" }, { "code": null, "e": 12964, "s": 12949, "text": " Richard Wells" }, { "code": null, "e": 12995, "s": 12964, "text": "\n 8 Lectures \n 33 mins\n" }, { "code": null, "e": 13009, "s": 12995, "text": " Anant Rungta" }, { "code": null, "e": 13043, "s": 13009, "text": "\n 9 Lectures \n 2.5 hours \n" }, { "code": null, "e": 13063, "s": 13043, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 13096, "s": 13063, "text": "\n 97 Lectures \n 6 hours \n" }, { "code": null, "e": 13116, "s": 13096, "text": " Skillbakerystudios" }, { "code": null, "e": 13123, "s": 13116, "text": " Print" }, { "code": null, "e": 13134, "s": 13123, "text": " Add Notes" } ]
Firebase - Read Data
In this chapter, we will show you how to read Firebase data. The following image shows the data we want to read. We can use the on() method to retrieve data. This method is taking the event type as "value" and then retrieves the snapshot of the data. When we add val() method to the snapshot, we will get the JavaScript representation of the data. Let us consider the following example. var ref = firebase.database().ref(); ref.on("value", function(snapshot) { console.log(snapshot.val()); }, function (error) { console.log("Error: " + error.code); }); If we run the following code, our console will show the data. In our next chapter, we will explain other event types that you can use for reading data. 60 Lectures 5 hours University Code 28 Lectures 2.5 hours Appeteria 85 Lectures 14.5 hours Appeteria 46 Lectures 2.5 hours Gautham Vijayan 13 Lectures 1.5 hours Nishant Kumar 85 Lectures 16.5 hours Rahul Agarwal Print Add Notes Bookmark this page
[ { "code": null, "e": 2279, "s": 2166, "text": "In this chapter, we will show you how to read Firebase data. The following image shows the data we want to read." }, { "code": null, "e": 2514, "s": 2279, "text": "We can use the on() method to retrieve data. This method is taking the event type as \"value\" and then retrieves the snapshot of the data. When we add val() method to the snapshot, we will get the JavaScript representation of the data." }, { "code": null, "e": 2553, "s": 2514, "text": "Let us consider the following example." }, { "code": null, "e": 2726, "s": 2553, "text": "var ref = firebase.database().ref();\n\nref.on(\"value\", function(snapshot) {\n console.log(snapshot.val());\n}, function (error) {\n console.log(\"Error: \" + error.code);\n});" }, { "code": null, "e": 2788, "s": 2726, "text": "If we run the following code, our console will show the data." }, { "code": null, "e": 2878, "s": 2788, "text": "In our next chapter, we will explain other event types that you can use for reading data." }, { "code": null, "e": 2911, "s": 2878, "text": "\n 60 Lectures \n 5 hours \n" }, { "code": null, "e": 2928, "s": 2911, "text": " University Code" }, { "code": null, "e": 2963, "s": 2928, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2974, "s": 2963, "text": " Appeteria" }, { "code": null, "e": 3010, "s": 2974, "text": "\n 85 Lectures \n 14.5 hours \n" }, { "code": null, "e": 3021, "s": 3010, "text": " Appeteria" }, { "code": null, "e": 3056, "s": 3021, "text": "\n 46 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3073, "s": 3056, "text": " Gautham Vijayan" }, { "code": null, "e": 3108, "s": 3073, "text": "\n 13 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3123, "s": 3108, "text": " Nishant Kumar" }, { "code": null, "e": 3159, "s": 3123, "text": "\n 85 Lectures \n 16.5 hours \n" }, { "code": null, "e": 3174, "s": 3159, "text": " Rahul Agarwal" }, { "code": null, "e": 3181, "s": 3174, "text": " Print" }, { "code": null, "e": 3192, "s": 3181, "text": " Add Notes" } ]
Learn Python Data Analytics By Example: NYC Parking Violations | by Nick Cox | Towards Data Science
While working towards my Master’s in Business Analytics, I found that learning by example was the best way for me to learn Python data analytics. Being given a dataset and a set of coding tasks is much more beneficial than reading a textbook or listening to a professor. I want to share this method of learning with others who will also benefit. All you need is a Python development environment (I recommend Jupyter Notebook) and a willingness to learn and have fun. Included in this article is a list of data analytics tasks, followed by a detailed walkthrough of how to complete the tasks. Please try to complete the tasks yourself before reading through the walkthrough — you will get more out of it that way. Do keep in mind that there are many many ways to solve coding problems, so your code likely will not match mine word for word. For this project we will use a dataset of 50,000 parking violations issued in New York City during the 2021 fiscal year. The dataset was created in January 2021 and contains data from April 1 to November 30, 2020 sourced from NYC Open Data. You will need to install the pandas and matplotlib libraries, if you do not already have them. Please perform the following tasks in Python using the violations.csv dataset available from the GitHub repo. Read the CSV file containing the NYC parking violation data. Change the ‘Issue Date’ column to a date format. Then print out the number of rows imported.Perform exploratory data analysis on the imported dataset to identify invalid data. Write code to remove the impacted rows. Then print out the number of rows remaining in the dataset.Display a simple plot that shows the number of parking violations issued for each vehicle year.List the top 5 violation codes for vehicles that are registered in states other than NY.Name the street where Hondas received the most parking violations.For vehicles that are from NY only, create a plot displaying the ratio of plate types that are not passenger, month by month.Determine whether the color of vehicles with passenger plates receiving the most violations is the same as the color of vehicles with commercial plates receiving the most violations.Display the number of registration states represented in the data and the average number of parking violations per registration state.Display the plate type that has the most parking violations for each violation code.Calculate the percentage of parking violations in each county and display in descending order. Read the CSV file containing the NYC parking violation data. Change the ‘Issue Date’ column to a date format. Then print out the number of rows imported. Perform exploratory data analysis on the imported dataset to identify invalid data. Write code to remove the impacted rows. Then print out the number of rows remaining in the dataset. Display a simple plot that shows the number of parking violations issued for each vehicle year. List the top 5 violation codes for vehicles that are registered in states other than NY. Name the street where Hondas received the most parking violations. For vehicles that are from NY only, create a plot displaying the ratio of plate types that are not passenger, month by month. Determine whether the color of vehicles with passenger plates receiving the most violations is the same as the color of vehicles with commercial plates receiving the most violations. Display the number of registration states represented in the data and the average number of parking violations per registration state. Display the plate type that has the most parking violations for each violation code. Calculate the percentage of parking violations in each county and display in descending order. Number of Rows: 50000 We start by making the contents of the pandas module available to our program. pandas is an easy to use open source data analysis and manipulation tool, built on top of the Python programming language. We will use it extensively throughout this project. import pandas as pd We import the contents of the violations.csv file by calling the read_csv() method and store it in a DataFrame, named df. A DataFrame is a two-dimensional data structure with labeled axes, consisting of data, rows and columns. Think of it like a table built in Microsoft Excel or Microsoft Access. df = pd.read_csv('violations.csv') We use the print() function to print the string ‘Number of Rows:’ followed by the number of rows in the DataFrame. The argument that we pass to the print() function is made up of two parts. The first is the string ‘Number of Rows: ‘ surrounded in single quotes, denoting it as a string. The second part of the argument is calculating the number of rows in df. We use the len() function to tell us the number of rows in df, then wrap it in a call to the str() method to convert the length into a string. Finally, the + concatenates (or joins) the two string parts together. All parts of the argument passed to the print() function must be of type string. print('Number of Rows: ' + str(len(df))) The following data is considered to be invalid: Registration State: values that are not a two letter state or province identifier. Plate Type: values that are not a three letter identifier (Registration Class Codes) Issue Date: dates not within the fiscal year (use 2020–11–30 as the end of the fiscal year) Violation Code: codes other than those between 1 and 99 (Violation Codes) Vehicle Make: blank values Violation Time: blank values Vehicle Year: vehicles with dates in the future (use 2020 as the current year) Number of Rows: 38937 We need to subset df to filter out records with invalid data. We are able to apply multiple parameters at once by wrapping each in parentheses and using the & character between them. We use != to represent not equal to, >= to represent greater than or equal to and <= to represent less than or equal to. For the Vehicle Make and Violation Time columns, we need to check for null values by calling the notnull() method. df = df[(df['Registration State'] != "99") & (df['Plate Type'] != "999") & (df['Issue Date'] >= '2020-04-01') & (df['Issue Date'] <= '2020-11-30') & (df['Violation Code'] != 0) & (df['Vehicle Make'].notnull()) & (df['Violation Time'].notnull()) & (df['Vehicle Year'] != 0) & (df['Vehicle Year'] <= 2020)] We use the print() function in exactly the same way as Step 1 above. print('Number of Rows: ' + str(len(df))) We make the contents of the matplotlib library available to our program. matplotlib is a comprehensive library for creating visualizations in Python. import matplotlib.pyplot as plt We need to create a dataset for the plot, containing vehicle year and the number of parking violations for each those years. To do this, we group the records in df by vehicle year and count the number of parking violations for each year. Each parking violation has a unique summons number. df_vehicle_year = df.groupby('Vehicle Year')['Summons Number'].count() We use the plot() function of matplotlib to create the plot. As an argument, we simply pass the new dataset that we created. Then we use the show() function to display the plot. plt.plot(df_vehicle_year)plt.show() There are a lot of elements in this single line of code to unpack, so we will take it one step at a time. Take your time to understand this line, as we will use this structure many more times in the steps to follow. In the first part of the statement, we filter df to those records with a registration state other than NY. df[df['Registration State'] != 'NY'] Next we group the resulting records by violation code and count the number of parking violations for each violation code. .groupby('Violation Code')['Summons Number'].count() We display the violation codes with the 5 highest counts by using the nlargest() method and passing it the argument 5. The first n rows with the largest values in the count column, in descending order, are displayed. .nlargest(5) Finally, we use the reset_index() method to reset the DataFrame index to the original one. We use it here to present the results in a more elegant manner. We pass the name argument of ‘Count’ to name the column containing the count values. .reset_index(name='Count') This line of code closely follows the structure of what we used in Step 4 above. In this instance we filter df to only those records with a vehicle make of Honda, group the resulting records by street name, count the number of parking violations for each street and display only the street with the most parking violations. df[df['Vehicle Make'] == 'HONDA'].groupby('Street Name')['Summons Number'].count().nlargest(1).reset_index(name='Count') We subset df by selecting only those records with a registration state of NY and store it as df_ny. df_ny = df[df['Registration State'] == 'NY'] To calculate the requested ratios, we need to create a dataset to represent the numerator (number of parking violations for all non-passenger vehicles by vehicle year) and another to represent the denominator (number of parking violations for all vehicles by vehicle year). For the numerator we filter df_ny to only those records with a plate type not equal to passenger, group the resulting records by vehicle year and count the number of parking violations for each year. We store this as df_ny_notpas. df_ny_notpas = df_ny[df_ny['Plate Type'] != 'PAS'].groupby('Vehicle Year')['Summons Number'].count() For the denominator we don’t need to filter df_ny as we need all records. Instead we just group the records by vehicle year and count the number of parking violations for each year. We store this as df_ny_all. df_ny_all = df_ny.groupby('Vehicle Year')['Summons Number'].count() To calculate the ratios for each year, we simply divide the numerator by the denominator. This is part of the magic of pandas, where it applies the division function to each of the count pairs in the DataFrames, year by year. When a vehicle year appears in only one of the DataFrames, the result is NaN. ratio = df_ny_notpas / df_ny_all We are unable to plot NaN values, so we replace them with 0 using the fillna() method on the ratio Dataframe. The inplace=True parameter updates the values directly in ratio. ratio.fillna(0, inplace = True) We use the plot() function of matplotlib to create the plot. As an argument, we simply pass the new dataset that we created. Then we use the show() function to display the plot. plt.plot(ratio)plt.show() We filter df to only those records with a plate type of passenger, group the resulting records by vehicle color, count the number of parking violations for each color and display the color with the most parking violations using nlargest(). df[df['Plate Type'] == 'PAS'].groupby('Vehicle Color')['Summons Number'].count().nlargest(1).reset_index(name='Count') We filter df to only those records with a plate type of commercial, group the resulting records by vehicle color, count the number of parking violations for each color and display the color with the most parking violations using nlargest(). df[df['Plate Type'] == 'COM'].groupby('Vehicle Color')['Summons Number'].count().nlargest(1).reset_index(name='Count') Number of Registration States: 45Average Number of Parking Violations per Registration State: 865.2666666666667 We print the string ‘Number of Registration States’ concatenated with the count of registration states in df. To determine the number of registration states we call the nunique() method on the registration state column in df, which returns the count of distinct observations, i.e., the number of unique states listed in the column. As we did before, we use str() to convert the numeric value into a string. print('Number of Registration States: ' + str(df['Registration State'].nunique())) We print the string ‘Average Number of Parking Violations per Registration State’ concatenated with the average number of parking violations. To calculate the latter, we group the rows in df by registration state, count the number of parking violations for each state and then average the counts by calling the mean() method. print('Average Number of Parking Violations per Registration State: ' + str(df.groupby('Registration State')['Summons Number'].count().mean())) In this step, we are using more advanced functionality. We will break this code down into snippets to explain. We start by grouping the records in df by violation code. df.groupby('Violation Code')['Plate Type'] Next, we want to determine which plate type gets the most parking violations for each of the violation codes. To do this we need to apply a function along an axis of the grouped data. Because we do not specify the axis, it defaults to 0, which is the index. The lambda function calls the value_counts() method on each group (violation code) and counts the number of instances of each plate type per group, in descending order. The call to the head() method then gives us the top plate type for each violation code group. .apply(lambda x: x.value_counts().head(1)) We use the reset_index() method to reset the DataFrame index to the original one. We use it here to present the results in a more elegant manner. We pass the name argument of ‘Count’ to name the column containing the count values. .reset_index(name='Count') Finally, we call the rename() method to rename the level_1 column as Plate Type, to make the output more readable. .rename(columns={'level_1': 'Plate Type'}) We group the rows in df by violation county, count the number of parking violations for each violation county and then store it as df_county. We call the reset_index() method to reset the index and to rename the result column as Percentage. df_county = df.groupby('Violation County')['Summons Number'].count().reset_index(name='Percentage') We replace the previously calculated values in the Percentage column by dividing them by the total sum of violations to calculate a percentage for each. df_county['Percentage'] = df_county['Percentage'] / df_county['Percentage'].sum() * 100 Finally, we call the sort_values method on df_county to sort the percentages in descending order. df_county.sort_values(by='Percentage', ascending=False).reset_index(drop=True) I hope you have found this project a useful way to learn Python data analytics. Please share your feedback in the comments section.
[ { "code": null, "e": 318, "s": 47, "text": "While working towards my Master’s in Business Analytics, I found that learning by example was the best way for me to learn Python data analytics. Being given a dataset and a set of coding tasks is much more beneficial than reading a textbook or listening to a professor." }, { "code": null, "e": 514, "s": 318, "text": "I want to share this method of learning with others who will also benefit. All you need is a Python development environment (I recommend Jupyter Notebook) and a willingness to learn and have fun." }, { "code": null, "e": 887, "s": 514, "text": "Included in this article is a list of data analytics tasks, followed by a detailed walkthrough of how to complete the tasks. Please try to complete the tasks yourself before reading through the walkthrough — you will get more out of it that way. Do keep in mind that there are many many ways to solve coding problems, so your code likely will not match mine word for word." }, { "code": null, "e": 1128, "s": 887, "text": "For this project we will use a dataset of 50,000 parking violations issued in New York City during the 2021 fiscal year. The dataset was created in January 2021 and contains data from April 1 to November 30, 2020 sourced from NYC Open Data." }, { "code": null, "e": 1223, "s": 1128, "text": "You will need to install the pandas and matplotlib libraries, if you do not already have them." }, { "code": null, "e": 1333, "s": 1223, "text": "Please perform the following tasks in Python using the violations.csv dataset available from the GitHub repo." }, { "code": null, "e": 2538, "s": 1333, "text": "Read the CSV file containing the NYC parking violation data. Change the ‘Issue Date’ column to a date format. Then print out the number of rows imported.Perform exploratory data analysis on the imported dataset to identify invalid data. Write code to remove the impacted rows. Then print out the number of rows remaining in the dataset.Display a simple plot that shows the number of parking violations issued for each vehicle year.List the top 5 violation codes for vehicles that are registered in states other than NY.Name the street where Hondas received the most parking violations.For vehicles that are from NY only, create a plot displaying the ratio of plate types that are not passenger, month by month.Determine whether the color of vehicles with passenger plates receiving the most violations is the same as the color of vehicles with commercial plates receiving the most violations.Display the number of registration states represented in the data and the average number of parking violations per registration state.Display the plate type that has the most parking violations for each violation code.Calculate the percentage of parking violations in each county and display in descending order." }, { "code": null, "e": 2692, "s": 2538, "text": "Read the CSV file containing the NYC parking violation data. Change the ‘Issue Date’ column to a date format. Then print out the number of rows imported." }, { "code": null, "e": 2876, "s": 2692, "text": "Perform exploratory data analysis on the imported dataset to identify invalid data. Write code to remove the impacted rows. Then print out the number of rows remaining in the dataset." }, { "code": null, "e": 2972, "s": 2876, "text": "Display a simple plot that shows the number of parking violations issued for each vehicle year." }, { "code": null, "e": 3061, "s": 2972, "text": "List the top 5 violation codes for vehicles that are registered in states other than NY." }, { "code": null, "e": 3128, "s": 3061, "text": "Name the street where Hondas received the most parking violations." }, { "code": null, "e": 3254, "s": 3128, "text": "For vehicles that are from NY only, create a plot displaying the ratio of plate types that are not passenger, month by month." }, { "code": null, "e": 3437, "s": 3254, "text": "Determine whether the color of vehicles with passenger plates receiving the most violations is the same as the color of vehicles with commercial plates receiving the most violations." }, { "code": null, "e": 3572, "s": 3437, "text": "Display the number of registration states represented in the data and the average number of parking violations per registration state." }, { "code": null, "e": 3657, "s": 3572, "text": "Display the plate type that has the most parking violations for each violation code." }, { "code": null, "e": 3752, "s": 3657, "text": "Calculate the percentage of parking violations in each county and display in descending order." }, { "code": null, "e": 3774, "s": 3752, "text": "Number of Rows: 50000" }, { "code": null, "e": 4028, "s": 3774, "text": "We start by making the contents of the pandas module available to our program. pandas is an easy to use open source data analysis and manipulation tool, built on top of the Python programming language. We will use it extensively throughout this project." }, { "code": null, "e": 4048, "s": 4028, "text": "import pandas as pd" }, { "code": null, "e": 4346, "s": 4048, "text": "We import the contents of the violations.csv file by calling the read_csv() method and store it in a DataFrame, named df. A DataFrame is a two-dimensional data structure with labeled axes, consisting of data, rows and columns. Think of it like a table built in Microsoft Excel or Microsoft Access." }, { "code": null, "e": 4381, "s": 4346, "text": "df = pd.read_csv('violations.csv')" }, { "code": null, "e": 4668, "s": 4381, "text": "We use the print() function to print the string ‘Number of Rows:’ followed by the number of rows in the DataFrame. The argument that we pass to the print() function is made up of two parts. The first is the string ‘Number of Rows: ‘ surrounded in single quotes, denoting it as a string." }, { "code": null, "e": 5035, "s": 4668, "text": "The second part of the argument is calculating the number of rows in df. We use the len() function to tell us the number of rows in df, then wrap it in a call to the str() method to convert the length into a string. Finally, the + concatenates (or joins) the two string parts together. All parts of the argument passed to the print() function must be of type string." }, { "code": null, "e": 5076, "s": 5035, "text": "print('Number of Rows: ' + str(len(df)))" }, { "code": null, "e": 5124, "s": 5076, "text": "The following data is considered to be invalid:" }, { "code": null, "e": 5207, "s": 5124, "text": "Registration State: values that are not a two letter state or province identifier." }, { "code": null, "e": 5292, "s": 5207, "text": "Plate Type: values that are not a three letter identifier (Registration Class Codes)" }, { "code": null, "e": 5384, "s": 5292, "text": "Issue Date: dates not within the fiscal year (use 2020–11–30 as the end of the fiscal year)" }, { "code": null, "e": 5458, "s": 5384, "text": "Violation Code: codes other than those between 1 and 99 (Violation Codes)" }, { "code": null, "e": 5485, "s": 5458, "text": "Vehicle Make: blank values" }, { "code": null, "e": 5514, "s": 5485, "text": "Violation Time: blank values" }, { "code": null, "e": 5593, "s": 5514, "text": "Vehicle Year: vehicles with dates in the future (use 2020 as the current year)" }, { "code": null, "e": 5615, "s": 5593, "text": "Number of Rows: 38937" }, { "code": null, "e": 6034, "s": 5615, "text": "We need to subset df to filter out records with invalid data. We are able to apply multiple parameters at once by wrapping each in parentheses and using the & character between them. We use != to represent not equal to, >= to represent greater than or equal to and <= to represent less than or equal to. For the Vehicle Make and Violation Time columns, we need to check for null values by calling the notnull() method." }, { "code": null, "e": 6371, "s": 6034, "text": "df = df[(df['Registration State'] != \"99\") & (df['Plate Type'] != \"999\") & (df['Issue Date'] >= '2020-04-01') & (df['Issue Date'] <= '2020-11-30') & (df['Violation Code'] != 0) & (df['Vehicle Make'].notnull()) & (df['Violation Time'].notnull()) & (df['Vehicle Year'] != 0) & (df['Vehicle Year'] <= 2020)]" }, { "code": null, "e": 6440, "s": 6371, "text": "We use the print() function in exactly the same way as Step 1 above." }, { "code": null, "e": 6481, "s": 6440, "text": "print('Number of Rows: ' + str(len(df)))" }, { "code": null, "e": 6631, "s": 6481, "text": "We make the contents of the matplotlib library available to our program. matplotlib is a comprehensive library for creating visualizations in Python." }, { "code": null, "e": 6663, "s": 6631, "text": "import matplotlib.pyplot as plt" }, { "code": null, "e": 6953, "s": 6663, "text": "We need to create a dataset for the plot, containing vehicle year and the number of parking violations for each those years. To do this, we group the records in df by vehicle year and count the number of parking violations for each year. Each parking violation has a unique summons number." }, { "code": null, "e": 7024, "s": 6953, "text": "df_vehicle_year = df.groupby('Vehicle Year')['Summons Number'].count()" }, { "code": null, "e": 7202, "s": 7024, "text": "We use the plot() function of matplotlib to create the plot. As an argument, we simply pass the new dataset that we created. Then we use the show() function to display the plot." }, { "code": null, "e": 7238, "s": 7202, "text": "plt.plot(df_vehicle_year)plt.show()" }, { "code": null, "e": 7454, "s": 7238, "text": "There are a lot of elements in this single line of code to unpack, so we will take it one step at a time. Take your time to understand this line, as we will use this structure many more times in the steps to follow." }, { "code": null, "e": 7561, "s": 7454, "text": "In the first part of the statement, we filter df to those records with a registration state other than NY." }, { "code": null, "e": 7598, "s": 7561, "text": "df[df['Registration State'] != 'NY']" }, { "code": null, "e": 7720, "s": 7598, "text": "Next we group the resulting records by violation code and count the number of parking violations for each violation code." }, { "code": null, "e": 7773, "s": 7720, "text": ".groupby('Violation Code')['Summons Number'].count()" }, { "code": null, "e": 7990, "s": 7773, "text": "We display the violation codes with the 5 highest counts by using the nlargest() method and passing it the argument 5. The first n rows with the largest values in the count column, in descending order, are displayed." }, { "code": null, "e": 8003, "s": 7990, "text": ".nlargest(5)" }, { "code": null, "e": 8243, "s": 8003, "text": "Finally, we use the reset_index() method to reset the DataFrame index to the original one. We use it here to present the results in a more elegant manner. We pass the name argument of ‘Count’ to name the column containing the count values." }, { "code": null, "e": 8270, "s": 8243, "text": ".reset_index(name='Count')" }, { "code": null, "e": 8594, "s": 8270, "text": "This line of code closely follows the structure of what we used in Step 4 above. In this instance we filter df to only those records with a vehicle make of Honda, group the resulting records by street name, count the number of parking violations for each street and display only the street with the most parking violations." }, { "code": null, "e": 8715, "s": 8594, "text": "df[df['Vehicle Make'] == 'HONDA'].groupby('Street Name')['Summons Number'].count().nlargest(1).reset_index(name='Count')" }, { "code": null, "e": 8815, "s": 8715, "text": "We subset df by selecting only those records with a registration state of NY and store it as df_ny." }, { "code": null, "e": 8860, "s": 8815, "text": "df_ny = df[df['Registration State'] == 'NY']" }, { "code": null, "e": 9134, "s": 8860, "text": "To calculate the requested ratios, we need to create a dataset to represent the numerator (number of parking violations for all non-passenger vehicles by vehicle year) and another to represent the denominator (number of parking violations for all vehicles by vehicle year)." }, { "code": null, "e": 9365, "s": 9134, "text": "For the numerator we filter df_ny to only those records with a plate type not equal to passenger, group the resulting records by vehicle year and count the number of parking violations for each year. We store this as df_ny_notpas." }, { "code": null, "e": 9466, "s": 9365, "text": "df_ny_notpas = df_ny[df_ny['Plate Type'] != 'PAS'].groupby('Vehicle Year')['Summons Number'].count()" }, { "code": null, "e": 9676, "s": 9466, "text": "For the denominator we don’t need to filter df_ny as we need all records. Instead we just group the records by vehicle year and count the number of parking violations for each year. We store this as df_ny_all." }, { "code": null, "e": 9744, "s": 9676, "text": "df_ny_all = df_ny.groupby('Vehicle Year')['Summons Number'].count()" }, { "code": null, "e": 10048, "s": 9744, "text": "To calculate the ratios for each year, we simply divide the numerator by the denominator. This is part of the magic of pandas, where it applies the division function to each of the count pairs in the DataFrames, year by year. When a vehicle year appears in only one of the DataFrames, the result is NaN." }, { "code": null, "e": 10081, "s": 10048, "text": "ratio = df_ny_notpas / df_ny_all" }, { "code": null, "e": 10256, "s": 10081, "text": "We are unable to plot NaN values, so we replace them with 0 using the fillna() method on the ratio Dataframe. The inplace=True parameter updates the values directly in ratio." }, { "code": null, "e": 10288, "s": 10256, "text": "ratio.fillna(0, inplace = True)" }, { "code": null, "e": 10466, "s": 10288, "text": "We use the plot() function of matplotlib to create the plot. As an argument, we simply pass the new dataset that we created. Then we use the show() function to display the plot." }, { "code": null, "e": 10492, "s": 10466, "text": "plt.plot(ratio)plt.show()" }, { "code": null, "e": 10732, "s": 10492, "text": "We filter df to only those records with a plate type of passenger, group the resulting records by vehicle color, count the number of parking violations for each color and display the color with the most parking violations using nlargest()." }, { "code": null, "e": 10851, "s": 10732, "text": "df[df['Plate Type'] == 'PAS'].groupby('Vehicle Color')['Summons Number'].count().nlargest(1).reset_index(name='Count')" }, { "code": null, "e": 11092, "s": 10851, "text": "We filter df to only those records with a plate type of commercial, group the resulting records by vehicle color, count the number of parking violations for each color and display the color with the most parking violations using nlargest()." }, { "code": null, "e": 11211, "s": 11092, "text": "df[df['Plate Type'] == 'COM'].groupby('Vehicle Color')['Summons Number'].count().nlargest(1).reset_index(name='Count')" }, { "code": null, "e": 11323, "s": 11211, "text": "Number of Registration States: 45Average Number of Parking Violations per Registration State: 865.2666666666667" }, { "code": null, "e": 11730, "s": 11323, "text": "We print the string ‘Number of Registration States’ concatenated with the count of registration states in df. To determine the number of registration states we call the nunique() method on the registration state column in df, which returns the count of distinct observations, i.e., the number of unique states listed in the column. As we did before, we use str() to convert the numeric value into a string." }, { "code": null, "e": 11813, "s": 11730, "text": "print('Number of Registration States: ' + str(df['Registration State'].nunique()))" }, { "code": null, "e": 12139, "s": 11813, "text": "We print the string ‘Average Number of Parking Violations per Registration State’ concatenated with the average number of parking violations. To calculate the latter, we group the rows in df by registration state, count the number of parking violations for each state and then average the counts by calling the mean() method." }, { "code": null, "e": 12284, "s": 12139, "text": "print('Average Number of Parking Violations per Registration State: ' + str(df.groupby('Registration State')['Summons Number'].count().mean()))" }, { "code": null, "e": 12395, "s": 12284, "text": "In this step, we are using more advanced functionality. We will break this code down into snippets to explain." }, { "code": null, "e": 12453, "s": 12395, "text": "We start by grouping the records in df by violation code." }, { "code": null, "e": 12496, "s": 12453, "text": "df.groupby('Violation Code')['Plate Type']" }, { "code": null, "e": 12754, "s": 12496, "text": "Next, we want to determine which plate type gets the most parking violations for each of the violation codes. To do this we need to apply a function along an axis of the grouped data. Because we do not specify the axis, it defaults to 0, which is the index." }, { "code": null, "e": 13017, "s": 12754, "text": "The lambda function calls the value_counts() method on each group (violation code) and counts the number of instances of each plate type per group, in descending order. The call to the head() method then gives us the top plate type for each violation code group." }, { "code": null, "e": 13060, "s": 13017, "text": ".apply(lambda x: x.value_counts().head(1))" }, { "code": null, "e": 13291, "s": 13060, "text": "We use the reset_index() method to reset the DataFrame index to the original one. We use it here to present the results in a more elegant manner. We pass the name argument of ‘Count’ to name the column containing the count values." }, { "code": null, "e": 13318, "s": 13291, "text": ".reset_index(name='Count')" }, { "code": null, "e": 13433, "s": 13318, "text": "Finally, we call the rename() method to rename the level_1 column as Plate Type, to make the output more readable." }, { "code": null, "e": 13476, "s": 13433, "text": ".rename(columns={'level_1': 'Plate Type'})" }, { "code": null, "e": 13717, "s": 13476, "text": "We group the rows in df by violation county, count the number of parking violations for each violation county and then store it as df_county. We call the reset_index() method to reset the index and to rename the result column as Percentage." }, { "code": null, "e": 13817, "s": 13717, "text": "df_county = df.groupby('Violation County')['Summons Number'].count().reset_index(name='Percentage')" }, { "code": null, "e": 13970, "s": 13817, "text": "We replace the previously calculated values in the Percentage column by dividing them by the total sum of violations to calculate a percentage for each." }, { "code": null, "e": 14058, "s": 13970, "text": "df_county['Percentage'] = df_county['Percentage'] / df_county['Percentage'].sum() * 100" }, { "code": null, "e": 14156, "s": 14058, "text": "Finally, we call the sort_values method on df_county to sort the percentages in descending order." }, { "code": null, "e": 14235, "s": 14156, "text": "df_county.sort_values(by='Percentage', ascending=False).reset_index(drop=True)" } ]
Tryit Editor v3.7
Tryit: link to stylesheet using relative url
[]
Cypress - Test Runner
Cypress Test Runner helps to trigger the test execution. As we complete Cypress installation, there comes a suggestion from the tool on the terminal, as mentioned below − You can open Cypress by running − node_modules/.bin/cypress open To open the Test Runner, we have to run the below mentioned command − node_modules/.bin/cypress open The Test Runner window opens up after some time with the message that a sample project folder structure has been provided by Cypress under examples folder. Click on the OK, got it! button. The screen that will appear on your computer would be as follows − Then the Test Runner is launched, with the more than one spec files available under the examples folder, as stated below − To run a specific file, for example, test2.spec.js, we have to click it. Also, the browser and the option to Stop the execution are available. The execution shall begin with the following screen showing the test steps, name of test case, test suite, URL, test duration, dimension of browser, and so on. 73 Lectures 12 hours Rahul Shetty Print Add Notes Bookmark this page
[ { "code": null, "e": 2668, "s": 2497, "text": "Cypress Test Runner helps to trigger the test execution. As we complete Cypress installation, there comes a suggestion from the tool on the terminal, as mentioned below −" }, { "code": null, "e": 2734, "s": 2668, "text": "You can open Cypress by running − node_modules/.bin/cypress open\n" }, { "code": null, "e": 2804, "s": 2734, "text": "To open the Test Runner, we have to run the below mentioned command −" }, { "code": null, "e": 2836, "s": 2804, "text": "node_modules/.bin/cypress open\n" }, { "code": null, "e": 2992, "s": 2836, "text": "The Test Runner window opens up after some time with the message that a sample project folder structure has been provided by Cypress under examples folder." }, { "code": null, "e": 3092, "s": 2992, "text": "Click on the OK, got it! button. The screen that will appear on your computer would be as follows −" }, { "code": null, "e": 3215, "s": 3092, "text": "Then the Test Runner is launched, with the more than one spec files available under the examples folder, as stated below −" }, { "code": null, "e": 3358, "s": 3215, "text": "To run a specific file, for example, test2.spec.js, we have to click it. Also, the browser and the option to Stop the execution are available." }, { "code": null, "e": 3518, "s": 3358, "text": "The execution shall begin with the following screen showing the test steps, name of test\ncase, test suite, URL, test duration, dimension of browser, and so on." }, { "code": null, "e": 3552, "s": 3518, "text": "\n 73 Lectures \n 12 hours \n" }, { "code": null, "e": 3566, "s": 3552, "text": " Rahul Shetty" }, { "code": null, "e": 3573, "s": 3566, "text": " Print" }, { "code": null, "e": 3584, "s": 3573, "text": " Add Notes" } ]
What is Binary Serialization and Deserialization in C# and how to achieve Binary Serialization in C#?
Converting an Object to a Binary format which is not in a human readable format is called Binary Serialization. Converting back the binary format to human readable format is called deserialization? To achieve binary serialization in C# we have to make use of library System.Runtime.Serialization.Formatters.Binary Assembly Create an object of BinaryFormatter class and make use of serialize method inside the class Serialize an Object to Binary [Serializable] public class Demo { public string ApplicationName { get; set; } = "Binary Serialize"; public int ApplicationId { get; set; } = 1001; } class Program { static void Main() { Demo sample = new Demo(); FileStream fileStream = new FileStream(@"C:\Temp\Questions.dat", FileMode.Create); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(fileStream, sample); Console.ReadKey(); } } ÿÿÿÿ AConsoleApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null ConsoleApp.Demo<ApplicationName>k__BackingField-<ApplicationId>k__BackingField Binary Serializeé Converting back from Binary to Object [Serializable] public class Demo { public string ApplicationName { get; set; } public int ApplicationId { get; set; } } class Program { static void Main() { FileStream fileStream = new FileStream(@"C:\Temp\Questions.dat ", FileMode.Open); BinaryFormatter formatter = new BinaryFormatter(); Demo deserializedSampledemo = (Demo)formatter.Deserialize(fileStream); Console.WriteLine($"ApplicationName { deserializedSampledemo.ApplicationName} --- ApplicationId { deserializedSampledemo.ApplicationId}"); Console.ReadKey(); } } ApplicationName Binary Serialize --- ApplicationId 1001
[ { "code": null, "e": 1174, "s": 1062, "text": "Converting an Object to a Binary format which is not in a human readable format is called Binary Serialization." }, { "code": null, "e": 1260, "s": 1174, "text": "Converting back the binary format to human readable format is called deserialization?" }, { "code": null, "e": 1385, "s": 1260, "text": "To achieve binary serialization in C# we have to make use of library System.Runtime.Serialization.Formatters.Binary Assembly" }, { "code": null, "e": 1477, "s": 1385, "text": "Create an object of BinaryFormatter class and make use of serialize method inside the class" }, { "code": null, "e": 1963, "s": 1477, "text": "Serialize an Object to Binary\n[Serializable]\npublic class Demo {\n public string ApplicationName { get; set; } = \"Binary Serialize\";\n public int ApplicationId { get; set; } = 1001;\n}\nclass Program {\n static void Main() {\n Demo sample = new Demo();\n FileStream fileStream = new FileStream(@\"C:\\Temp\\Questions.dat\", FileMode.Create);\n BinaryFormatter formatter = new BinaryFormatter();\n formatter.Serialize(fileStream, sample);\n Console.ReadKey();\n }\n}" }, { "code": null, "e": 1972, "s": 1963, "text": "ÿÿÿÿ" }, { "code": null, "e": 2137, "s": 1972, "text": "AConsoleApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null ConsoleApp.Demo<ApplicationName>k__BackingField-<ApplicationId>k__BackingField Binary Serializeé" }, { "code": null, "e": 2749, "s": 2137, "text": "Converting back from Binary to Object\n[Serializable]\npublic class Demo {\n public string ApplicationName { get; set; }\n public int ApplicationId { get; set; }\n}\nclass Program {\n static void Main() {\n FileStream fileStream = new FileStream(@\"C:\\Temp\\Questions.dat \", FileMode.Open);\n BinaryFormatter formatter = new BinaryFormatter();\n Demo deserializedSampledemo = (Demo)formatter.Deserialize(fileStream);\n Console.WriteLine($\"ApplicationName { deserializedSampledemo.ApplicationName} --- ApplicationId { deserializedSampledemo.ApplicationId}\");\n Console.ReadKey();\n }\n}" }, { "code": null, "e": 2805, "s": 2749, "text": "ApplicationName Binary Serialize --- ApplicationId 1001" } ]
How to resolve the error that occurs while using a reserved word as a table or column name in MySQL?
This error occurs when you try to use a reserved word as a table or column name. It can occur due to − Case 1: Whenever you use reserved word as a table name − mysql> create table insert −> ( −> Id int −> ); The error is as follows − ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'insert ( Id int )' at line 1 The above error occurred because the word ‘insert’ is a keyword in MySQL. Case 2 − Whenever you use reserved word as a column name in MySQL. mysql> create table Customers −> ( −> Add int −> ); The error is as follows − ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Add int )' at line 3 The above error occurred because the column name ‘Add’ is a reserved word in MySQL. To avoid the above error, you need to know about all the reserved words of MySQL Some of the MySQL reserved words are as follows − Insert Add Is Key Like etc. The complete list of MySQL reserved keywords are as follows. This is the official website of MySQL − https://dev.mysql.com/doc/refman/5.7/en/keywords.html Use a backtick with the reserved keyword to solve this issue. Note - You cannot use a reserved keyword for table or column name. However, including them with backtick would be considered correct. For Example − create table `insert` Demo of backtick with table as well as column name. mysql> create table `Insert` −> ( −> `Add` int −> ); Query OK, 0 rows affected (0.59 sec) With the help of backtick, you will not get any error.
[ { "code": null, "e": 1165, "s": 1062, "text": "This error occurs when you try to use a reserved word as a table or column name. It can occur due to −" }, { "code": null, "e": 1222, "s": 1165, "text": "Case 1: Whenever you use reserved word as a table name −" }, { "code": null, "e": 1270, "s": 1222, "text": "mysql> create table insert\n−> (\n−> Id int\n−> );" }, { "code": null, "e": 1296, "s": 1270, "text": "The error is as follows −" }, { "code": null, "e": 1480, "s": 1296, "text": "ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'insert\n(\nId int\n)' at line 1" }, { "code": null, "e": 1554, "s": 1480, "text": "The above error occurred because the word ‘insert’ is a keyword in MySQL." }, { "code": null, "e": 1621, "s": 1554, "text": "Case 2 − Whenever you use reserved word as a column name in MySQL." }, { "code": null, "e": 1682, "s": 1621, "text": "mysql> create table Customers\n −> (\n −> Add int\n −> );" }, { "code": null, "e": 1708, "s": 1682, "text": "The error is as follows −" }, { "code": null, "e": 1884, "s": 1708, "text": "ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Add int\n)' at line 3" }, { "code": null, "e": 1968, "s": 1884, "text": "The above error occurred because the column name ‘Add’ is a reserved word in MySQL." }, { "code": null, "e": 2049, "s": 1968, "text": "To avoid the above error, you need to know about all the reserved words of MySQL" }, { "code": null, "e": 2099, "s": 2049, "text": "Some of the MySQL reserved words are as follows −" }, { "code": null, "e": 2127, "s": 2099, "text": "Insert\nAdd\nIs\nKey\nLike etc." }, { "code": null, "e": 2282, "s": 2127, "text": "The complete list of MySQL reserved keywords are as follows. This is the official website of MySQL − https://dev.mysql.com/doc/refman/5.7/en/keywords.html" }, { "code": null, "e": 2344, "s": 2282, "text": "Use a backtick with the reserved keyword to solve this issue." }, { "code": null, "e": 2478, "s": 2344, "text": "Note - You cannot use a reserved keyword for table or column name. However, including them with backtick would be considered correct." }, { "code": null, "e": 2492, "s": 2478, "text": "For Example −" }, { "code": null, "e": 2514, "s": 2492, "text": "create table `insert`" }, { "code": null, "e": 2566, "s": 2514, "text": "Demo of backtick with table as well as column name." }, { "code": null, "e": 2665, "s": 2566, "text": "mysql> create table `Insert`\n −> (\n −> `Add` int\n −> );\nQuery OK, 0 rows affected (0.59 sec)" }, { "code": null, "e": 2720, "s": 2665, "text": "With the help of backtick, you will not get any error." } ]
HTML novalidate Attribute
The HTML novalidate attribute define that while submitting the form the form data should not be validated in an HTML document. Following is the syntax − <form novalidate></form> Let us see an example of HTML novalidate Attribute − Live Demo <!DOCTYPE html> <html> <style> body { color: #000; height: 100vh; background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) no-repeat; text-align: center; } input[type='text'] { width: 300px; padding: 8px 16px; border: 2px solid #fff; background: transparent; border-radius: 20px; display: block; margin: 1rem auto; outline: none; } .btn { background: #db133a; border: none; height: 2rem; border-radius: 20px; width: 330px; display: block; color: #fff; outline: none; cursor: pointer; margin: 1rem auto; } ::placeholder { color: #000; } </style> <body> <h1>HTML novalidate attribute Demo</h1> <form> <input type="text" placeholder="Enter your name" required> <input type="submit" value="Submit" class="btn" onclick='check()'> </form> <button type='button' class="btn" onclick="set()">Set No Validation</button> <div class="show"></div> <script> function set() { document.querySelector('form').setAttribute('novalidate', 'true'); } </script> </body> </html> Try to click on “Submit” button without entering any name in the text field, it will produce a warning message − Now click on “Set No Validation” button to set novalidate attribute on the form element and now try to submit the form without entering any name in the text field, this time it will easily get submitted without showing any warning message −
[ { "code": null, "e": 1189, "s": 1062, "text": "The HTML novalidate attribute define that while submitting the form the form data should not be validated in an HTML document." }, { "code": null, "e": 1215, "s": 1189, "text": "Following is the syntax −" }, { "code": null, "e": 1240, "s": 1215, "text": "<form novalidate></form>" }, { "code": null, "e": 1293, "s": 1240, "text": "Let us see an example of HTML novalidate Attribute −" }, { "code": null, "e": 1304, "s": 1293, "text": " Live Demo" }, { "code": null, "e": 2438, "s": 1304, "text": "<!DOCTYPE html>\n<html>\n<style>\n body {\n color: #000;\n height: 100vh;\n background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) no-repeat;\n text-align: center;\n }\n input[type='text'] {\n width: 300px;\n padding: 8px 16px;\n border: 2px solid #fff;\n background: transparent;\n border-radius: 20px;\n display: block;\n margin: 1rem auto;\n outline: none;\n }\n .btn {\n background: #db133a;\n border: none;\n height: 2rem;\n border-radius: 20px;\n width: 330px;\n display: block;\n color: #fff;\n outline: none;\n cursor: pointer;\n margin: 1rem auto;\n }\n ::placeholder {\n color: #000;\n }\n</style>\n<body>\n<h1>HTML novalidate attribute Demo</h1>\n<form>\n<input type=\"text\" placeholder=\"Enter your name\" required>\n<input type=\"submit\" value=\"Submit\" class=\"btn\" onclick='check()'>\n</form>\n<button type='button' class=\"btn\" onclick=\"set()\">Set No Validation</button>\n<div class=\"show\"></div>\n<script>\n function set() {\n document.querySelector('form').setAttribute('novalidate', 'true');\n }\n</script>\n</body>\n</html>" }, { "code": null, "e": 2551, "s": 2438, "text": "Try to click on “Submit” button without entering any name in the text field, it will produce a warning message −" }, { "code": null, "e": 2791, "s": 2551, "text": "Now click on “Set No Validation” button to set novalidate attribute on the form element and now try to submit the form without entering any name in the text field, this time it will easily get submitted without showing any warning message " }, { "code": null, "e": 2793, "s": 2791, "text": "−" } ]
8086 program to convert 8 bit BCD number into ASCII Code - GeeksforGeeks
13 Jan, 2022 Problem – Write an assembly language program in 8086 microprocessor to convert 8 bit BCD number to its respective ASCII Code. Assumption – Starting address of program: 400 Input memory location: 2000 Output memory location: 3000 Example : Input: DATA: 98H in memory location 2000 Output: DATA: 38H in memory location 3000 and 39H in memory location 3001 Algorithm – Load contents of memory location 2000 in register AL Copy contents of register AL in register AH Perform AND operation on register AL with 0F Assign 04 to CL Register Shift the contents of AH by executing SHR instruction using CL Perform OR operation on register AX with 3030 Store the content of AX in memory location 3000 Load contents of memory location 2000 in register AL Copy contents of register AL in register AH Perform AND operation on register AL with 0F Assign 04 to CL Register Shift the contents of AH by executing SHR instruction using CL Perform OR operation on register AX with 3030 Store the content of AX in memory location 3000 Program – Explanation – MOV AL, [2000]: loads contents of memory location 2000 in AL MOV AH, AL: copy contents of AL in AH AND AL, 0F: do AND operation on AL with 0F MOV CL, 04 assign 04 to CL register SHR AH, CL: shift the content of AH register right by 4 bits i.e. value of CL register OR AX, 3030: do OR operation on AX with 3030 MOV [3000], AX: stores the content of AX register pair in 3000 memory address HLT: stops executing the program MOV AL, [2000]: loads contents of memory location 2000 in AL MOV AH, AL: copy contents of AL in AH AND AL, 0F: do AND operation on AL with 0F MOV CL, 04 assign 04 to CL register SHR AH, CL: shift the content of AH register right by 4 bits i.e. value of CL register OR AX, 3030: do OR operation on AX with 3030 MOV [3000], AX: stores the content of AX register pair in 3000 memory address HLT: stops executing the program gulshankumarar231 rkbhola5 microprocessor system-programming Computer Organization & Architecture microprocessor Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Logical and Physical Address in Operating System Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput) Memory Hierarchy Design and its Characteristics Computer Organization | Von Neumann architecture Architecture of 8085 microprocessor Interrupts Difference between Von Neumann and Harvard Architecture IEEE Standard 754 Floating Point Numbers Pin diagram of 8085 microprocessor Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)
[ { "code": null, "e": 24992, "s": 24964, "text": "\n13 Jan, 2022" }, { "code": null, "e": 25119, "s": 24992, "text": "Problem – Write an assembly language program in 8086 microprocessor to convert 8 bit BCD number to its respective ASCII Code. " }, { "code": null, "e": 25223, "s": 25119, "text": "Assumption – Starting address of program: 400 Input memory location: 2000 Output memory location: 3000 " }, { "code": null, "e": 25234, "s": 25223, "text": "Example : " }, { "code": null, "e": 25359, "s": 25234, "text": "Input: \nDATA: 98H in memory location 2000\n\nOutput:\nDATA: 38H in memory location 3000 and \n 39H in memory location 3001 " }, { "code": null, "e": 25372, "s": 25359, "text": "Algorithm – " }, { "code": null, "e": 25704, "s": 25372, "text": "Load contents of memory location 2000 in register AL Copy contents of register AL in register AH Perform AND operation on register AL with 0F Assign 04 to CL Register Shift the contents of AH by executing SHR instruction using CL Perform OR operation on register AX with 3030 Store the content of AX in memory location 3000 " }, { "code": null, "e": 25759, "s": 25704, "text": "Load contents of memory location 2000 in register AL " }, { "code": null, "e": 25805, "s": 25759, "text": "Copy contents of register AL in register AH " }, { "code": null, "e": 25852, "s": 25805, "text": "Perform AND operation on register AL with 0F " }, { "code": null, "e": 25879, "s": 25852, "text": "Assign 04 to CL Register " }, { "code": null, "e": 25944, "s": 25879, "text": "Shift the contents of AH by executing SHR instruction using CL " }, { "code": null, "e": 25992, "s": 25944, "text": "Perform OR operation on register AX with 3030 " }, { "code": null, "e": 26042, "s": 25992, "text": "Store the content of AX in memory location 3000 " }, { "code": null, "e": 26053, "s": 26042, "text": "Program – " }, { "code": null, "e": 26068, "s": 26053, "text": "Explanation – " }, { "code": null, "e": 26496, "s": 26068, "text": "MOV AL, [2000]: loads contents of memory location 2000 in AL MOV AH, AL: copy contents of AL in AH AND AL, 0F: do AND operation on AL with 0F MOV CL, 04 assign 04 to CL register SHR AH, CL: shift the content of AH register right by 4 bits i.e. value of CL register OR AX, 3030: do OR operation on AX with 3030 MOV [3000], AX: stores the content of AX register pair in 3000 memory address HLT: stops executing the program" }, { "code": null, "e": 26559, "s": 26496, "text": "MOV AL, [2000]: loads contents of memory location 2000 in AL " }, { "code": null, "e": 26599, "s": 26559, "text": "MOV AH, AL: copy contents of AL in AH " }, { "code": null, "e": 26644, "s": 26599, "text": "AND AL, 0F: do AND operation on AL with 0F " }, { "code": null, "e": 26682, "s": 26644, "text": "MOV CL, 04 assign 04 to CL register " }, { "code": null, "e": 26771, "s": 26682, "text": "SHR AH, CL: shift the content of AH register right by 4 bits i.e. value of CL register " }, { "code": null, "e": 26818, "s": 26771, "text": "OR AX, 3030: do OR operation on AX with 3030 " }, { "code": null, "e": 26898, "s": 26818, "text": "MOV [3000], AX: stores the content of AX register pair in 3000 memory address " }, { "code": null, "e": 26931, "s": 26898, "text": "HLT: stops executing the program" }, { "code": null, "e": 26949, "s": 26931, "text": "gulshankumarar231" }, { "code": null, "e": 26958, "s": 26949, "text": "rkbhola5" }, { "code": null, "e": 26973, "s": 26958, "text": "microprocessor" }, { "code": null, "e": 26992, "s": 26973, "text": "system-programming" }, { "code": null, "e": 27029, "s": 26992, "text": "Computer Organization & Architecture" }, { "code": null, "e": 27044, "s": 27029, "text": "microprocessor" }, { "code": null, "e": 27142, "s": 27044, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27191, "s": 27142, "text": "Logical and Physical Address in Operating System" }, { "code": null, "e": 27286, "s": 27191, "text": "Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)" }, { "code": null, "e": 27334, "s": 27286, "text": "Memory Hierarchy Design and its Characteristics" }, { "code": null, "e": 27383, "s": 27334, "text": "Computer Organization | Von Neumann architecture" }, { "code": null, "e": 27419, "s": 27383, "text": "Architecture of 8085 microprocessor" }, { "code": null, "e": 27430, "s": 27419, "text": "Interrupts" }, { "code": null, "e": 27486, "s": 27430, "text": "Difference between Von Neumann and Harvard Architecture" }, { "code": null, "e": 27527, "s": 27486, "text": "IEEE Standard 754 Floating Point Numbers" }, { "code": null, "e": 27562, "s": 27527, "text": "Pin diagram of 8085 microprocessor" } ]
Anonymous Inner Class in Java - GeeksforGeeks
15 Dec, 2021 Nested Classes in Java is prerequisite required before adhering forward to grasp about anonymous Inner class. It is an inner class without a name and for which only a single object is created. An anonymous inner class can be useful when making an instance of an object with certain “extras” such as overriding methods of a class or interface, without having to actually subclass a class. Tip: Anonymous inner classes are useful in writing implementation classes for listener interfaces in graphics programming. The syntax of an anonymous class expression is like the invocation of a constructor, except that there is a class definition contained in a block of code. Syntax: // Test can be interface,abstract/concrete class Test t = new Test() { // data members and methods public void test_method() { ........ ........ } }; Now let us do discuss the difference between regular class(normal classes) and Anonymous Inner class A normal class can implement any number of interfaces but the anonymous inner class can implement only one interface at a time. A regular class can extend a class and implement any number of interfaces simultaneously. But anonymous Inner class can extend a class or can implement an interface but not both at a time. For regular/normal class, we can write any number of constructors but we can’t write any constructor for anonymous Inner class because the anonymous class does not have any name and while defining constructor class name and constructor name must be same. Accessing Local Variables of the Enclosing Scope, and Declaring and Accessing Members of the Anonymous Class Like local classes, anonymous classes can capture variables; they have the same access to local variables of the enclosing scope: An anonymous class has access to the members of its enclosing class. An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final. Like a nested class, a declaration of a type (such as a variable) in anonymous class shadows any other declarations in the enclosing scope that have the same name. Anonymous classes also have the same restrictions as local classes with respect to their members: We cannot declare static initializers or member interfaces in an anonymous class. An anonymous class can have static members provided that they are constant variables. Note: We can declare the following in anonymous classes as follows: Fields Extra methods (even if they do not implement any methods of the supertype) Instance initializers Local classes Ways: Anonymous inner classes are generic created via below listed two ways as follows: Class (may be abstract or concrete)Interface Class (may be abstract or concrete) Interface Now let us take an example with which we will understand anonymous inner class, let us take a simple program Example Java // Java program to demonstrate Need for// Anonymous Inner class // Interfaceinterface Age { // Defining variables and methods int x = 21; void getAge();} // Class 1// Helper class implementing methods of Age Interfaceclass MyClass implements Age { // Overriding getAge() method @Override public void getAge() { // Print statement System.out.print("Age is " + x); }} // Class 2// Main class// AnonymousDemoclass GFG { // Main driver method public static void main(String[] args) { // Class 1 is implementation class of Age interface MyClass obj = new MyClass(); // calling getage() method implemented at Class1 // inside main() method obj.getAge(); }} Output: Output explanation: In the above program, interface Age is created with getAge() method and x=21. Myclass is written as an implementation class of Age interface. As done in Program, there is no need to write a separate class Myclass. Instead, directly copy the code of Myclass into this parameter, as shown here: Age oj1 = new Age() { @Override public void getAge() { System.out.print("Age is " + x); } }; Here, an object to Age is not created but an object of Myclass is created and copied in the entire class code as shown above. This is possible only with anonymous inner class. Such a class is called ‘anonymous inner class’, so here we call ‘Myclass’ as anonymous inner class. Example: Java // Java Program to Demonstrate Anonymous inner class // Interfaceinterface Age { int x = 21; void getAge();} // Main classclass AnonymousDemo { // Main driver method public static void main(String[] args) { // Myclass is hidden inner class of Age interface // whose name is not written but an object to it // is created. Age oj1 = new Age() { @Override public void getAge() { // printing age System.out.print("Age is " + x); } }; oj1.getAge(); }} Age is 21 Based on declaration and behavior, there are 3 types of anonymous Inner classes: Anonymous Inner class that extends a classAnonymous Inner class that implements an interfaceAnonymous Inner class that defines inside method/constructor argument Anonymous Inner class that extends a class Anonymous Inner class that implements an interface Anonymous Inner class that defines inside method/constructor argument Type 1: Anonymous Inner class that extends a class We can have an anonymous inner class that extends a class. For example, we know that we can create a thread by extending a Thread class. Suppose we need an immediate thread but we don’t want to create a class that extends Thread class all the time. With the help of this type of Anonymous Inner class, we can define a ready thread. Example Java // Java program to illustrate creating an immediate thread// Using Anonymous Inner class that extends a Class // Main classclass MyThread { // Main driver method public static void main(String[] args) { // Using Anonymous Inner class that extends a class // Here a Thread class Thread t = new Thread() { // run() method for the thread public void run() { // Print statement for child thread // execution System.out.println("Child Thread"); } }; // Starting the thread t.start(); // Displaying main thread only for readability System.out.println("Main Thread"); }} Main Thread Child Thread Type 2: Anonymous Inner class that implements an interface We can also have an anonymous inner class that implements an interface. For example, we also know that by implementing Runnable interface we can create a Thread. Here we use an anonymous Inner class that implements an interface. Example Java // Java program to illustrate defining a thread// Using Anonymous Inner class that implements an interface // Main classclass MyThread { // Main driver method public static void main(String[] args) { // Here we are using Anonymous Inner class // that implements a interface i.e. Here Runnable // interface Runnable r = new Runnable() { // run() method for the thread public void run() { // Print statement when run() is invoked System.out.println("Child Thread"); } }; // Creating thread in main() using Thread class Thread t = new Thread(r); // Starting the thread using start() method // which invokes run() method automatically t.start(); // Print statement only System.out.println("Main Thread"); }} Main Thread Child Thread Type 3: Anonymous Inner class that defines inside method/constructor argument Anonymous inner classes in method/constructor arguments are often used in graphical user interface (GUI) applications. To get you familiar with syntax lets have a look at the following program that creates a thread using this type of Anonymous Inner class Example Java // Java program to illustrate defining a thread// Using Anonymous Inner class that define inside argument // Main classclass MyThread { // Main driver method public static void main(String[] args) { // Using Anonymous Inner class that define inside // argument // Here constructor argument Thread t = new Thread(new Runnable() { public void run() { System.out.println("Child Thread"); } }); t.start(); System.out.println("Main Thread"); }} Main Thread Child Thread However, constructors can not be declared in an anonymous class.This article is contributed by Nishant Sharma and Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.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. soumyajyotibhowmik kapoorsagar226 arorakashish0911 Java-Class and Object Java Java-Class and Object Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Arrays in Java Split() String method in Java with examples For-each loop in Java Reverse a string in Java Arrays.sort() in Java with examples Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples How to iterate any Map in Java Initialize an ArrayList in Java Interfaces in Java
[ { "code": null, "e": 22939, "s": 22911, "text": "\n15 Dec, 2021" }, { "code": null, "e": 23327, "s": 22939, "text": "Nested Classes in Java is prerequisite required before adhering forward to grasp about anonymous Inner class. It is an inner class without a name and for which only a single object is created. An anonymous inner class can be useful when making an instance of an object with certain “extras” such as overriding methods of a class or interface, without having to actually subclass a class." }, { "code": null, "e": 23451, "s": 23327, "text": "Tip: Anonymous inner classes are useful in writing implementation classes for listener interfaces in graphics programming. " }, { "code": null, "e": 23607, "s": 23451, "text": "The syntax of an anonymous class expression is like the invocation of a constructor, except that there is a class definition contained in a block of code. " }, { "code": null, "e": 23615, "s": 23607, "text": "Syntax:" }, { "code": null, "e": 23795, "s": 23615, "text": "// Test can be interface,abstract/concrete class\nTest t = new Test() \n{\n // data members and methods\n public void test_method() \n {\n ........\n ........\n } \n};" }, { "code": null, "e": 23896, "s": 23795, "text": "Now let us do discuss the difference between regular class(normal classes) and Anonymous Inner class" }, { "code": null, "e": 24024, "s": 23896, "text": "A normal class can implement any number of interfaces but the anonymous inner class can implement only one interface at a time." }, { "code": null, "e": 24213, "s": 24024, "text": "A regular class can extend a class and implement any number of interfaces simultaneously. But anonymous Inner class can extend a class or can implement an interface but not both at a time." }, { "code": null, "e": 24468, "s": 24213, "text": "For regular/normal class, we can write any number of constructors but we can’t write any constructor for anonymous Inner class because the anonymous class does not have any name and while defining constructor class name and constructor name must be same." }, { "code": null, "e": 24578, "s": 24468, "text": "Accessing Local Variables of the Enclosing Scope, and Declaring and Accessing Members of the Anonymous Class " }, { "code": null, "e": 24710, "s": 24578, "text": "Like local classes, anonymous classes can capture variables; they have the same access to local variables of the enclosing scope: " }, { "code": null, "e": 24779, "s": 24710, "text": "An anonymous class has access to the members of its enclosing class." }, { "code": null, "e": 24904, "s": 24779, "text": "An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final." }, { "code": null, "e": 25068, "s": 24904, "text": "Like a nested class, a declaration of a type (such as a variable) in anonymous class shadows any other declarations in the enclosing scope that have the same name." }, { "code": null, "e": 25167, "s": 25068, "text": "Anonymous classes also have the same restrictions as local classes with respect to their members: " }, { "code": null, "e": 25249, "s": 25167, "text": "We cannot declare static initializers or member interfaces in an anonymous class." }, { "code": null, "e": 25335, "s": 25249, "text": "An anonymous class can have static members provided that they are constant variables." }, { "code": null, "e": 25403, "s": 25335, "text": "Note: We can declare the following in anonymous classes as follows:" }, { "code": null, "e": 25410, "s": 25403, "text": "Fields" }, { "code": null, "e": 25485, "s": 25410, "text": "Extra methods (even if they do not implement any methods of the supertype)" }, { "code": null, "e": 25507, "s": 25485, "text": "Instance initializers" }, { "code": null, "e": 25521, "s": 25507, "text": "Local classes" }, { "code": null, "e": 25527, "s": 25521, "text": "Ways:" }, { "code": null, "e": 25610, "s": 25527, "text": "Anonymous inner classes are generic created via below listed two ways as follows: " }, { "code": null, "e": 25655, "s": 25610, "text": "Class (may be abstract or concrete)Interface" }, { "code": null, "e": 25691, "s": 25655, "text": "Class (may be abstract or concrete)" }, { "code": null, "e": 25701, "s": 25691, "text": "Interface" }, { "code": null, "e": 25810, "s": 25701, "text": "Now let us take an example with which we will understand anonymous inner class, let us take a simple program" }, { "code": null, "e": 25818, "s": 25810, "text": "Example" }, { "code": null, "e": 25823, "s": 25818, "text": "Java" }, { "code": "// Java program to demonstrate Need for// Anonymous Inner class // Interfaceinterface Age { // Defining variables and methods int x = 21; void getAge();} // Class 1// Helper class implementing methods of Age Interfaceclass MyClass implements Age { // Overriding getAge() method @Override public void getAge() { // Print statement System.out.print(\"Age is \" + x); }} // Class 2// Main class// AnonymousDemoclass GFG { // Main driver method public static void main(String[] args) { // Class 1 is implementation class of Age interface MyClass obj = new MyClass(); // calling getage() method implemented at Class1 // inside main() method obj.getAge(); }}", "e": 26559, "s": 25823, "text": null }, { "code": null, "e": 26567, "s": 26559, "text": "Output:" }, { "code": null, "e": 26587, "s": 26567, "text": "Output explanation:" }, { "code": null, "e": 26885, "s": 26587, "text": "In the above program, interface Age is created with getAge() method and x=21. Myclass is written as an implementation class of Age interface. As done in Program, there is no need to write a separate class Myclass. Instead, directly copy the code of Myclass into this parameter, as shown here: " }, { "code": null, "e": 27004, "s": 26885, "text": "Age oj1 = new Age() \n{\n @Override\n public void getAge() \n {\n System.out.print(\"Age is \" + x);\n }\n};" }, { "code": null, "e": 27280, "s": 27004, "text": "Here, an object to Age is not created but an object of Myclass is created and copied in the entire class code as shown above. This is possible only with anonymous inner class. Such a class is called ‘anonymous inner class’, so here we call ‘Myclass’ as anonymous inner class." }, { "code": null, "e": 27289, "s": 27280, "text": "Example:" }, { "code": null, "e": 27294, "s": 27289, "text": "Java" }, { "code": "// Java Program to Demonstrate Anonymous inner class // Interfaceinterface Age { int x = 21; void getAge();} // Main classclass AnonymousDemo { // Main driver method public static void main(String[] args) { // Myclass is hidden inner class of Age interface // whose name is not written but an object to it // is created. Age oj1 = new Age() { @Override public void getAge() { // printing age System.out.print(\"Age is \" + x); } }; oj1.getAge(); }}", "e": 27887, "s": 27294, "text": null }, { "code": null, "e": 27897, "s": 27887, "text": "Age is 21" }, { "code": null, "e": 27979, "s": 27897, "text": "Based on declaration and behavior, there are 3 types of anonymous Inner classes: " }, { "code": null, "e": 28141, "s": 27979, "text": "Anonymous Inner class that extends a classAnonymous Inner class that implements an interfaceAnonymous Inner class that defines inside method/constructor argument" }, { "code": null, "e": 28184, "s": 28141, "text": "Anonymous Inner class that extends a class" }, { "code": null, "e": 28235, "s": 28184, "text": "Anonymous Inner class that implements an interface" }, { "code": null, "e": 28305, "s": 28235, "text": "Anonymous Inner class that defines inside method/constructor argument" }, { "code": null, "e": 28356, "s": 28305, "text": "Type 1: Anonymous Inner class that extends a class" }, { "code": null, "e": 28688, "s": 28356, "text": "We can have an anonymous inner class that extends a class. For example, we know that we can create a thread by extending a Thread class. Suppose we need an immediate thread but we don’t want to create a class that extends Thread class all the time. With the help of this type of Anonymous Inner class, we can define a ready thread." }, { "code": null, "e": 28696, "s": 28688, "text": "Example" }, { "code": null, "e": 28701, "s": 28696, "text": "Java" }, { "code": "// Java program to illustrate creating an immediate thread// Using Anonymous Inner class that extends a Class // Main classclass MyThread { // Main driver method public static void main(String[] args) { // Using Anonymous Inner class that extends a class // Here a Thread class Thread t = new Thread() { // run() method for the thread public void run() { // Print statement for child thread // execution System.out.println(\"Child Thread\"); } }; // Starting the thread t.start(); // Displaying main thread only for readability System.out.println(\"Main Thread\"); }}", "e": 29438, "s": 28701, "text": null }, { "code": null, "e": 29463, "s": 29438, "text": "Main Thread\nChild Thread" }, { "code": null, "e": 29522, "s": 29463, "text": "Type 2: Anonymous Inner class that implements an interface" }, { "code": null, "e": 29751, "s": 29522, "text": "We can also have an anonymous inner class that implements an interface. For example, we also know that by implementing Runnable interface we can create a Thread. Here we use an anonymous Inner class that implements an interface." }, { "code": null, "e": 29759, "s": 29751, "text": "Example" }, { "code": null, "e": 29764, "s": 29759, "text": "Java" }, { "code": "// Java program to illustrate defining a thread// Using Anonymous Inner class that implements an interface // Main classclass MyThread { // Main driver method public static void main(String[] args) { // Here we are using Anonymous Inner class // that implements a interface i.e. Here Runnable // interface Runnable r = new Runnable() { // run() method for the thread public void run() { // Print statement when run() is invoked System.out.println(\"Child Thread\"); } }; // Creating thread in main() using Thread class Thread t = new Thread(r); // Starting the thread using start() method // which invokes run() method automatically t.start(); // Print statement only System.out.println(\"Main Thread\"); }}", "e": 30655, "s": 29764, "text": null }, { "code": null, "e": 30680, "s": 30655, "text": "Main Thread\nChild Thread" }, { "code": null, "e": 30758, "s": 30680, "text": "Type 3: Anonymous Inner class that defines inside method/constructor argument" }, { "code": null, "e": 31014, "s": 30758, "text": "Anonymous inner classes in method/constructor arguments are often used in graphical user interface (GUI) applications. To get you familiar with syntax lets have a look at the following program that creates a thread using this type of Anonymous Inner class" }, { "code": null, "e": 31022, "s": 31014, "text": "Example" }, { "code": null, "e": 31027, "s": 31022, "text": "Java" }, { "code": "// Java program to illustrate defining a thread// Using Anonymous Inner class that define inside argument // Main classclass MyThread { // Main driver method public static void main(String[] args) { // Using Anonymous Inner class that define inside // argument // Here constructor argument Thread t = new Thread(new Runnable() { public void run() { System.out.println(\"Child Thread\"); } }); t.start(); System.out.println(\"Main Thread\"); }}", "e": 31589, "s": 31027, "text": null }, { "code": null, "e": 31614, "s": 31589, "text": "Main Thread\nChild Thread" }, { "code": null, "e": 32070, "s": 31614, "text": "However, constructors can not be declared in an anonymous class.This article is contributed by Nishant Sharma and Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.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": 32089, "s": 32070, "text": "soumyajyotibhowmik" }, { "code": null, "e": 32104, "s": 32089, "text": "kapoorsagar226" }, { "code": null, "e": 32121, "s": 32104, "text": "arorakashish0911" }, { "code": null, "e": 32143, "s": 32121, "text": "Java-Class and Object" }, { "code": null, "e": 32148, "s": 32143, "text": "Java" }, { "code": null, "e": 32170, "s": 32148, "text": "Java-Class and Object" }, { "code": null, "e": 32175, "s": 32170, "text": "Java" }, { "code": null, "e": 32273, "s": 32175, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32282, "s": 32273, "text": "Comments" }, { "code": null, "e": 32295, "s": 32282, "text": "Old Comments" }, { "code": null, "e": 32310, "s": 32295, "text": "Arrays in Java" }, { "code": null, "e": 32354, "s": 32310, "text": "Split() String method in Java with examples" }, { "code": null, "e": 32376, "s": 32354, "text": "For-each loop in Java" }, { "code": null, "e": 32401, "s": 32376, "text": "Reverse a string in Java" }, { "code": null, "e": 32437, "s": 32401, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 32488, "s": 32437, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 32518, "s": 32488, "text": "HashMap in Java with Examples" }, { "code": null, "e": 32549, "s": 32518, "text": "How to iterate any Map in Java" }, { "code": null, "e": 32581, "s": 32549, "text": "Initialize an ArrayList in Java" } ]
C++ String Library - find_last_of
It searches the string for the last character that matches any of the characters specified in its arguments. Following is the declaration for std::string::find_last_of. size_t find_last_of (const string& str, size_t pos = npos) const; size_t find_last_of (const string& str, size_t pos = npos) const noexcept; size_t find_last_of (const string& str, size_t pos = npos) const noexcept; str − It is a string object. str − It is a string object. len − It is used to copy the characters. len − It is used to copy the characters. pos − Position of the first character to be copied. pos − Position of the first character to be copied. none if an exception is thrown, there are no changes in the string. In below example for std::string::find_last_of. #include <iostream> #include <string> #include <cstddef> void SplitFilename (const std::string& str) { std::cout << "Splitting: " << str << '\n'; std::size_t found = str.find_last_of("/\\"); std::cout << " path: " << str.substr(0,found) << '\n'; std::cout << " file: " << str.substr(found+1) << '\n'; } int main () { std::string str1 ("/usr/bin/man"); std::string str2 ("c:\\windows\\winhelp.exe"); SplitFilename (str1); SplitFilename (str2); return 0; } Print Add Notes Bookmark this page
[ { "code": null, "e": 2712, "s": 2603, "text": "It searches the string for the last character that matches any of the characters specified in its arguments." }, { "code": null, "e": 2772, "s": 2712, "text": "Following is the declaration for std::string::find_last_of." }, { "code": null, "e": 2838, "s": 2772, "text": "size_t find_last_of (const string& str, size_t pos = npos) const;" }, { "code": null, "e": 2913, "s": 2838, "text": "size_t find_last_of (const string& str, size_t pos = npos) const noexcept;" }, { "code": null, "e": 2988, "s": 2913, "text": "size_t find_last_of (const string& str, size_t pos = npos) const noexcept;" }, { "code": null, "e": 3017, "s": 2988, "text": "str − It is a string object." }, { "code": null, "e": 3046, "s": 3017, "text": "str − It is a string object." }, { "code": null, "e": 3087, "s": 3046, "text": "len − It is used to copy the characters." }, { "code": null, "e": 3128, "s": 3087, "text": "len − It is used to copy the characters." }, { "code": null, "e": 3180, "s": 3128, "text": "pos − Position of the first character to be copied." }, { "code": null, "e": 3232, "s": 3180, "text": "pos − Position of the first character to be copied." }, { "code": null, "e": 3237, "s": 3232, "text": "none" }, { "code": null, "e": 3300, "s": 3237, "text": "if an exception is thrown, there are no changes in the string." }, { "code": null, "e": 3348, "s": 3300, "text": "In below example for std::string::find_last_of." }, { "code": null, "e": 3833, "s": 3348, "text": "#include <iostream>\n#include <string>\n#include <cstddef>\nvoid SplitFilename (const std::string& str) {\n std::cout << \"Splitting: \" << str << '\\n';\n std::size_t found = str.find_last_of(\"/\\\\\");\n std::cout << \" path: \" << str.substr(0,found) << '\\n';\n std::cout << \" file: \" << str.substr(found+1) << '\\n';\n}\n\nint main () {\n std::string str1 (\"/usr/bin/man\");\n std::string str2 (\"c:\\\\windows\\\\winhelp.exe\");\n\n SplitFilename (str1);\n SplitFilename (str2);\n\n return 0;\n}" }, { "code": null, "e": 3840, "s": 3833, "text": " Print" }, { "code": null, "e": 3851, "s": 3840, "text": " Add Notes" } ]
Knock - Subdomain Scanner Tool in Kali Linux - GeeksforGeeks
18 Jul, 2021 Knock is a tool written in Python and is designed to enumerate subdomains in a target domain through a wordlist. First clone the tool from the GitHub repository by using the below command. git clone https://github.com/santiko/KnockPy.git Then Change to your preferred directory. cd KnockPy Fig 1: Cloning tool from GitHub repository. Run tool: To run the tool and to know its options, type the following command. python knock.py -h Fig 2: Options provided by Knock. Show version: To show version of the tool, enter: python knock.py -v Fig 3: Version of knock. Short information: To find out short information about any domain, enter: python knock.py -i domain name (which in our case is google.com) Fig 4: Short info about google.com Resolve: To resolve domain name, type: python knock.py -r google.com Fig 5: Resolving domain google.com Zone Transfer: To check if zone transfer is enabled or not, enter the following command. python knock.py -z youtube.com Fig 6: Checking zone transfer enabled or not. Subdomains: To get the subdomain of a website, type the following command python knock.py tesla.com Fig 7: Getting subdomains. As we can see from the image shown below, that knock found 48 subdomains in 12 hosts of tesla.com Fig 8: subdomains Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Thread functions in C/C++ mv command in Linux with examples nohup Command in Linux with Examples scp command in Linux with Examples Docker - COPY Instruction chown command in Linux with Examples nslookup command in Linux with Examples SED command in Linux | Set 2 Named Pipe or FIFO with example C program uniq Command in LINUX with examples
[ { "code": null, "e": 24039, "s": 24011, "text": "\n18 Jul, 2021" }, { "code": null, "e": 24152, "s": 24039, "text": "Knock is a tool written in Python and is designed to enumerate subdomains in a target domain through a wordlist." }, { "code": null, "e": 24228, "s": 24152, "text": "First clone the tool from the GitHub repository by using the below command." }, { "code": null, "e": 24277, "s": 24228, "text": "git clone https://github.com/santiko/KnockPy.git" }, { "code": null, "e": 24318, "s": 24277, "text": "Then Change to your preferred directory." }, { "code": null, "e": 24329, "s": 24318, "text": "cd KnockPy" }, { "code": null, "e": 24373, "s": 24329, "text": "Fig 1: Cloning tool from GitHub repository." }, { "code": null, "e": 24452, "s": 24373, "text": "Run tool: To run the tool and to know its options, type the following command." }, { "code": null, "e": 24471, "s": 24452, "text": "python knock.py -h" }, { "code": null, "e": 24505, "s": 24471, "text": "Fig 2: Options provided by Knock." }, { "code": null, "e": 24555, "s": 24505, "text": "Show version: To show version of the tool, enter:" }, { "code": null, "e": 24574, "s": 24555, "text": "python knock.py -v" }, { "code": null, "e": 24599, "s": 24574, "text": "Fig 3: Version of knock." }, { "code": null, "e": 24673, "s": 24599, "text": "Short information: To find out short information about any domain, enter:" }, { "code": null, "e": 24738, "s": 24673, "text": "python knock.py -i domain name (which in our case is google.com)" }, { "code": null, "e": 24773, "s": 24738, "text": "Fig 4: Short info about google.com" }, { "code": null, "e": 24812, "s": 24773, "text": "Resolve: To resolve domain name, type:" }, { "code": null, "e": 24842, "s": 24812, "text": "python knock.py -r google.com" }, { "code": null, "e": 24877, "s": 24842, "text": "Fig 5: Resolving domain google.com" }, { "code": null, "e": 24966, "s": 24877, "text": "Zone Transfer: To check if zone transfer is enabled or not, enter the following command." }, { "code": null, "e": 24997, "s": 24966, "text": "python knock.py -z youtube.com" }, { "code": null, "e": 25043, "s": 24997, "text": "Fig 6: Checking zone transfer enabled or not." }, { "code": null, "e": 25117, "s": 25043, "text": "Subdomains: To get the subdomain of a website, type the following command" }, { "code": null, "e": 25143, "s": 25117, "text": "python knock.py tesla.com" }, { "code": null, "e": 25170, "s": 25143, "text": "Fig 7: Getting subdomains." }, { "code": null, "e": 25268, "s": 25170, "text": "As we can see from the image shown below, that knock found 48 subdomains in 12 hosts of tesla.com" }, { "code": null, "e": 25286, "s": 25268, "text": "Fig 8: subdomains" }, { "code": null, "e": 25297, "s": 25286, "text": "Kali-Linux" }, { "code": null, "e": 25309, "s": 25297, "text": "Linux-Tools" }, { "code": null, "e": 25320, "s": 25309, "text": "Linux-Unix" }, { "code": null, "e": 25418, "s": 25320, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25427, "s": 25418, "text": "Comments" }, { "code": null, "e": 25440, "s": 25427, "text": "Old Comments" }, { "code": null, "e": 25466, "s": 25440, "text": "Thread functions in C/C++" }, { "code": null, "e": 25500, "s": 25466, "text": "mv command in Linux with examples" }, { "code": null, "e": 25537, "s": 25500, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 25572, "s": 25537, "text": "scp command in Linux with Examples" }, { "code": null, "e": 25598, "s": 25572, "text": "Docker - COPY Instruction" }, { "code": null, "e": 25635, "s": 25598, "text": "chown command in Linux with Examples" }, { "code": null, "e": 25675, "s": 25635, "text": "nslookup command in Linux with Examples" }, { "code": null, "e": 25704, "s": 25675, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 25746, "s": 25704, "text": "Named Pipe or FIFO with example C program" } ]
Check if an integer can be expressed as a sum of two semi-primes in Python
Suppose we have a number n, we have to check whether n can be expressed as a sum of two semi-primes or not. As we know the semi-prime is a number if it can be expressed as product of two primes number. First few semi-prime numbers are (1 - 100 range): 4, 6, 9, 10, 14, 15, 21, 22, 25, 26, 33, 34, 35, 38, 39, 46, 49, 51, 55, 57, 58, 62, 65, 69, 74, 77, 82, 85, 86, 87, 91, 93, 94, 95. So, if the input is like n = 108, then the output will be True as this is sum of 14 and 94 both are semi-prime. To solve this, we will follow these steps − MAX := 10000 assuming given inputs are sum of semi-primes which are in range 1 to 10000 nums := a new list s_prime_flags := an array of size MAX and fill with False Define a function get_semi_primes() . This will take for i in range 2 to MAX - 1, docount := 0num := ij := 2while count < 2 and j^2 <= num, dowhile num is divisible by j, donum := num / jcount := count + 1j := j + 1if num > 1, thencount := count + 1if count is same as 2, thens_prime_flags[i] := True count := 0 num := i j := 2 while count < 2 and j^2 <= num, dowhile num is divisible by j, donum := num / jcount := count + 1j := j + 1 while num is divisible by j, donum := num / jcount := count + 1 num := num / j count := count + 1 j := j + 1 if num > 1, thencount := count + 1 count := count + 1 if count is same as 2, thens_prime_flags[i] := True s_prime_flags[i] := True insert i at the end of nums From the main method do the following − call get_semi_primes() i := 0 while nums[i] <= quotient of (n / 2), doif s_prime_flags[n - nums[i]] is True, thenreturn Truei := i + 1 if s_prime_flags[n - nums[i]] is True, thenreturn True return True i := i + 1 return False Let us see the following implementation to get better understanding − Live Demo MAX = 10000 nums = [] s_prime_flags = [False] * MAX def get_semi_primes(): for i in range(2, MAX): count = 0 num = i j = 2 while count < 2 and j * j <= num: while num % j == 0: num /= j count += 1 j += 1 if num > 1: count += 1 if count == 2: s_prime_flags[i] = True nums.append(i) def solve(n): get_semi_primes() i = 0 while nums[i] <= n // 2: if s_prime_flags[n - nums[i]] == True: return True i += 1 return False n = 108 print(solve(n)) [4, 2, 3], 11 True
[ { "code": null, "e": 1170, "s": 1062, "text": "Suppose we have a number n, we have to check whether n can be expressed as a sum of two semi-primes or not." }, { "code": null, "e": 1447, "s": 1170, "text": "As we know the semi-prime is a number if it can be expressed as product of two primes number. First few semi-prime numbers are (1 - 100 range): 4, 6, 9, 10, 14, 15, 21, 22, 25, 26, 33, 34, 35, 38, 39, 46, 49, 51, 55, 57, 58, 62, 65, 69, 74, 77, 82, 85, 86, 87, 91, 93, 94, 95." }, { "code": null, "e": 1559, "s": 1447, "text": "So, if the input is like n = 108, then the output will be True as this is sum of 14 and 94 both are semi-prime." }, { "code": null, "e": 1603, "s": 1559, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1691, "s": 1603, "text": "MAX := 10000 assuming given inputs are sum of semi-primes which are in range 1 to 10000" }, { "code": null, "e": 1710, "s": 1691, "text": "nums := a new list" }, { "code": null, "e": 1768, "s": 1710, "text": "s_prime_flags := an array of size MAX and fill with False" }, { "code": null, "e": 1821, "s": 1768, "text": "Define a function get_semi_primes() . This will take" }, { "code": null, "e": 2069, "s": 1821, "text": "for i in range 2 to MAX - 1, docount := 0num := ij := 2while count < 2 and j^2 <= num, dowhile num is divisible by j, donum := num / jcount := count + 1j := j + 1if num > 1, thencount := count + 1if count is same as 2, thens_prime_flags[i] := True" }, { "code": null, "e": 2080, "s": 2069, "text": "count := 0" }, { "code": null, "e": 2089, "s": 2080, "text": "num := i" }, { "code": null, "e": 2096, "s": 2089, "text": "j := 2" }, { "code": null, "e": 2204, "s": 2096, "text": "while count < 2 and j^2 <= num, dowhile num is divisible by j, donum := num / jcount := count + 1j := j + 1" }, { "code": null, "e": 2268, "s": 2204, "text": "while num is divisible by j, donum := num / jcount := count + 1" }, { "code": null, "e": 2283, "s": 2268, "text": "num := num / j" }, { "code": null, "e": 2302, "s": 2283, "text": "count := count + 1" }, { "code": null, "e": 2313, "s": 2302, "text": "j := j + 1" }, { "code": null, "e": 2348, "s": 2313, "text": "if num > 1, thencount := count + 1" }, { "code": null, "e": 2367, "s": 2348, "text": "count := count + 1" }, { "code": null, "e": 2419, "s": 2367, "text": "if count is same as 2, thens_prime_flags[i] := True" }, { "code": null, "e": 2444, "s": 2419, "text": "s_prime_flags[i] := True" }, { "code": null, "e": 2472, "s": 2444, "text": "insert i at the end of nums" }, { "code": null, "e": 2512, "s": 2472, "text": "From the main method do the following −" }, { "code": null, "e": 2535, "s": 2512, "text": "call get_semi_primes()" }, { "code": null, "e": 2542, "s": 2535, "text": "i := 0" }, { "code": null, "e": 2647, "s": 2542, "text": "while nums[i] <= quotient of (n / 2), doif s_prime_flags[n - nums[i]] is True, thenreturn Truei := i + 1" }, { "code": null, "e": 2702, "s": 2647, "text": "if s_prime_flags[n - nums[i]] is True, thenreturn True" }, { "code": null, "e": 2714, "s": 2702, "text": "return True" }, { "code": null, "e": 2725, "s": 2714, "text": "i := i + 1" }, { "code": null, "e": 2738, "s": 2725, "text": "return False" }, { "code": null, "e": 2808, "s": 2738, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2819, "s": 2808, "text": " Live Demo" }, { "code": null, "e": 3396, "s": 2819, "text": "MAX = 10000\nnums = []\ns_prime_flags = [False] * MAX\ndef get_semi_primes():\n for i in range(2, MAX):\n count = 0\n num = i\n j = 2\n while count < 2 and j * j <= num:\n while num % j == 0:\n num /= j\n count += 1\n j += 1\n if num > 1:\n count += 1\n if count == 2:\n s_prime_flags[i] = True\n nums.append(i)\ndef solve(n):\n get_semi_primes()\n i = 0\n while nums[i] <= n // 2:\n if s_prime_flags[n - nums[i]] == True:\n return True\n i += 1\n return False\nn = 108\nprint(solve(n))" }, { "code": null, "e": 3410, "s": 3396, "text": "[4, 2, 3], 11" }, { "code": null, "e": 3415, "s": 3410, "text": "True" } ]
Replace null values with default value in Java Map
To replace null values with default value in Java Map, the code is as follows − Live Demo import java.util.*; import java.util.stream.*; public class Demo{ public static <T, K> Map<K, T> null_vals(Map<K, T> my_map, T def_val){ my_map = my_map.entrySet().stream().map(entry -> { if (entry.getValue() == null) entry.setValue(def_val); return entry; }) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); return my_map; } public static void main(String[] args){ Map<Integer, Integer> my_map = new HashMap<>(); my_map.put(1, null); my_map.put(2, 56); my_map.put(3, null); my_map.put(4, 99); int defaultValue = 0; System.out.println("The map with null values is : "+ my_map); my_map = null_vals(my_map, defaultValue); System.out.println("The map with null values replaced is : " + my_map); } } The map with null values is : {1=null, 2=56, 3=null, 4=99} The map with null values replaced is : {1=0, 2=56, 3=0, 4=99} A class named Demo contains a function named ‘null_vals’ that checks for null values in an array and replaces them with a default value that is previously defined. In the main function, a Map instance is created and elements are pushed into it using the ‘put’ function. The ‘null_vals’ function is called on this map and the null values are replaced with a default value.
[ { "code": null, "e": 1142, "s": 1062, "text": "To replace null values with default value in Java Map, the code is as follows −" }, { "code": null, "e": 1153, "s": 1142, "text": " Live Demo" }, { "code": null, "e": 1985, "s": 1153, "text": "import java.util.*;\nimport java.util.stream.*;\npublic class Demo{\n public static <T, K> Map<K, T> null_vals(Map<K, T> my_map, T def_val){\n my_map = my_map.entrySet().stream().map(entry -> {\n if (entry.getValue() == null)\n entry.setValue(def_val);\n return entry;\n })\n .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));\n return my_map;\n }\n public static void main(String[] args){\n Map<Integer, Integer> my_map = new HashMap<>();\n my_map.put(1, null);\n my_map.put(2, 56);\n my_map.put(3, null);\n my_map.put(4, 99);\n int defaultValue = 0;\n System.out.println(\"The map with null values is : \"+ my_map);\n my_map = null_vals(my_map, defaultValue);\n System.out.println(\"The map with null values replaced is : \" + my_map);\n }\n}" }, { "code": null, "e": 2106, "s": 1985, "text": "The map with null values is : {1=null, 2=56, 3=null, 4=99}\nThe map with null values replaced is : {1=0, 2=56, 3=0, 4=99}" }, { "code": null, "e": 2478, "s": 2106, "text": "A class named Demo contains a function named ‘null_vals’ that checks for null values in an array and replaces them with a default value that is previously defined. In the main function, a Map instance is created and elements are pushed into it using the ‘put’ function. The ‘null_vals’ function is called on this map and the null values are replaced with a default value." } ]
Guide to Big Data Joins — Python, SQL, Pandas, Spark, Dask | by Doug Foo | Towards Data Science
There are many ways to spin a disk, filet a fish, or work with Big Data — here is a quick guide. Kaggle Movies Database [8] — 26 million ratings for 45,000 movies, data split across 5 files: To find the top average ratings for movies you need to join links to metadata to ratings: SELECT m.title, avg(r.rating) FROM links l INNER JOIN to metas m ON m.imdbId=l.imdbId INNER JOIN to ratings ON r.movieId=l.movieId GROUP BY m.title HAVING count(r.rating) > 2 and avg(r.rating) > 4.5 The classic way is to load up a Database, indexing and run the SQL mentioned before (or using classic SQL below): SELECT m.title, avg(r.rating) FROM links l, metas m, ratings r WHERE m.imdbId=l.imdbId and r.movieId=l.movieId GROUP BY m.title HAVING count(r.rating) > 2 and avg(r.rating) > 4.5 Joins in RDBMS are done in 3 major ways with some platform variants: Nested Loops —for each row of Table A lookup the matching key in Table B. An index on B makes the lookup O(A*log B), otherwise the join is SLOW — O(A*B).Hash-Join — build a hash/map of Table B by lookup key, making the join lookup very fast — O(A*1)Merge-Sort — sort both tables and merge on a single pass, not super fast unless pre-sorted — O(A+B+A log A+B log B) → O(A log A + B log B) Nested Loops —for each row of Table A lookup the matching key in Table B. An index on B makes the lookup O(A*log B), otherwise the join is SLOW — O(A*B). Hash-Join — build a hash/map of Table B by lookup key, making the join lookup very fast — O(A*1) Merge-Sort — sort both tables and merge on a single pass, not super fast unless pre-sorted — O(A+B+A log A+B log B) → O(A log A + B log B) Using Sqlite3 [1]— creating a database, tables and loading is very easy: Loading & querying 26m rows of data with takes ~10 min (maybe we could combine-tune the first two steps ..) load from csv/disk — 35 sec insert to DB — 8 min add indexes — 30 sec group by query — 20 sec You can also use sqlite3 command line to test and view query execution plans as seen below. Our target query takes about 21 seconds to execute after adding a few extra indexes on the join columns. Using a SQL DB is scalable but old school. We’ll try hipster techniques next. We can scrap the DB overhead and write the data loads and joins directly & tediously in Python: “merge()” is a Nested Loop join without indexes. The loop has to scan the metas and links table for every rating (26m * 50k *2). With 100k reviews, it takes 5min, so 26m reviews will take forever... “merge_wmap()” is a Hash join — we build a map for metas and links resulting in O(n*1) performance. Joining 26m rows takes just 3 sec! I did not implement the group-by-filter — it would be relatively fast (requires a sort-scan-combine of the 26m row results) — I estimate total time to load and process ~ 0:53 raw CSV loading to arrays — 35 sec manual merge with indexes — 3 sec manual group-by & filter — 15 sec (TBD ~ estimate) Raw Python is fast but ugly. Full speed of your local PC and full control of all your bugs. Pandas[2] is the defacto package on Python for data prep. Extremely fast and easy to use, we can do load, join and group with minimal code: Pandas is clever. You do not need to pre-define hashes or indexes, it appears to generate what's needed on the fly to optimize joins. The biggest limit is its existence on a single machine. Processing 26m rows done in ~0:17, with less code and no external systems (DB, Cluster, etc). loading 3 csv to DataFrames — 5 seconds joining 3 DataFrames — 8 seconds join, group by and filter — +4 seconds Pandas file load is way faster than my custom py~ 35sec vs 5sec ! Goes to show don’t be a hack, use libraries. Pandas is, in theory, its single threaded/process (doesn’t seem like it on my TaskManager) thus the dataset size is limited by your PC’s memory. Nonetheless — Pandas is the ultimate way to work on small/medium data — but we want BIG DATA! SQL is great but limited parallelization and ability to hack with. Python and Pandas are super flexible but lack scalability. Apache Spark [5] is the defacto way to parallelize in-memory operations on big data. Spark has an object called a DataFrame (yes another!) which is just like a Pandas DataFrame and can even load/steal data from it (though you should probably load data via HDFS or the Cloud to avoid BIG data transfer issues): I wrote two Spark join methods. Both run in parallel. The default mode (line 15) will partition your data and shuffle (spread) it around the cluster nodes. The latter “broadcast” mode (line 18) replicates the smaller tables once and only partitions and sends the large table contents. Broadcast mode can be much faster with smaller join tables. Spark divides work across workers nodes (JVMs — set to 8 to match my # of CPU cores) — to divide and conquer back into an aggregation. Spark code and result output below: df.groupBy('title').agg(func.mean('rating'). alias('avg_rating'),func.count('rating'). alias('r_count')).filter('r_count >2'). filter('avg_rating > 4.5').show() (Non-lab certified results from my laptop) First off note the run times to join 3 datasets together: Surprising that a raw Python solution is the fastest? Hack hack! The final results of top movies groups (includes Spark): Pandas is remarkable fast and efficient, up the point that you have core memory. At some point, Python/Pandas will run out of memory and crash. Spark is a good scaling solution, albeit the cluster management can be tricky. In-memory distributed processing, partitioning jobs & data + a partitioned storage strategy (HDFS or other) is the right direction. RDBMS are reliable but have scaling limits on moving data & processing More on Spark in the next chapters.... Oops, I forgot Dask (native Python clusters) — maybe next time. Above stats collected from my MSFT Surface Laptop 3 — i7/16gb/256gb SSD [0] Full source for test code (not just gists)— DougFoo’s GitHub [1] SQLite Python Guide — Official Python Docs [2] Pandas Guide — 10 minute tutorial [3] Bit older analysis SQLite vs Pandas — Wes McKiney blog [4] Spark Joins DB Deck— DataBricks Presentation [5] Nice Detailed Intro on Spark— TDS Article by A. Ialenti [6] PYArrow for fast DataFrame loads in Spark — Bryan Cutler IBM [7] Install PySpark Win in 10min — TDS Article by Uma G [8] Movie Review Files — Kaggle Datasets
[ { "code": null, "e": 269, "s": 172, "text": "There are many ways to spin a disk, filet a fish, or work with Big Data — here is a quick guide." }, { "code": null, "e": 363, "s": 269, "text": "Kaggle Movies Database [8] — 26 million ratings for 45,000 movies, data split across 5 files:" }, { "code": null, "e": 453, "s": 363, "text": "To find the top average ratings for movies you need to join links to metadata to ratings:" }, { "code": null, "e": 652, "s": 453, "text": "SELECT m.title, avg(r.rating) FROM links l INNER JOIN to metas m ON m.imdbId=l.imdbId INNER JOIN to ratings ON r.movieId=l.movieId GROUP BY m.title HAVING count(r.rating) > 2 and avg(r.rating) > 4.5" }, { "code": null, "e": 766, "s": 652, "text": "The classic way is to load up a Database, indexing and run the SQL mentioned before (or using classic SQL below):" }, { "code": null, "e": 945, "s": 766, "text": "SELECT m.title, avg(r.rating) FROM links l, metas m, ratings r WHERE m.imdbId=l.imdbId and r.movieId=l.movieId GROUP BY m.title HAVING count(r.rating) > 2 and avg(r.rating) > 4.5" }, { "code": null, "e": 1014, "s": 945, "text": "Joins in RDBMS are done in 3 major ways with some platform variants:" }, { "code": null, "e": 1402, "s": 1014, "text": "Nested Loops —for each row of Table A lookup the matching key in Table B. An index on B makes the lookup O(A*log B), otherwise the join is SLOW — O(A*B).Hash-Join — build a hash/map of Table B by lookup key, making the join lookup very fast — O(A*1)Merge-Sort — sort both tables and merge on a single pass, not super fast unless pre-sorted — O(A+B+A log A+B log B) → O(A log A + B log B)" }, { "code": null, "e": 1556, "s": 1402, "text": "Nested Loops —for each row of Table A lookup the matching key in Table B. An index on B makes the lookup O(A*log B), otherwise the join is SLOW — O(A*B)." }, { "code": null, "e": 1653, "s": 1556, "text": "Hash-Join — build a hash/map of Table B by lookup key, making the join lookup very fast — O(A*1)" }, { "code": null, "e": 1792, "s": 1653, "text": "Merge-Sort — sort both tables and merge on a single pass, not super fast unless pre-sorted — O(A+B+A log A+B log B) → O(A log A + B log B)" }, { "code": null, "e": 1865, "s": 1792, "text": "Using Sqlite3 [1]— creating a database, tables and loading is very easy:" }, { "code": null, "e": 1973, "s": 1865, "text": "Loading & querying 26m rows of data with takes ~10 min (maybe we could combine-tune the first two steps ..)" }, { "code": null, "e": 2001, "s": 1973, "text": "load from csv/disk — 35 sec" }, { "code": null, "e": 2022, "s": 2001, "text": "insert to DB — 8 min" }, { "code": null, "e": 2043, "s": 2022, "text": "add indexes — 30 sec" }, { "code": null, "e": 2067, "s": 2043, "text": "group by query — 20 sec" }, { "code": null, "e": 2264, "s": 2067, "text": "You can also use sqlite3 command line to test and view query execution plans as seen below. Our target query takes about 21 seconds to execute after adding a few extra indexes on the join columns." }, { "code": null, "e": 2342, "s": 2264, "text": "Using a SQL DB is scalable but old school. We’ll try hipster techniques next." }, { "code": null, "e": 2438, "s": 2342, "text": "We can scrap the DB overhead and write the data loads and joins directly & tediously in Python:" }, { "code": null, "e": 2637, "s": 2438, "text": "“merge()” is a Nested Loop join without indexes. The loop has to scan the metas and links table for every rating (26m * 50k *2). With 100k reviews, it takes 5min, so 26m reviews will take forever..." }, { "code": null, "e": 2772, "s": 2637, "text": "“merge_wmap()” is a Hash join — we build a map for metas and links resulting in O(n*1) performance. Joining 26m rows takes just 3 sec!" }, { "code": null, "e": 2947, "s": 2772, "text": "I did not implement the group-by-filter — it would be relatively fast (requires a sort-scan-combine of the 26m row results) — I estimate total time to load and process ~ 0:53" }, { "code": null, "e": 2982, "s": 2947, "text": "raw CSV loading to arrays — 35 sec" }, { "code": null, "e": 3016, "s": 2982, "text": "manual merge with indexes — 3 sec" }, { "code": null, "e": 3067, "s": 3016, "text": "manual group-by & filter — 15 sec (TBD ~ estimate)" }, { "code": null, "e": 3159, "s": 3067, "text": "Raw Python is fast but ugly. Full speed of your local PC and full control of all your bugs." }, { "code": null, "e": 3299, "s": 3159, "text": "Pandas[2] is the defacto package on Python for data prep. Extremely fast and easy to use, we can do load, join and group with minimal code:" }, { "code": null, "e": 3583, "s": 3299, "text": "Pandas is clever. You do not need to pre-define hashes or indexes, it appears to generate what's needed on the fly to optimize joins. The biggest limit is its existence on a single machine. Processing 26m rows done in ~0:17, with less code and no external systems (DB, Cluster, etc)." }, { "code": null, "e": 3623, "s": 3583, "text": "loading 3 csv to DataFrames — 5 seconds" }, { "code": null, "e": 3656, "s": 3623, "text": "joining 3 DataFrames — 8 seconds" }, { "code": null, "e": 3695, "s": 3656, "text": "join, group by and filter — +4 seconds" }, { "code": null, "e": 3951, "s": 3695, "text": "Pandas file load is way faster than my custom py~ 35sec vs 5sec ! Goes to show don’t be a hack, use libraries. Pandas is, in theory, its single threaded/process (doesn’t seem like it on my TaskManager) thus the dataset size is limited by your PC’s memory." }, { "code": null, "e": 4045, "s": 3951, "text": "Nonetheless — Pandas is the ultimate way to work on small/medium data — but we want BIG DATA!" }, { "code": null, "e": 4256, "s": 4045, "text": "SQL is great but limited parallelization and ability to hack with. Python and Pandas are super flexible but lack scalability. Apache Spark [5] is the defacto way to parallelize in-memory operations on big data." }, { "code": null, "e": 4481, "s": 4256, "text": "Spark has an object called a DataFrame (yes another!) which is just like a Pandas DataFrame and can even load/steal data from it (though you should probably load data via HDFS or the Cloud to avoid BIG data transfer issues):" }, { "code": null, "e": 4826, "s": 4481, "text": "I wrote two Spark join methods. Both run in parallel. The default mode (line 15) will partition your data and shuffle (spread) it around the cluster nodes. The latter “broadcast” mode (line 18) replicates the smaller tables once and only partitions and sends the large table contents. Broadcast mode can be much faster with smaller join tables." }, { "code": null, "e": 4997, "s": 4826, "text": "Spark divides work across workers nodes (JVMs — set to 8 to match my # of CPU cores) — to divide and conquer back into an aggregation. Spark code and result output below:" }, { "code": null, "e": 5177, "s": 4997, "text": "df.groupBy('title').agg(func.mean('rating'). alias('avg_rating'),func.count('rating'). alias('r_count')).filter('r_count >2'). filter('avg_rating > 4.5').show()" }, { "code": null, "e": 5220, "s": 5177, "text": "(Non-lab certified results from my laptop)" }, { "code": null, "e": 5278, "s": 5220, "text": "First off note the run times to join 3 datasets together:" }, { "code": null, "e": 5343, "s": 5278, "text": "Surprising that a raw Python solution is the fastest? Hack hack!" }, { "code": null, "e": 5400, "s": 5343, "text": "The final results of top movies groups (includes Spark):" }, { "code": null, "e": 5544, "s": 5400, "text": "Pandas is remarkable fast and efficient, up the point that you have core memory. At some point, Python/Pandas will run out of memory and crash." }, { "code": null, "e": 5755, "s": 5544, "text": "Spark is a good scaling solution, albeit the cluster management can be tricky. In-memory distributed processing, partitioning jobs & data + a partitioned storage strategy (HDFS or other) is the right direction." }, { "code": null, "e": 5826, "s": 5755, "text": "RDBMS are reliable but have scaling limits on moving data & processing" }, { "code": null, "e": 5929, "s": 5826, "text": "More on Spark in the next chapters.... Oops, I forgot Dask (native Python clusters) — maybe next time." }, { "code": null, "e": 6001, "s": 5929, "text": "Above stats collected from my MSFT Surface Laptop 3 — i7/16gb/256gb SSD" }, { "code": null, "e": 6066, "s": 6001, "text": "[0] Full source for test code (not just gists)— DougFoo’s GitHub" }, { "code": null, "e": 6113, "s": 6066, "text": "[1] SQLite Python Guide — Official Python Docs" }, { "code": null, "e": 6151, "s": 6113, "text": "[2] Pandas Guide — 10 minute tutorial" }, { "code": null, "e": 6210, "s": 6151, "text": "[3] Bit older analysis SQLite vs Pandas — Wes McKiney blog" }, { "code": null, "e": 6259, "s": 6210, "text": "[4] Spark Joins DB Deck— DataBricks Presentation" }, { "code": null, "e": 6319, "s": 6259, "text": "[5] Nice Detailed Intro on Spark— TDS Article by A. Ialenti" }, { "code": null, "e": 6384, "s": 6319, "text": "[6] PYArrow for fast DataFrame loads in Spark — Bryan Cutler IBM" }, { "code": null, "e": 6440, "s": 6384, "text": "[7] Install PySpark Win in 10min — TDS Article by Uma G" } ]
Calendar getTime() Method in Java with Examples - GeeksforGeeks
24 Jun, 2021 The getTime() method in Calendar class is used to return an object resembling the Date that is represented by this Calendar’s time value.Syntax: public final Date getTime() Parameters: The method does not take any parameters.Return Value: The method returns the Date, represented by this Calendar.Below programs illustrate the working of getTime() Method of Calendar class: Example 1: Java // Java code to illustrate// getTime() method import java.util.*; public class Calendar_Demo { public static void main(String args[]) throws InterruptedException { // Creating a calendar Calendar calndr1 = Calendar.getInstance(); // Displaying the current time System.out.println("The Current" + " Time is: " + calndr1.getTime()); // Adding few delay Thread.sleep(10000); // Creating another calendar Calendar calndr2 = Calendar.getInstance(); // Displaying the upcoming time Date dt = calndr2.getTime(); System.out.println("The upcoming" + " time is: " + dt); }} The Current Time is: Wed Feb 20 14:40:37 UTC 2019 The upcoming time is: Wed Feb 20 14:40:47 UTC 2019 Example 2: Java // Java code to illustrate// getTime() method import java.util.*; public class Calendar_Demo { public static void main(String args[]) throws InterruptedException { // Creating a calendar Calendar calndr1 = Calendar.getInstance(); // Displaying the current time System.out.println("The Current" + " Time is: " + calndr1.getTime()); // Adding few delay Thread.sleep(5000); // Creating another calendar Calendar calndr2 = Calendar.getInstance(); // Displaying the upcoming time Date dt = calndr2.getTime(); System.out.println("The upcoming" + " time is: " + dt); }} The Current Time is: Wed Feb 20 14:40:50 UTC 2019 The upcoming time is: Wed Feb 20 14:40:55 UTC 2019 Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#getMaximum-int- adnanirshad158 Java - util package Java-Calendar Java-Functions Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples How to iterate any Map in Java Initialize an ArrayList in Java Interfaces in Java ArrayList in Java Multidimensional Arrays in Java Stack Class in Java Singleton Class in Java Collections in Java
[ { "code": null, "e": 24121, "s": 24093, "text": "\n24 Jun, 2021" }, { "code": null, "e": 24268, "s": 24121, "text": "The getTime() method in Calendar class is used to return an object resembling the Date that is represented by this Calendar’s time value.Syntax: " }, { "code": null, "e": 24296, "s": 24268, "text": "public final Date getTime()" }, { "code": null, "e": 24510, "s": 24296, "text": "Parameters: The method does not take any parameters.Return Value: The method returns the Date, represented by this Calendar.Below programs illustrate the working of getTime() Method of Calendar class: Example 1: " }, { "code": null, "e": 24515, "s": 24510, "text": "Java" }, { "code": "// Java code to illustrate// getTime() method import java.util.*; public class Calendar_Demo { public static void main(String args[]) throws InterruptedException { // Creating a calendar Calendar calndr1 = Calendar.getInstance(); // Displaying the current time System.out.println(\"The Current\" + \" Time is: \" + calndr1.getTime()); // Adding few delay Thread.sleep(10000); // Creating another calendar Calendar calndr2 = Calendar.getInstance(); // Displaying the upcoming time Date dt = calndr2.getTime(); System.out.println(\"The upcoming\" + \" time is: \" + dt); }}", "e": 25267, "s": 24515, "text": null }, { "code": null, "e": 25368, "s": 25267, "text": "The Current Time is: Wed Feb 20 14:40:37 UTC 2019\nThe upcoming time is: Wed Feb 20 14:40:47 UTC 2019" }, { "code": null, "e": 25383, "s": 25370, "text": "Example 2: " }, { "code": null, "e": 25388, "s": 25383, "text": "Java" }, { "code": "// Java code to illustrate// getTime() method import java.util.*; public class Calendar_Demo { public static void main(String args[]) throws InterruptedException { // Creating a calendar Calendar calndr1 = Calendar.getInstance(); // Displaying the current time System.out.println(\"The Current\" + \" Time is: \" + calndr1.getTime()); // Adding few delay Thread.sleep(5000); // Creating another calendar Calendar calndr2 = Calendar.getInstance(); // Displaying the upcoming time Date dt = calndr2.getTime(); System.out.println(\"The upcoming\" + \" time is: \" + dt); }}", "e": 26139, "s": 25388, "text": null }, { "code": null, "e": 26240, "s": 26139, "text": "The Current Time is: Wed Feb 20 14:40:50 UTC 2019\nThe upcoming time is: Wed Feb 20 14:40:55 UTC 2019" }, { "code": null, "e": 26336, "s": 26242, "text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#getMaximum-int- " }, { "code": null, "e": 26351, "s": 26336, "text": "adnanirshad158" }, { "code": null, "e": 26371, "s": 26351, "text": "Java - util package" }, { "code": null, "e": 26385, "s": 26371, "text": "Java-Calendar" }, { "code": null, "e": 26400, "s": 26385, "text": "Java-Functions" }, { "code": null, "e": 26405, "s": 26400, "text": "Java" }, { "code": null, "e": 26410, "s": 26405, "text": "Java" }, { "code": null, "e": 26508, "s": 26410, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26517, "s": 26508, "text": "Comments" }, { "code": null, "e": 26530, "s": 26517, "text": "Old Comments" }, { "code": null, "e": 26581, "s": 26530, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 26611, "s": 26581, "text": "HashMap in Java with Examples" }, { "code": null, "e": 26642, "s": 26611, "text": "How to iterate any Map in Java" }, { "code": null, "e": 26674, "s": 26642, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 26693, "s": 26674, "text": "Interfaces in Java" }, { "code": null, "e": 26711, "s": 26693, "text": "ArrayList in Java" }, { "code": null, "e": 26743, "s": 26711, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 26763, "s": 26743, "text": "Stack Class in Java" }, { "code": null, "e": 26787, "s": 26763, "text": "Singleton Class in Java" } ]
How to delete all elements from arraylist for listview in Android?
This example demonstrate about How to delete all elements from arraylist for listview in Android Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" android:orientation = "vertical"> <EditText android:id = "@+id/name" android:layout_width = "match_parent" android:hint = "Enter Name" android:layout_height = "wrap_content" /> <LinearLayout android:layout_width = "wrap_content" android:layout_height = "wrap_content"> <Button android:id = "@+id/save" android:text = "Save" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> <Button android:id = "@+id/refresh" android:text = "Refresh" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> <Button android:id = "@+id/delete" android:text = "Delete" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> <Button android:id = "@+id/deleteall" android:text = "Delete ALL" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> </LinearLayout> <ListView android:id = "@+id/listView" android:layout_width = "match_parent" android:layout_height = "wrap_content"> </ListView> </LinearLayout> In the above code, we have taken name as Edit text, when user click on save button it will store the data into arraylist. Click on delete all button to delete all elements for listview. Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { Button save, refresh; EditText name; ArrayAdapter arrayAdapter; private ListView listView; ArrayList array_list; @Override protected void onCreate(Bundle readdInstanceState) { super.onCreate(readdInstanceState); setContentView(R.layout.activity_main); array_list = new ArrayList(); name = findViewById(R.id.name); listView = findViewById(R.id.listView); findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { arrayAdapter.notifyDataSetChanged(); listView.invalidateViews(); listView.refreshDrawableState(); } }); findViewById(R.id.deleteall).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(array_list.size()>0) { if (!name.getText().toString().isEmpty()) { array_list.clear(); arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, array_list); listView.setAdapter(arrayAdapter); Toast.makeText(MainActivity.this, "deleted all", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(MainActivity.this, "There is no element to delete", Toast.LENGTH_LONG).show(); } } }); findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(array_list.size()>0) { if (!name.getText().toString().isEmpty()) { array_list.remove(name.getText().toString()); arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, array_list); listView.setAdapter(arrayAdapter); Toast.makeText(MainActivity.this, "deleted", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(MainActivity.this, "There is no element to delete", Toast.LENGTH_LONG).show(); } } }); findViewById(R.id.save).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!name.getText().toString().isEmpty()) { array_list.add(name.getText().toString()); arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, array_list); listView.setAdapter(arrayAdapter); Toast.makeText(MainActivity.this, "Inserted", Toast.LENGTH_LONG).show(); } else { name.setError("Enter NAME"); } } }); } } Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – In the above result, we are inserting name into arraylist and displaying name in list view. Now click on delete all button to delete listview items Click here to download the project code
[ { "code": null, "e": 1159, "s": 1062, "text": "This example demonstrate about How to delete all elements from arraylist for listview in Android" }, { "code": null, "e": 1288, "s": 1159, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1353, "s": 1288, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2869, "s": 1353, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\nxmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:orientation = \"vertical\">\n <EditText\n android:id = \"@+id/name\"\n android:layout_width = \"match_parent\"\n android:hint = \"Enter Name\"\n android:layout_height = \"wrap_content\" />\n <LinearLayout\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\">\n <Button\n android:id = \"@+id/save\"\n android:text = \"Save\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n <Button\n android:id = \"@+id/refresh\"\n android:text = \"Refresh\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n <Button\n android:id = \"@+id/delete\"\n android:text = \"Delete\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n <Button\n android:id = \"@+id/deleteall\"\n android:text = \"Delete ALL\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n </LinearLayout>\n <ListView\n android:id = \"@+id/listView\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\">\n </ListView>\n</LinearLayout>" }, { "code": null, "e": 3055, "s": 2869, "text": "In the above code, we have taken name as Edit text, when user click on save button it will store the data into arraylist. Click on delete all button to delete all elements for listview." }, { "code": null, "e": 3112, "s": 3055, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 6271, "s": 3112, "text": "package com.example.andy.myapplication;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.ListView;\nimport android.widget.Toast;\nimport java.util.ArrayList;\npublic class MainActivity extends AppCompatActivity {\n Button save, refresh;\n EditText name;\n ArrayAdapter arrayAdapter;\n private ListView listView;\n ArrayList array_list;\n @Override\n protected void onCreate(Bundle readdInstanceState) {\n super.onCreate(readdInstanceState);\n setContentView(R.layout.activity_main);\n array_list = new ArrayList();\n name = findViewById(R.id.name);\n listView = findViewById(R.id.listView);\n findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n arrayAdapter.notifyDataSetChanged();\n listView.invalidateViews();\n listView.refreshDrawableState();\n }\n });\n findViewById(R.id.deleteall).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if(array_list.size()>0) {\n if (!name.getText().toString().isEmpty()) {\n array_list.clear();\n arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, array_list);\n listView.setAdapter(arrayAdapter);\n Toast.makeText(MainActivity.this, \"deleted all\", Toast.LENGTH_LONG).show();\n }\n } else {\n Toast.makeText(MainActivity.this, \"There is no element to delete\", Toast.LENGTH_LONG).show();\n }\n }\n });\n findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if(array_list.size()>0) {\n if (!name.getText().toString().isEmpty()) {\n array_list.remove(name.getText().toString());\n arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, array_list);\n listView.setAdapter(arrayAdapter);\n Toast.makeText(MainActivity.this, \"deleted\", Toast.LENGTH_LONG).show();\n }\n } else {\n Toast.makeText(MainActivity.this, \"There is no element to delete\", Toast.LENGTH_LONG).show();\n }\n }\n });\n findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!name.getText().toString().isEmpty()) {\n array_list.add(name.getText().toString());\n arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, array_list);\n listView.setAdapter(arrayAdapter);\n Toast.makeText(MainActivity.this, \"Inserted\", Toast.LENGTH_LONG).show();\n } else {\n name.setError(\"Enter NAME\");\n }\n }\n });\n }\n}" }, { "code": null, "e": 6618, "s": 6271, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 6766, "s": 6618, "text": "In the above result, we are inserting name into arraylist and displaying name in list view. Now click on delete all button to delete listview items" }, { "code": null, "e": 6808, "s": 6766, "text": "Click here to download the project code" } ]
How to Maximize window in chrome using webDriver (Python)?
We can maximize windows on Chrome with a webdriver. While working on any automated test cases, if the browser opens in maximized mode then the probability of the scripts getting failed lessens. This is because if the element is visible, then the chances of its interaction increases. Also, if the window is maximized, then the testers or developers working on them gets a better visibility of the test steps. Some of the applications open in maximized mode automatically. Applying maximizing techniques on them does not have any impact on them. Let us see the methods with which we can maximize window in chrome in python − Using maximize_window() method. Using maximize_window() method. Using fullscreen_window() method. Using fullscreen_window() method. Code Implementation with maximize_window(). from selenium import webdriver driver = webdriver.Chrome (executable_path="C:\\chromedriver.exe") # maximize with maximize_window() driver.maximize_window() driver.get("https://www.tutorialspoint.com/index.htm") driver.quit() Code Implementation with fullscreen_window(). from selenium import webdriver driver = webdriver.Chrome (executable_path="C:\\chromedriver.exe") # maximize with maximize_window() driver.fullscreen_window() driver.get("https://www.tutorialspoint.com/index.htm") driver.quit() So in the above code implementations we have done the following steps − Launched the Chrome browser. Launched the Chrome browser. Opened an URL. Opened an URL. Maximized the Chrome browser. Maximized the Chrome browser. Quitted the driver session. Quitted the driver session.
[ { "code": null, "e": 1256, "s": 1062, "text": "We can maximize windows on Chrome with a webdriver. While working on any automated test cases, if the browser opens in maximized mode then the probability of the scripts getting failed lessens." }, { "code": null, "e": 1471, "s": 1256, "text": "This is because if the element is visible, then the chances of its interaction increases. Also, if the window is maximized, then the testers or developers working on them gets a better visibility of the test steps." }, { "code": null, "e": 1686, "s": 1471, "text": "Some of the applications open in maximized mode automatically. Applying maximizing techniques on them does not have any impact on them. Let us see the methods with which we can maximize window in chrome in python −" }, { "code": null, "e": 1718, "s": 1686, "text": "Using maximize_window() method." }, { "code": null, "e": 1750, "s": 1718, "text": "Using maximize_window() method." }, { "code": null, "e": 1784, "s": 1750, "text": "Using fullscreen_window() method." }, { "code": null, "e": 1818, "s": 1784, "text": "Using fullscreen_window() method." }, { "code": null, "e": 1862, "s": 1818, "text": "Code Implementation with maximize_window()." }, { "code": null, "e": 2088, "s": 1862, "text": "from selenium import webdriver\ndriver = webdriver.Chrome (executable_path=\"C:\\\\chromedriver.exe\")\n# maximize with maximize_window()\ndriver.maximize_window()\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\ndriver.quit()" }, { "code": null, "e": 2134, "s": 2088, "text": "Code Implementation with fullscreen_window()." }, { "code": null, "e": 2362, "s": 2134, "text": "from selenium import webdriver\ndriver = webdriver.Chrome (executable_path=\"C:\\\\chromedriver.exe\")\n# maximize with maximize_window()\ndriver.fullscreen_window()\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\ndriver.quit()" }, { "code": null, "e": 2434, "s": 2362, "text": "So in the above code implementations we have done the following steps −" }, { "code": null, "e": 2463, "s": 2434, "text": "Launched the Chrome browser." }, { "code": null, "e": 2492, "s": 2463, "text": "Launched the Chrome browser." }, { "code": null, "e": 2507, "s": 2492, "text": "Opened an URL." }, { "code": null, "e": 2522, "s": 2507, "text": "Opened an URL." }, { "code": null, "e": 2552, "s": 2522, "text": "Maximized the Chrome browser." }, { "code": null, "e": 2582, "s": 2552, "text": "Maximized the Chrome browser." }, { "code": null, "e": 2610, "s": 2582, "text": "Quitted the driver session." }, { "code": null, "e": 2638, "s": 2610, "text": "Quitted the driver session." } ]
Redis - Environment
In this chapter, you will learn about the environmental setup for Redis. To install Redis on Ubuntu, go to the terminal and type the following commands − $sudo apt-get update $sudo apt-get install redis-server This will install Redis on your machine. $redis-server $redis-cli This will open a redis prompt. redis 127.0.0.1:6379> In the above prompt, 127.0.0.1 is your machine's IP address and 6379 is the port on which Redis server is running. Now type the following PING command. redis 127.0.0.1:6379> ping PONG This shows that Redis is successfully installed on your machine. To install Redis desktop manager on Ubuntu, just download the package from https://redisdesktop.com/download Open the downloaded package and install it. Redis desktop manager will give you UI to manage your Redis keys and data. 22 Lectures 40 mins Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2118, "s": 2045, "text": "In this chapter, you will learn about the environmental setup for Redis." }, { "code": null, "e": 2199, "s": 2118, "text": "To install Redis on Ubuntu, go to the terminal and type the following commands −" }, { "code": null, "e": 2257, "s": 2199, "text": "$sudo apt-get update \n$sudo apt-get install redis-server\n" }, { "code": null, "e": 2298, "s": 2257, "text": "This will install Redis on your machine." }, { "code": null, "e": 2313, "s": 2298, "text": "$redis-server\n" }, { "code": null, "e": 2326, "s": 2313, "text": "$redis-cli \n" }, { "code": null, "e": 2357, "s": 2326, "text": "This will open a redis prompt." }, { "code": null, "e": 2380, "s": 2357, "text": "redis 127.0.0.1:6379>\n" }, { "code": null, "e": 2532, "s": 2380, "text": "In the above prompt, 127.0.0.1 is your machine's IP address and 6379 is the port on which Redis server is running. Now type the following PING command." }, { "code": null, "e": 2566, "s": 2532, "text": "redis 127.0.0.1:6379> ping \nPONG\n" }, { "code": null, "e": 2631, "s": 2566, "text": "This shows that Redis is successfully installed on your machine." }, { "code": null, "e": 2740, "s": 2631, "text": "To install Redis desktop manager on Ubuntu, just download the package from https://redisdesktop.com/download" }, { "code": null, "e": 2784, "s": 2740, "text": "Open the downloaded package and install it." }, { "code": null, "e": 2859, "s": 2784, "text": "Redis desktop manager will give you UI to manage your Redis keys and data." }, { "code": null, "e": 2891, "s": 2859, "text": "\n 22 Lectures \n 40 mins\n" }, { "code": null, "e": 2911, "s": 2891, "text": " Skillbakerystudios" }, { "code": null, "e": 2918, "s": 2911, "text": " Print" }, { "code": null, "e": 2929, "s": 2918, "text": " Add Notes" } ]
Scikit Learn - Clustering Performance Evaluation
There are various functions with the help of which we can evaluate the performance of clustering algorithms. Following are some important and mostly used functions given by the Scikit-learn for evaluating clustering performance − Rand Index is a function that computes a similarity measure between two clustering. For this computation rand index considers all pairs of samples and counting pairs that are assigned in the similar or different clusters in the predicted and true clustering. Afterwards, the raw Rand Index score is ‘adjusted for chance’ into the Adjusted Rand Index score by using the following formula − It has two parameters namely labels_true, which is ground truth class labels, and labels_pred, which are clusters label to evaluate. from sklearn.metrics.cluster import adjusted_rand_score labels_true = [0, 0, 1, 1, 1, 1] labels_pred = [0, 0, 2, 2, 3, 3] adjusted_rand_score(labels_true, labels_pred) 0.4444444444444445 Perfect labeling would be scored 1 and bad labelling or independent labelling is scored 0 or negative. Mutual Information is a function that computes the agreement of the two assignments. It ignores the permutations. There are following versions available − Scikit learn have sklearn.metrics.normalized_mutual_info_score module. from sklearn.metrics.cluster import normalized_mutual_info_score labels_true = [0, 0, 1, 1, 1, 1] labels_pred = [0, 0, 2, 2, 3, 3] normalized_mutual_info_score (labels_true, labels_pred) 0.7611702597222881 Scikit learn have sklearn.metrics.adjusted_mutual_info_score module. from sklearn.metrics.cluster import adjusted_mutual_info_score labels_true = [0, 0, 1, 1, 1, 1] labels_pred = [0, 0, 2, 2, 3, 3] adjusted_mutual_info_score (labels_true, labels_pred) 0.4444444444444448 The Fowlkes-Mallows function measures the similarity of two clustering of a set of points. It may be defined as the geometric mean of the pairwise precision and recall. Mathematically, Here, TP = True Positive − number of pair of points belonging to the same clusters in true as well as predicted labels both. FP = False Positive − number of pair of points belonging to the same clusters in true labels but not in the predicted labels. FN = False Negative − number of pair of points belonging to the same clusters in the predicted labels but not in the true labels. The Scikit learn has sklearn.metrics.fowlkes_mallows_score module − from sklearn.metrics.cluster import fowlkes_mallows_score labels_true = [0, 0, 1, 1, 1, 1] labels_pred = [0, 0, 2, 2, 3, 3] fowlkes_mallows__score (labels_true, labels_pred) 0.6546536707079771 The Silhouette function will compute the mean Silhouette Coefficient of all samples using the mean intra-cluster distance and the mean nearest-cluster distance for each sample. Mathematically, Here, a is intra-cluster distance. and, b is mean nearest-cluster distance. The Scikit learn have sklearn.metrics.silhouette_score module − from sklearn import metrics.silhouette_score from sklearn.metrics import pairwise_distances from sklearn import datasets import numpy as np from sklearn.cluster import KMeans dataset = datasets.load_iris() X = dataset.data y = dataset.target kmeans_model = KMeans(n_clusters = 3, random_state = 1).fit(X) labels = kmeans_model.labels_ silhouette_score(X, labels, metric = 'euclidean') 0.5528190123564091 This matrix will report the intersection cardinality for every trusted pair of (true, predicted). Confusion matrix for classification problems is a square contingency matrix. The Scikit learn have sklearn.metrics.contingency_matrix module. from sklearn.metrics.cluster import contingency_matrix x = ["a", "a", "a", "b", "b", "b"] y = [1, 1, 2, 0, 1, 2] contingency_matrix(x, y) array([ [0, 2, 1], [1, 1, 1] ]) The first row of above output shows that among three samples whose true cluster is “a”, none of them is in 0, two of the are in 1 and 1 is in 2. On the other hand, second row shows that among three samples whose true cluster is “b”, 1 is in 0, 1 is in 1 and 1 is in 2. 11 Lectures 2 hours PARTHA MAJUMDAR Print Add Notes Bookmark this page
[ { "code": null, "e": 2330, "s": 2221, "text": "There are various functions with the help of which we can evaluate the performance of clustering algorithms." }, { "code": null, "e": 2451, "s": 2330, "text": "Following are some important and mostly used functions given by the Scikit-learn for evaluating clustering performance −" }, { "code": null, "e": 2840, "s": 2451, "text": "Rand Index is a function that computes a similarity measure between two clustering. For this computation rand index considers all pairs of samples and counting pairs that are assigned in the similar or different clusters in the predicted and true clustering. Afterwards, the raw Rand Index score is ‘adjusted for chance’ into the Adjusted Rand Index score by using the following formula −" }, { "code": null, "e": 2973, "s": 2840, "text": "It has two parameters namely labels_true, which is ground truth class labels, and labels_pred, which are clusters label to evaluate." }, { "code": null, "e": 3152, "s": 2973, "text": "from sklearn.metrics.cluster import adjusted_rand_score\n \n labels_true = [0, 0, 1, 1, 1, 1]\n labels_pred = [0, 0, 2, 2, 3, 3]\n\nadjusted_rand_score(labels_true, labels_pred)" }, { "code": null, "e": 3172, "s": 3152, "text": "0.4444444444444445\n" }, { "code": null, "e": 3275, "s": 3172, "text": "Perfect labeling would be scored 1 and bad labelling or independent labelling is scored 0 or negative." }, { "code": null, "e": 3430, "s": 3275, "text": "Mutual Information is a function that computes the agreement of the two assignments. It ignores the permutations. There are following versions available −" }, { "code": null, "e": 3501, "s": 3430, "text": "Scikit learn have sklearn.metrics.normalized_mutual_info_score module." }, { "code": null, "e": 3699, "s": 3501, "text": "from sklearn.metrics.cluster import normalized_mutual_info_score\n \n labels_true = [0, 0, 1, 1, 1, 1]\n labels_pred = [0, 0, 2, 2, 3, 3]\n\nnormalized_mutual_info_score (labels_true, labels_pred)" }, { "code": null, "e": 3719, "s": 3699, "text": "0.7611702597222881\n" }, { "code": null, "e": 3788, "s": 3719, "text": "Scikit learn have sklearn.metrics.adjusted_mutual_info_score module." }, { "code": null, "e": 3979, "s": 3788, "text": "from sklearn.metrics.cluster import adjusted_mutual_info_score\n\n labels_true = [0, 0, 1, 1, 1, 1]\n labels_pred = [0, 0, 2, 2, 3, 3]\n\nadjusted_mutual_info_score (labels_true, labels_pred)" }, { "code": null, "e": 3999, "s": 3979, "text": "0.4444444444444448\n" }, { "code": null, "e": 4168, "s": 3999, "text": "The Fowlkes-Mallows function measures the similarity of two clustering of a set of points. It may be defined as the geometric mean of the pairwise precision and recall." }, { "code": null, "e": 4184, "s": 4168, "text": "Mathematically," }, { "code": null, "e": 4309, "s": 4184, "text": "Here, TP = True Positive − number of pair of points belonging to the same clusters in true as well as predicted labels both." }, { "code": null, "e": 4435, "s": 4309, "text": "FP = False Positive − number of pair of points belonging to the same clusters in true labels but not in the predicted labels." }, { "code": null, "e": 4565, "s": 4435, "text": "FN = False Negative − number of pair of points belonging to the same clusters in the predicted labels but not in the true labels." }, { "code": null, "e": 4633, "s": 4565, "text": "The Scikit learn has sklearn.metrics.fowlkes_mallows_score module −" }, { "code": null, "e": 4815, "s": 4633, "text": "from sklearn.metrics.cluster import fowlkes_mallows_score\n\n labels_true = [0, 0, 1, 1, 1, 1]\n labels_pred = [0, 0, 2, 2, 3, 3]\n\nfowlkes_mallows__score (labels_true, labels_pred)" }, { "code": null, "e": 4835, "s": 4815, "text": "0.6546536707079771\n" }, { "code": null, "e": 5012, "s": 4835, "text": "The Silhouette function will compute the mean Silhouette Coefficient of all samples using the mean intra-cluster distance and the mean nearest-cluster distance for each sample." }, { "code": null, "e": 5028, "s": 5012, "text": "Mathematically," }, { "code": null, "e": 5063, "s": 5028, "text": "Here, a is intra-cluster distance." }, { "code": null, "e": 5104, "s": 5063, "text": "and, b is mean nearest-cluster distance." }, { "code": null, "e": 5168, "s": 5104, "text": "The Scikit learn have sklearn.metrics.silhouette_score module −" }, { "code": null, "e": 5554, "s": 5168, "text": "from sklearn import metrics.silhouette_score\nfrom sklearn.metrics import pairwise_distances\nfrom sklearn import datasets\nimport numpy as np\nfrom sklearn.cluster import KMeans\ndataset = datasets.load_iris()\nX = dataset.data\ny = dataset.target\n\nkmeans_model = KMeans(n_clusters = 3, random_state = 1).fit(X)\nlabels = kmeans_model.labels_\nsilhouette_score(X, labels, metric = 'euclidean')" }, { "code": null, "e": 5574, "s": 5554, "text": "0.5528190123564091\n" }, { "code": null, "e": 5749, "s": 5574, "text": "This matrix will report the intersection cardinality for every trusted pair of (true, predicted). Confusion matrix for classification problems is a square contingency matrix." }, { "code": null, "e": 5814, "s": 5749, "text": "The Scikit learn have sklearn.metrics.contingency_matrix module." }, { "code": null, "e": 5952, "s": 5814, "text": "from sklearn.metrics.cluster import contingency_matrix\nx = [\"a\", \"a\", \"a\", \"b\", \"b\", \"b\"]\ny = [1, 1, 2, 0, 1, 2]\ncontingency_matrix(x, y)" }, { "code": null, "e": 5991, "s": 5952, "text": "array([\n [0, 2, 1],\n [1, 1, 1]\n])\n" }, { "code": null, "e": 6260, "s": 5991, "text": "The first row of above output shows that among three samples whose true cluster is “a”, none of them is in 0, two of the are in 1 and 1 is in 2. On the other hand, second row shows that among three samples whose true cluster is “b”, 1 is in 0, 1 is in 1 and 1 is in 2." }, { "code": null, "e": 6293, "s": 6260, "text": "\n 11 Lectures \n 2 hours \n" }, { "code": null, "e": 6310, "s": 6293, "text": " PARTHA MAJUMDAR" }, { "code": null, "e": 6317, "s": 6310, "text": " Print" }, { "code": null, "e": 6328, "s": 6317, "text": " Add Notes" } ]
Properties of Relational Decomposition - GeeksforGeeks
29 Aug, 2019 When a relation in the relational model is not appropriate normal form then the decomposition of a relation is required. In a database, breaking down the table into multiple tables termed as decomposition. The properties of a relational decomposition are listed below : Attribute Preservation:Using functional dependencies the algorithms decompose the universal relation schema R in a set of relation schemas D = { R1, R2, ..... Rn } relational database schema, where ‘D’ is called the Decomposition of R.The attributes in R will appear in at least one relation schema Ri in the decomposition, i.e., no attribute is lost. This is called the Attribute Preservation condition of decomposition.Dependency Preservation:If each functional dependency X->Y specified in F appears directly in one of the relation schemas Ri in the decomposition D or could be inferred from the dependencies that appear in some Ri. This is the Dependency Preservation.If a decomposition is not dependency preserving some dependency is lost in decomposition. To check this condition, take the JOIN of 2 or more relations in the decomposition.For example:R = (A, B, C) F = {A ->B, B->C} Key = {A} R is not in BCNF. Decomposition R1 = (A, B), R2 = (B, C) R1 and R2 are in BCNF, Lossless-join decomposition, Dependency preserving.Each Functional Dependency specified in F either appears directly in one of the relations in the decomposition.It is not necessary that all dependencies from the relation R appear in some relation Ri.It is sufficient that the union of the dependencies on all the relations Ri be equivalent to the dependencies on R.Non Additive Join Property:Another property of decomposition is that D should possess is the Non Additive Join Property, which ensures that no spurious tuples are generated when a NATURAL JOIN operation is applied to the relations resulting from the decomposition.No redundancy:Decomposition is used to eliminate some of the problems of bad design like anomalies, inconsistencies, and redundancy.If the relation has no proper decomposition, then it may lead to problems like loss of information.Lossless Join:Lossless join property is a feature of decomposition supported by normalization. It is the ability to ensure that any instance of the original relation can be identified from corresponding instances in the smaller relations.For example:R : relation, F : set of functional dependencies on R,X, Y : decomposition of R,A decomposition {R1, R2, ..., Rn} of a relation R is called a lossless decomposition for R if the natural join of R1, R2, ..., Rn produces exactly the relation R.A decomposition is lossless if we can recover:R(A, B, C) -> Decompose -> R1(A, B) R2(A, C) -> Recover -> R’(A, B, C)Thus, R’ = RDecomposition is lossless if:X intersection Y -> X, that is: all attributes common to both X and Y functionally determine ALL the attributes in X.X intersection Y -> Y, that is: all attributes common to both X and Y functionally determine ALL the attributes in YIf X intersection Y forms a superkey of either X or Y, the decomposition of R is a lossless decomposition. Attribute Preservation:Using functional dependencies the algorithms decompose the universal relation schema R in a set of relation schemas D = { R1, R2, ..... Rn } relational database schema, where ‘D’ is called the Decomposition of R.The attributes in R will appear in at least one relation schema Ri in the decomposition, i.e., no attribute is lost. This is called the Attribute Preservation condition of decomposition. The attributes in R will appear in at least one relation schema Ri in the decomposition, i.e., no attribute is lost. This is called the Attribute Preservation condition of decomposition. Dependency Preservation:If each functional dependency X->Y specified in F appears directly in one of the relation schemas Ri in the decomposition D or could be inferred from the dependencies that appear in some Ri. This is the Dependency Preservation.If a decomposition is not dependency preserving some dependency is lost in decomposition. To check this condition, take the JOIN of 2 or more relations in the decomposition.For example:R = (A, B, C) F = {A ->B, B->C} Key = {A} R is not in BCNF. Decomposition R1 = (A, B), R2 = (B, C) R1 and R2 are in BCNF, Lossless-join decomposition, Dependency preserving.Each Functional Dependency specified in F either appears directly in one of the relations in the decomposition.It is not necessary that all dependencies from the relation R appear in some relation Ri.It is sufficient that the union of the dependencies on all the relations Ri be equivalent to the dependencies on R. If a decomposition is not dependency preserving some dependency is lost in decomposition. To check this condition, take the JOIN of 2 or more relations in the decomposition. For example: R = (A, B, C) F = {A ->B, B->C} Key = {A} R is not in BCNF. Decomposition R1 = (A, B), R2 = (B, C) R1 and R2 are in BCNF, Lossless-join decomposition, Dependency preserving.Each Functional Dependency specified in F either appears directly in one of the relations in the decomposition.It is not necessary that all dependencies from the relation R appear in some relation Ri.It is sufficient that the union of the dependencies on all the relations Ri be equivalent to the dependencies on R. Non Additive Join Property:Another property of decomposition is that D should possess is the Non Additive Join Property, which ensures that no spurious tuples are generated when a NATURAL JOIN operation is applied to the relations resulting from the decomposition. No redundancy:Decomposition is used to eliminate some of the problems of bad design like anomalies, inconsistencies, and redundancy.If the relation has no proper decomposition, then it may lead to problems like loss of information. Lossless Join:Lossless join property is a feature of decomposition supported by normalization. It is the ability to ensure that any instance of the original relation can be identified from corresponding instances in the smaller relations.For example:R : relation, F : set of functional dependencies on R,X, Y : decomposition of R,A decomposition {R1, R2, ..., Rn} of a relation R is called a lossless decomposition for R if the natural join of R1, R2, ..., Rn produces exactly the relation R.A decomposition is lossless if we can recover:R(A, B, C) -> Decompose -> R1(A, B) R2(A, C) -> Recover -> R’(A, B, C)Thus, R’ = RDecomposition is lossless if:X intersection Y -> X, that is: all attributes common to both X and Y functionally determine ALL the attributes in X.X intersection Y -> Y, that is: all attributes common to both X and Y functionally determine ALL the attributes in YIf X intersection Y forms a superkey of either X or Y, the decomposition of R is a lossless decomposition. For example:R : relation, F : set of functional dependencies on R,X, Y : decomposition of R,A decomposition {R1, R2, ..., Rn} of a relation R is called a lossless decomposition for R if the natural join of R1, R2, ..., Rn produces exactly the relation R. A decomposition is lossless if we can recover:R(A, B, C) -> Decompose -> R1(A, B) R2(A, C) -> Recover -> R’(A, B, C)Thus, R’ = RDecomposition is lossless if:X intersection Y -> X, that is: all attributes common to both X and Y functionally determine ALL the attributes in X.X intersection Y -> Y, that is: all attributes common to both X and Y functionally determine ALL the attributes in YIf X intersection Y forms a superkey of either X or Y, the decomposition of R is a lossless decomposition. DBMS-Normalization DBMS GATE CS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Functional dependencies in DBMS Introduction of Relational Algebra in DBMS What is Temporary Table in SQL? KDD Process in Data Mining Two Phase Locking Protocol Layers of OSI Model Types of Operating Systems TCP/IP Model Page Replacement Algorithms in Operating Systems Differences between TCP and UDP
[ { "code": null, "e": 24330, "s": 24302, "text": "\n29 Aug, 2019" }, { "code": null, "e": 24600, "s": 24330, "text": "When a relation in the relational model is not appropriate normal form then the decomposition of a relation is required. In a database, breaking down the table into multiple tables termed as decomposition. The properties of a relational decomposition are listed below :" }, { "code": null, "e": 27430, "s": 24600, "text": "Attribute Preservation:Using functional dependencies the algorithms decompose the universal relation schema R in a set of relation schemas D = { R1, R2, ..... Rn } relational database schema, where ‘D’ is called the Decomposition of R.The attributes in R will appear in at least one relation schema Ri in the decomposition, i.e., no attribute is lost. This is called the Attribute Preservation condition of decomposition.Dependency Preservation:If each functional dependency X->Y specified in F appears directly in one of the relation schemas Ri in the decomposition D or could be inferred from the dependencies that appear in some Ri. This is the Dependency Preservation.If a decomposition is not dependency preserving some dependency is lost in decomposition. To check this condition, take the JOIN of 2 or more relations in the decomposition.For example:R = (A, B, C)\nF = {A ->B, B->C}\nKey = {A}\n\nR is not in BCNF.\nDecomposition R1 = (A, B), R2 = (B, C) R1 and R2 are in BCNF, Lossless-join decomposition, Dependency preserving.Each Functional Dependency specified in F either appears directly in one of the relations in the decomposition.It is not necessary that all dependencies from the relation R appear in some relation Ri.It is sufficient that the union of the dependencies on all the relations Ri be equivalent to the dependencies on R.Non Additive Join Property:Another property of decomposition is that D should possess is the Non Additive Join Property, which ensures that no spurious tuples are generated when a NATURAL JOIN operation is applied to the relations resulting from the decomposition.No redundancy:Decomposition is used to eliminate some of the problems of bad design like anomalies, inconsistencies, and redundancy.If the relation has no proper decomposition, then it may lead to problems like loss of information.Lossless Join:Lossless join property is a feature of decomposition supported by normalization. It is the ability to ensure that any instance of the original relation can be identified from corresponding instances in the smaller relations.For example:R : relation, F : set of functional dependencies on R,X, Y : decomposition of R,A decomposition {R1, R2, ..., Rn} of a relation R is called a lossless decomposition for R if the natural join of R1, R2, ..., Rn produces exactly the relation R.A decomposition is lossless if we can recover:R(A, B, C) -> Decompose -> R1(A, B) R2(A, C) -> Recover -> R’(A, B, C)Thus, R’ = RDecomposition is lossless if:X intersection Y -> X, that is: all attributes common to both X and Y functionally determine ALL the attributes in X.X intersection Y -> Y, that is: all attributes common to both X and Y functionally determine ALL the attributes in YIf X intersection Y forms a superkey of either X or Y, the decomposition of R is a lossless decomposition." }, { "code": null, "e": 27852, "s": 27430, "text": "Attribute Preservation:Using functional dependencies the algorithms decompose the universal relation schema R in a set of relation schemas D = { R1, R2, ..... Rn } relational database schema, where ‘D’ is called the Decomposition of R.The attributes in R will appear in at least one relation schema Ri in the decomposition, i.e., no attribute is lost. This is called the Attribute Preservation condition of decomposition." }, { "code": null, "e": 28039, "s": 27852, "text": "The attributes in R will appear in at least one relation schema Ri in the decomposition, i.e., no attribute is lost. This is called the Attribute Preservation condition of decomposition." }, { "code": null, "e": 28965, "s": 28039, "text": "Dependency Preservation:If each functional dependency X->Y specified in F appears directly in one of the relation schemas Ri in the decomposition D or could be inferred from the dependencies that appear in some Ri. This is the Dependency Preservation.If a decomposition is not dependency preserving some dependency is lost in decomposition. To check this condition, take the JOIN of 2 or more relations in the decomposition.For example:R = (A, B, C)\nF = {A ->B, B->C}\nKey = {A}\n\nR is not in BCNF.\nDecomposition R1 = (A, B), R2 = (B, C) R1 and R2 are in BCNF, Lossless-join decomposition, Dependency preserving.Each Functional Dependency specified in F either appears directly in one of the relations in the decomposition.It is not necessary that all dependencies from the relation R appear in some relation Ri.It is sufficient that the union of the dependencies on all the relations Ri be equivalent to the dependencies on R." }, { "code": null, "e": 29139, "s": 28965, "text": "If a decomposition is not dependency preserving some dependency is lost in decomposition. To check this condition, take the JOIN of 2 or more relations in the decomposition." }, { "code": null, "e": 29152, "s": 29139, "text": "For example:" }, { "code": null, "e": 29253, "s": 29152, "text": "R = (A, B, C)\nF = {A ->B, B->C}\nKey = {A}\n\nR is not in BCNF.\nDecomposition R1 = (A, B), R2 = (B, C) " }, { "code": null, "e": 29643, "s": 29253, "text": "R1 and R2 are in BCNF, Lossless-join decomposition, Dependency preserving.Each Functional Dependency specified in F either appears directly in one of the relations in the decomposition.It is not necessary that all dependencies from the relation R appear in some relation Ri.It is sufficient that the union of the dependencies on all the relations Ri be equivalent to the dependencies on R." }, { "code": null, "e": 29908, "s": 29643, "text": "Non Additive Join Property:Another property of decomposition is that D should possess is the Non Additive Join Property, which ensures that no spurious tuples are generated when a NATURAL JOIN operation is applied to the relations resulting from the decomposition." }, { "code": null, "e": 30140, "s": 29908, "text": "No redundancy:Decomposition is used to eliminate some of the problems of bad design like anomalies, inconsistencies, and redundancy.If the relation has no proper decomposition, then it may lead to problems like loss of information." }, { "code": null, "e": 31129, "s": 30140, "text": "Lossless Join:Lossless join property is a feature of decomposition supported by normalization. It is the ability to ensure that any instance of the original relation can be identified from corresponding instances in the smaller relations.For example:R : relation, F : set of functional dependencies on R,X, Y : decomposition of R,A decomposition {R1, R2, ..., Rn} of a relation R is called a lossless decomposition for R if the natural join of R1, R2, ..., Rn produces exactly the relation R.A decomposition is lossless if we can recover:R(A, B, C) -> Decompose -> R1(A, B) R2(A, C) -> Recover -> R’(A, B, C)Thus, R’ = RDecomposition is lossless if:X intersection Y -> X, that is: all attributes common to both X and Y functionally determine ALL the attributes in X.X intersection Y -> Y, that is: all attributes common to both X and Y functionally determine ALL the attributes in YIf X intersection Y forms a superkey of either X or Y, the decomposition of R is a lossless decomposition." }, { "code": null, "e": 31384, "s": 31129, "text": "For example:R : relation, F : set of functional dependencies on R,X, Y : decomposition of R,A decomposition {R1, R2, ..., Rn} of a relation R is called a lossless decomposition for R if the natural join of R1, R2, ..., Rn produces exactly the relation R." }, { "code": null, "e": 31881, "s": 31384, "text": "A decomposition is lossless if we can recover:R(A, B, C) -> Decompose -> R1(A, B) R2(A, C) -> Recover -> R’(A, B, C)Thus, R’ = RDecomposition is lossless if:X intersection Y -> X, that is: all attributes common to both X and Y functionally determine ALL the attributes in X.X intersection Y -> Y, that is: all attributes common to both X and Y functionally determine ALL the attributes in YIf X intersection Y forms a superkey of either X or Y, the decomposition of R is a lossless decomposition." }, { "code": null, "e": 31900, "s": 31881, "text": "DBMS-Normalization" }, { "code": null, "e": 31905, "s": 31900, "text": "DBMS" }, { "code": null, "e": 31913, "s": 31905, "text": "GATE CS" }, { "code": null, "e": 31918, "s": 31913, "text": "DBMS" }, { "code": null, "e": 32016, "s": 31918, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32057, "s": 32016, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 32100, "s": 32057, "text": "Introduction of Relational Algebra in DBMS" }, { "code": null, "e": 32132, "s": 32100, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 32159, "s": 32132, "text": "KDD Process in Data Mining" }, { "code": null, "e": 32186, "s": 32159, "text": "Two Phase Locking Protocol" }, { "code": null, "e": 32206, "s": 32186, "text": "Layers of OSI Model" }, { "code": null, "e": 32233, "s": 32206, "text": "Types of Operating Systems" }, { "code": null, "e": 32246, "s": 32233, "text": "TCP/IP Model" }, { "code": null, "e": 32295, "s": 32246, "text": "Page Replacement Algorithms in Operating Systems" } ]
How to create a notification with NotificationCompat.Builder in Android?
Before getting into NotificationCompact.Builder, we should know what is a notification in android. Notification is just like as a message showing system on the action bar. just like missed call notification as shown below This example demonstrates how to integrate Android Notification. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project, and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:app = "http://schemas.android.com/apk/res-auto" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity"> <Button android:id = "@+id/button" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "Click" app:layout_constraintBottom_toBottomOf = "parent" app:layout_constraintLeft_toLeftOf = "parent" app:layout_constraintRight_toRightOf = "parent" app:layout_constraintTop_toTopOf = "parent" /> </android.support.constraint.ConstraintLayout> Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.annotation.SuppressLint; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.BitmapFactory; import android.graphics.Color; import android.os.Build; import android.support.annotation.RequiresApi; import android.support.v4.app.NotificationCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Switch; import android.widget.Toast; public class MainActivity extends AppCompatActivity implements View.OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button=findViewById(R.id.button); button.setOnClickListener(this); } @RequiresApi(api = Build.VERSION_CODES.O) @Override public void onClick(View v) { switch (v.getId()) { case R.id.button: notificationDialog(); break; } } @RequiresApi(api = Build.VERSION_CODES.O) private void notificationDialog() { NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); String NOTIFICATION_CHANNEL_ID = "tutorialspoint_01"; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { @SuppressLint("WrongConstant") NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_MAX); // Configure the notification channel. notificationChannel.setDescription("Sample Channel description"); notificationChannel.enableLights(true); notificationChannel.setLightColor(Color.RED); notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000}); notificationChannel.enableVibration(true); notificationManager.createNotificationChannel(notificationChannel); } NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID); notificationBuilder.setAutoCancel(true) .setDefaults(Notification.DEFAULT_ALL) .setWhen(System.currentTimeMillis()) .setSmallIcon(R.mipmap.ic_launcher) .setTicker("Tutorialspoint") //.setPriority(Notification.PRIORITY_MAX) .setContentTitle("sample notification") .setContentText("This is sample notification") .setContentInfo("Information"); notificationManager.notify(1, notificationBuilder.build()); } } Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen Now click on above button you will get an output as shown below
[ { "code": null, "e": 1284, "s": 1062, "text": "Before getting into NotificationCompact.Builder, we should know what is a notification in android. Notification is just like as a message showing system on the action bar. just like missed call notification as shown below" }, { "code": null, "e": 1349, "s": 1284, "text": "This example demonstrates how to integrate Android Notification." }, { "code": null, "e": 1479, "s": 1349, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project, and fill all required details to create a new project." }, { "code": null, "e": 1544, "s": 1479, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2348, "s": 1544, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.constraint.ConstraintLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\">\n <Button\n android:id = \"@+id/button\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:text = \"Click\"\n app:layout_constraintBottom_toBottomOf = \"parent\"\n app:layout_constraintLeft_toLeftOf = \"parent\"\n app:layout_constraintRight_toRightOf = \"parent\"\n app:layout_constraintTop_toTopOf = \"parent\" />\n</android.support.constraint.ConstraintLayout>" }, { "code": null, "e": 2405, "s": 2348, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 5248, "s": 2405, "text": "package com.example.andy.myapplication;\nimport android.annotation.SuppressLint;\nimport android.app.Notification;\nimport android.app.NotificationChannel;\nimport android.app.NotificationManager;\nimport android.app.PendingIntent;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.graphics.BitmapFactory;\nimport android.graphics.Color;\nimport android.os.Build;\nimport android.support.annotation.RequiresApi;\nimport android.support.v4.app.NotificationCompat;\nimport android.support.v7.app.AlertDialog;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.Switch;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity implements View.OnClickListener {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n Button button=findViewById(R.id.button);\n button.setOnClickListener(this);\n }\n @RequiresApi(api = Build.VERSION_CODES.O)\n @Override\n public void onClick(View v) {\n switch (v.getId()) {\n case R.id.button:\n notificationDialog();\n break;\n }\n }\n @RequiresApi(api = Build.VERSION_CODES.O)\n private void notificationDialog() {\n NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);\n String NOTIFICATION_CHANNEL_ID = \"tutorialspoint_01\";\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {\n @SuppressLint(\"WrongConstant\") NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, \"My Notifications\", NotificationManager.IMPORTANCE_MAX);\n // Configure the notification channel.\n notificationChannel.setDescription(\"Sample Channel description\");\n notificationChannel.enableLights(true);\n notificationChannel.setLightColor(Color.RED);\n notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});\n notificationChannel.enableVibration(true);\n notificationManager.createNotificationChannel(notificationChannel);\n }\n NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);\n notificationBuilder.setAutoCancel(true)\n .setDefaults(Notification.DEFAULT_ALL)\n .setWhen(System.currentTimeMillis())\n .setSmallIcon(R.mipmap.ic_launcher)\n .setTicker(\"Tutorialspoint\")\n //.setPriority(Notification.PRIORITY_MAX)\n .setContentTitle(\"sample notification\")\n .setContentText(\"This is sample notification\")\n .setContentInfo(\"Information\");\n notificationManager.notify(1, notificationBuilder.build());\n }\n}" }, { "code": null, "e": 5597, "s": 5248, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen" }, { "code": null, "e": 5661, "s": 5597, "text": "Now click on above button you will get an output as shown below" } ]