title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Automate the Structure of Your Data Science Projects with Cookiecutter | by Ahmed Besbes | Towards Data Science
|
Here’s a situation a lot of data scientists are familiar with.
Every time you start a new project, you reuse the structure of older projects. You go through their folders and copy-paste them, you remove the unnecessary files, you rename the remaining ones with your new project’s specifics, and you go inside each configuration file and replace the old environment variables (URLs, API keys, Hosts, Ports, etc.) with the new ones.
And maybe, who knows, you’ll create new configurations and new folders along the way.
❌ We all agree that this is a pretty tedious and repetitive task. Not to mention that it’s prone to errors.
✅ Wouldn’t be more convenient to start each new project from a master template that you’d clone and fill in with the specific information from the terminal? Wouldn’t be great to let this template automatically build a whole folder structure for you, and populate the files with the right names and variables you define?
Cookiecutter is the right solution to this problem.
In this post, we’ll have a look at cookiecutter.We’ll understand how it works and how you can use it to build custom and reusable templates for your projects.Then, we’ll cover the Cookiecutter Data Science open-source template to kickstart data science projects that follow the best standards in the industry.
Without further ado, let’s have a look 🔍
“Cookiecutter creates projects from project templates.” — official doc
Projects can be python packages, web applications, machine learning apps with complex workflows or anything you can think of
Templates are what cookiecutter uses to create projects. They rely on Jinja2’s syntax
What cookiecutter does is quite simple: it clones a directory and put it inside your new project. It then replaces all the names that are between {{ and }} (Jinja2 syntax) with names that it finds in the cookiecutter.json file. (We’ll see an example of how to build a cookiecutter template in the next section)
To get started using cookiecutter, you can install it with pip:
pip install cookiecutter
or conda:
conda install -c conda-forge cookiecutter
👉 You can use cookiecutter on all platforms: Windows, Mac and Linux👉 It works with Python 2.7+ and 3.5+(although prefer Python 3.5+ since Python 2.7 is no longer maintained)👉 You can use Cookiecutter to create templates in one or multiple languages
In this section, I’ll show you how to create a cookiecutter template to kickstart Streamlit projects.
If you’re not familiar with Streamlit, it’s a Python library designed to build web applications. It’s very simple to use and provides a lot of functionalities. I use it on a daily basis to share experiments and results with my team and to prototype machine learning apps.
My Streamlit-based projects tend to have the following structure:
An src folder that contains the main script of the app (app.py ) as well as a utils module that contains two scripts: ui.py to put the layout functions and common.py to hold other utility functions for data processing or remote database connections (among other things)
A .gitignore file to prevent git from versioning unnecessary files (such as .env files, or .pyc files)
Procfile and setup.sh : to handle the deployment on Heroku
requirements.txt : to list the project dependencies
A .env file to store the environment variables of the project
A README.md to share details about the project
To create a cookiecutter template that generates this structure, let’s start by creating a folder for this template.
mkdir streamlit-cookiecuttercd streamlit-cookiecutter
Inside this folder, create the cookiecutter.json file:
A few things about this file:
Each key is an item that cookiecutter will ask for when it kickstarts a project from the template
Each value corresponds to the default value of each item
The values of the items are set in order. For example, the repo_name is set after the project_name (since its value depends on project_name ‘s value)
Setting the values of these items happens when you clone the template with cookiecutter: we’ll see how this is done in the next step.
Now create the folder and put the desired target structure in it. We’ll name this folder based on the repo_name item. In cookiecutter syntax: {{cookiecutter.repo_name}} .
Inside the {{cookiecutter.repo_name}} folder, put the desired structure that you want into your projects:
Each of these files can access the values of the items you pass to cookie-cutter: all you have to do is use {{ and }} .
Let’s see how we can exploit this.
👉 Generate a README.mdWe can automatically generate the README.md by inserting the items project_name , description , open_source_license in it.
{{cookiecutter.description}}
{{cookiecutter.open_source_license}}
👉 Set environment variablesWe can automatically fill in the values of s3_bucket , aws_profile,port , host and api_key inside the .env file.
👉 Deduplicate codeIf your Streamlit apps follow the same structure and all start with the name of the project as the title, there’s no need to repeat this code every time.
Once you’re done with your template’s code, push it to Github. I’ve done it and you can check it here.
Now that the template is on Github, let’s use it to start a project.
Let’s say that I want to create a sentiment analysis app in Streamlit.
All I need to do is call cookiecutter with the URL of the template.
cookiecutter git@github.com:ahmedbesbes/streamlit-cookiecutter.git
Once you execute this command, Cookiecutter will ask you to set the values of the items you defined in the cookiecutter.json file (notice that the default value of each item is put between brackets).
After entering the specific values for each item, the project is created.
Let’s check its README.md✅
Its .envfile ✅
Its app.pyfile ✅
All good. The project has the desired structure and the files are populated with the right data.
Now we can start working on this app.
One great thing about cookiecutter is the vibrant community. There’s a bunch of open-source templates out there and of different flavours (Django, Flask, FastAPI, you name it). You can easily look them up on Github and start using them.
One particular template that caught my attention is Cookiecutter Data Science.
As the authors say, this template is:
A logical, reasonably standardized, but flexible project structure for doing and sharing data science work.
What this template provides in practice, is a set of directories to better organize your work. It’s slightly opinionated, but it follows good practices that the field agrees on.
In my opinion, it helps:
Organizing the modules by responsibility: dataset creation, feature engineering, modelling, visualization
Organizing the data by pipeline stage
Enforcing unit tests
Creating documentation
You can start using this template like the following:
Once you’re done setting the values for each item, you’ll get the following structure:
You don’t have to stick with this structure: if you’re not happy with it, you can fork the template and modify it to fit your needs.
Cookiecutter is a fantastic library. It helps automate project creation and prevents you from repeating yourself. As a data scientist, it must be part of your toolbox.
To learn more about Cookiecutter, I’ve selected some good resources you can easily go through:
https://github.com/cookiecutter/cookiecutter
https://drivendata.github.io/cookiecutter-data-science/
https://dev.to/azure/10-top-tips-for-reproducible-machine-learning-36g0
https://towardsdatascience.com/template-your-data-science-projects-with-cookiecutter-754d3c584d13
https://youtu.be/nExL0SgKsDY (an excellent Youtube video)
If you’ve stuck till the end, I really thank you for your time and hope that you learned something about cookiecutter and project templating.
That’ll be all for me today. Until next time for more programming tips and tutorials. 👋
|
[
{
"code": null,
"e": 235,
"s": 172,
"text": "Here’s a situation a lot of data scientists are familiar with."
},
{
"code": null,
"e": 603,
"s": 235,
"text": "Every time you start a new project, you reuse the structure of older projects. You go through their folders and copy-paste them, you remove the unnecessary files, you rename the remaining ones with your new project’s specifics, and you go inside each configuration file and replace the old environment variables (URLs, API keys, Hosts, Ports, etc.) with the new ones."
},
{
"code": null,
"e": 689,
"s": 603,
"text": "And maybe, who knows, you’ll create new configurations and new folders along the way."
},
{
"code": null,
"e": 797,
"s": 689,
"text": "❌ We all agree that this is a pretty tedious and repetitive task. Not to mention that it’s prone to errors."
},
{
"code": null,
"e": 1117,
"s": 797,
"text": "✅ Wouldn’t be more convenient to start each new project from a master template that you’d clone and fill in with the specific information from the terminal? Wouldn’t be great to let this template automatically build a whole folder structure for you, and populate the files with the right names and variables you define?"
},
{
"code": null,
"e": 1169,
"s": 1117,
"text": "Cookiecutter is the right solution to this problem."
},
{
"code": null,
"e": 1479,
"s": 1169,
"text": "In this post, we’ll have a look at cookiecutter.We’ll understand how it works and how you can use it to build custom and reusable templates for your projects.Then, we’ll cover the Cookiecutter Data Science open-source template to kickstart data science projects that follow the best standards in the industry."
},
{
"code": null,
"e": 1520,
"s": 1479,
"text": "Without further ado, let’s have a look 🔍"
},
{
"code": null,
"e": 1591,
"s": 1520,
"text": "“Cookiecutter creates projects from project templates.” — official doc"
},
{
"code": null,
"e": 1716,
"s": 1591,
"text": "Projects can be python packages, web applications, machine learning apps with complex workflows or anything you can think of"
},
{
"code": null,
"e": 1802,
"s": 1716,
"text": "Templates are what cookiecutter uses to create projects. They rely on Jinja2’s syntax"
},
{
"code": null,
"e": 2113,
"s": 1802,
"text": "What cookiecutter does is quite simple: it clones a directory and put it inside your new project. It then replaces all the names that are between {{ and }} (Jinja2 syntax) with names that it finds in the cookiecutter.json file. (We’ll see an example of how to build a cookiecutter template in the next section)"
},
{
"code": null,
"e": 2177,
"s": 2113,
"text": "To get started using cookiecutter, you can install it with pip:"
},
{
"code": null,
"e": 2202,
"s": 2177,
"text": "pip install cookiecutter"
},
{
"code": null,
"e": 2212,
"s": 2202,
"text": "or conda:"
},
{
"code": null,
"e": 2254,
"s": 2212,
"text": "conda install -c conda-forge cookiecutter"
},
{
"code": null,
"e": 2503,
"s": 2254,
"text": "👉 You can use cookiecutter on all platforms: Windows, Mac and Linux👉 It works with Python 2.7+ and 3.5+(although prefer Python 3.5+ since Python 2.7 is no longer maintained)👉 You can use Cookiecutter to create templates in one or multiple languages"
},
{
"code": null,
"e": 2605,
"s": 2503,
"text": "In this section, I’ll show you how to create a cookiecutter template to kickstart Streamlit projects."
},
{
"code": null,
"e": 2877,
"s": 2605,
"text": "If you’re not familiar with Streamlit, it’s a Python library designed to build web applications. It’s very simple to use and provides a lot of functionalities. I use it on a daily basis to share experiments and results with my team and to prototype machine learning apps."
},
{
"code": null,
"e": 2943,
"s": 2877,
"text": "My Streamlit-based projects tend to have the following structure:"
},
{
"code": null,
"e": 3213,
"s": 2943,
"text": "An src folder that contains the main script of the app (app.py ) as well as a utils module that contains two scripts: ui.py to put the layout functions and common.py to hold other utility functions for data processing or remote database connections (among other things)"
},
{
"code": null,
"e": 3316,
"s": 3213,
"text": "A .gitignore file to prevent git from versioning unnecessary files (such as .env files, or .pyc files)"
},
{
"code": null,
"e": 3375,
"s": 3316,
"text": "Procfile and setup.sh : to handle the deployment on Heroku"
},
{
"code": null,
"e": 3427,
"s": 3375,
"text": "requirements.txt : to list the project dependencies"
},
{
"code": null,
"e": 3489,
"s": 3427,
"text": "A .env file to store the environment variables of the project"
},
{
"code": null,
"e": 3536,
"s": 3489,
"text": "A README.md to share details about the project"
},
{
"code": null,
"e": 3653,
"s": 3536,
"text": "To create a cookiecutter template that generates this structure, let’s start by creating a folder for this template."
},
{
"code": null,
"e": 3707,
"s": 3653,
"text": "mkdir streamlit-cookiecuttercd streamlit-cookiecutter"
},
{
"code": null,
"e": 3762,
"s": 3707,
"text": "Inside this folder, create the cookiecutter.json file:"
},
{
"code": null,
"e": 3792,
"s": 3762,
"text": "A few things about this file:"
},
{
"code": null,
"e": 3890,
"s": 3792,
"text": "Each key is an item that cookiecutter will ask for when it kickstarts a project from the template"
},
{
"code": null,
"e": 3947,
"s": 3890,
"text": "Each value corresponds to the default value of each item"
},
{
"code": null,
"e": 4097,
"s": 3947,
"text": "The values of the items are set in order. For example, the repo_name is set after the project_name (since its value depends on project_name ‘s value)"
},
{
"code": null,
"e": 4231,
"s": 4097,
"text": "Setting the values of these items happens when you clone the template with cookiecutter: we’ll see how this is done in the next step."
},
{
"code": null,
"e": 4402,
"s": 4231,
"text": "Now create the folder and put the desired target structure in it. We’ll name this folder based on the repo_name item. In cookiecutter syntax: {{cookiecutter.repo_name}} ."
},
{
"code": null,
"e": 4508,
"s": 4402,
"text": "Inside the {{cookiecutter.repo_name}} folder, put the desired structure that you want into your projects:"
},
{
"code": null,
"e": 4628,
"s": 4508,
"text": "Each of these files can access the values of the items you pass to cookie-cutter: all you have to do is use {{ and }} ."
},
{
"code": null,
"e": 4663,
"s": 4628,
"text": "Let’s see how we can exploit this."
},
{
"code": null,
"e": 4808,
"s": 4663,
"text": "👉 Generate a README.mdWe can automatically generate the README.md by inserting the items project_name , description , open_source_license in it."
},
{
"code": null,
"e": 4837,
"s": 4808,
"text": "{{cookiecutter.description}}"
},
{
"code": null,
"e": 4874,
"s": 4837,
"text": "{{cookiecutter.open_source_license}}"
},
{
"code": null,
"e": 5014,
"s": 4874,
"text": "👉 Set environment variablesWe can automatically fill in the values of s3_bucket , aws_profile,port , host and api_key inside the .env file."
},
{
"code": null,
"e": 5186,
"s": 5014,
"text": "👉 Deduplicate codeIf your Streamlit apps follow the same structure and all start with the name of the project as the title, there’s no need to repeat this code every time."
},
{
"code": null,
"e": 5289,
"s": 5186,
"text": "Once you’re done with your template’s code, push it to Github. I’ve done it and you can check it here."
},
{
"code": null,
"e": 5358,
"s": 5289,
"text": "Now that the template is on Github, let’s use it to start a project."
},
{
"code": null,
"e": 5429,
"s": 5358,
"text": "Let’s say that I want to create a sentiment analysis app in Streamlit."
},
{
"code": null,
"e": 5497,
"s": 5429,
"text": "All I need to do is call cookiecutter with the URL of the template."
},
{
"code": null,
"e": 5564,
"s": 5497,
"text": "cookiecutter git@github.com:ahmedbesbes/streamlit-cookiecutter.git"
},
{
"code": null,
"e": 5764,
"s": 5564,
"text": "Once you execute this command, Cookiecutter will ask you to set the values of the items you defined in the cookiecutter.json file (notice that the default value of each item is put between brackets)."
},
{
"code": null,
"e": 5838,
"s": 5764,
"text": "After entering the specific values for each item, the project is created."
},
{
"code": null,
"e": 5865,
"s": 5838,
"text": "Let’s check its README.md✅"
},
{
"code": null,
"e": 5880,
"s": 5865,
"text": "Its .envfile ✅"
},
{
"code": null,
"e": 5897,
"s": 5880,
"text": "Its app.pyfile ✅"
},
{
"code": null,
"e": 5994,
"s": 5897,
"text": "All good. The project has the desired structure and the files are populated with the right data."
},
{
"code": null,
"e": 6032,
"s": 5994,
"text": "Now we can start working on this app."
},
{
"code": null,
"e": 6269,
"s": 6032,
"text": "One great thing about cookiecutter is the vibrant community. There’s a bunch of open-source templates out there and of different flavours (Django, Flask, FastAPI, you name it). You can easily look them up on Github and start using them."
},
{
"code": null,
"e": 6348,
"s": 6269,
"text": "One particular template that caught my attention is Cookiecutter Data Science."
},
{
"code": null,
"e": 6386,
"s": 6348,
"text": "As the authors say, this template is:"
},
{
"code": null,
"e": 6494,
"s": 6386,
"text": "A logical, reasonably standardized, but flexible project structure for doing and sharing data science work."
},
{
"code": null,
"e": 6672,
"s": 6494,
"text": "What this template provides in practice, is a set of directories to better organize your work. It’s slightly opinionated, but it follows good practices that the field agrees on."
},
{
"code": null,
"e": 6697,
"s": 6672,
"text": "In my opinion, it helps:"
},
{
"code": null,
"e": 6803,
"s": 6697,
"text": "Organizing the modules by responsibility: dataset creation, feature engineering, modelling, visualization"
},
{
"code": null,
"e": 6841,
"s": 6803,
"text": "Organizing the data by pipeline stage"
},
{
"code": null,
"e": 6862,
"s": 6841,
"text": "Enforcing unit tests"
},
{
"code": null,
"e": 6885,
"s": 6862,
"text": "Creating documentation"
},
{
"code": null,
"e": 6939,
"s": 6885,
"text": "You can start using this template like the following:"
},
{
"code": null,
"e": 7026,
"s": 6939,
"text": "Once you’re done setting the values for each item, you’ll get the following structure:"
},
{
"code": null,
"e": 7159,
"s": 7026,
"text": "You don’t have to stick with this structure: if you’re not happy with it, you can fork the template and modify it to fit your needs."
},
{
"code": null,
"e": 7327,
"s": 7159,
"text": "Cookiecutter is a fantastic library. It helps automate project creation and prevents you from repeating yourself. As a data scientist, it must be part of your toolbox."
},
{
"code": null,
"e": 7422,
"s": 7327,
"text": "To learn more about Cookiecutter, I’ve selected some good resources you can easily go through:"
},
{
"code": null,
"e": 7467,
"s": 7422,
"text": "https://github.com/cookiecutter/cookiecutter"
},
{
"code": null,
"e": 7523,
"s": 7467,
"text": "https://drivendata.github.io/cookiecutter-data-science/"
},
{
"code": null,
"e": 7595,
"s": 7523,
"text": "https://dev.to/azure/10-top-tips-for-reproducible-machine-learning-36g0"
},
{
"code": null,
"e": 7693,
"s": 7595,
"text": "https://towardsdatascience.com/template-your-data-science-projects-with-cookiecutter-754d3c584d13"
},
{
"code": null,
"e": 7751,
"s": 7693,
"text": "https://youtu.be/nExL0SgKsDY (an excellent Youtube video)"
},
{
"code": null,
"e": 7893,
"s": 7751,
"text": "If you’ve stuck till the end, I really thank you for your time and hope that you learned something about cookiecutter and project templating."
}
] |
Comparator reversed() method in Java with examples - GeeksforGeeks
|
05 Feb, 2021
The reversed() method of Comparator Interface in Java returns a comparator that imposes the reverse ordering of this comparator. If you use sort method of the array and passes this comparator after applying the reversed method then it will sort the array in reverse order.
Syntax:
default Comparator<T> reversed()
Parameters: This method accepts nothing.
Return value: This method returns a comparator that imposes the reverse ordering of this comparator.
Below programs illustrate reversed() method:
Program 1:
Java
// Java program to demonstrate// Comparator.reversed() method import java.util.*; public class GFG { public static void main(String[] args) { String[] Arraystrings = { "aman", "amar", "avik" }; System.out.println("before sort : " + Arrays.toString(Arraystrings)); Comparator<String> comp = (String::compareTo); Arrays.sort(Arraystrings, comp.reversed()); System.out.println("after sort : " + Arrays.toString(Arraystrings)); }}
before sort : [aman, amar, avik]
after sort : [avik, amar, aman]
Program 2:
Java
// Java program to demonstrate// Comparator.reversed() method import java.util.*; public class GFG { public static void main(String[] args) { String[] list = { "KKR", "CSK", "MI", "KXIP", "RCB", "SRH", "DC", "RR" }; System.out.println("Before sorting:"); System.out.println(Arrays.toString(list)); Comparator<String> comp = (String::compareTo); Arrays.sort(list, comp.reversed()); System.out.println("After sorting:"); System.out.println(Arrays.toString(list)); }}
Before sorting:
[KKR, CSK, MI, KXIP, RCB, SRH, DC, RR]
After sorting:
[SRH, RR, RCB, MI, KXIP, KKR, DC, CSK]
References: https://docs.oracle.com/javase/10/docs/api/java/util/Comparator.html#reversed()
lyleziegelmiller
Java - util package
Java-Comparator
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
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
LinkedList in Java
|
[
{
"code": null,
"e": 24109,
"s": 24081,
"text": "\n05 Feb, 2021"
},
{
"code": null,
"e": 24382,
"s": 24109,
"text": "The reversed() method of Comparator Interface in Java returns a comparator that imposes the reverse ordering of this comparator. If you use sort method of the array and passes this comparator after applying the reversed method then it will sort the array in reverse order."
},
{
"code": null,
"e": 24392,
"s": 24382,
"text": "Syntax: "
},
{
"code": null,
"e": 24425,
"s": 24392,
"text": "default Comparator<T> reversed()"
},
{
"code": null,
"e": 24466,
"s": 24425,
"text": "Parameters: This method accepts nothing."
},
{
"code": null,
"e": 24567,
"s": 24466,
"text": "Return value: This method returns a comparator that imposes the reverse ordering of this comparator."
},
{
"code": null,
"e": 24613,
"s": 24567,
"text": "Below programs illustrate reversed() method: "
},
{
"code": null,
"e": 24625,
"s": 24613,
"text": "Program 1: "
},
{
"code": null,
"e": 24630,
"s": 24625,
"text": "Java"
},
{
"code": "// Java program to demonstrate// Comparator.reversed() method import java.util.*; public class GFG { public static void main(String[] args) { String[] Arraystrings = { \"aman\", \"amar\", \"avik\" }; System.out.println(\"before sort : \" + Arrays.toString(Arraystrings)); Comparator<String> comp = (String::compareTo); Arrays.sort(Arraystrings, comp.reversed()); System.out.println(\"after sort : \" + Arrays.toString(Arraystrings)); }}",
"e": 25158,
"s": 24630,
"text": null
},
{
"code": null,
"e": 25224,
"s": 25158,
"text": "before sort : [aman, amar, avik]\nafter sort : [avik, amar, aman]\n"
},
{
"code": null,
"e": 25236,
"s": 25224,
"text": "Program 2: "
},
{
"code": null,
"e": 25241,
"s": 25236,
"text": "Java"
},
{
"code": "// Java program to demonstrate// Comparator.reversed() method import java.util.*; public class GFG { public static void main(String[] args) { String[] list = { \"KKR\", \"CSK\", \"MI\", \"KXIP\", \"RCB\", \"SRH\", \"DC\", \"RR\" }; System.out.println(\"Before sorting:\"); System.out.println(Arrays.toString(list)); Comparator<String> comp = (String::compareTo); Arrays.sort(list, comp.reversed()); System.out.println(\"After sorting:\"); System.out.println(Arrays.toString(list)); }}",
"e": 25795,
"s": 25241,
"text": null
},
{
"code": null,
"e": 25905,
"s": 25795,
"text": "Before sorting:\n[KKR, CSK, MI, KXIP, RCB, SRH, DC, RR]\nAfter sorting:\n[SRH, RR, RCB, MI, KXIP, KKR, DC, CSK]\n"
},
{
"code": null,
"e": 25998,
"s": 25905,
"text": "References: https://docs.oracle.com/javase/10/docs/api/java/util/Comparator.html#reversed() "
},
{
"code": null,
"e": 26015,
"s": 25998,
"text": "lyleziegelmiller"
},
{
"code": null,
"e": 26035,
"s": 26015,
"text": "Java - util package"
},
{
"code": null,
"e": 26051,
"s": 26035,
"text": "Java-Comparator"
},
{
"code": null,
"e": 26066,
"s": 26051,
"text": "Java-Functions"
},
{
"code": null,
"e": 26071,
"s": 26066,
"text": "Java"
},
{
"code": null,
"e": 26076,
"s": 26071,
"text": "Java"
},
{
"code": null,
"e": 26174,
"s": 26076,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26183,
"s": 26174,
"text": "Comments"
},
{
"code": null,
"e": 26196,
"s": 26183,
"text": "Old Comments"
},
{
"code": null,
"e": 26247,
"s": 26196,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 26277,
"s": 26247,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 26308,
"s": 26277,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 26327,
"s": 26308,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 26359,
"s": 26327,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 26377,
"s": 26359,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 26397,
"s": 26377,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 26429,
"s": 26397,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 26453,
"s": 26429,
"text": "Singleton Class in Java"
}
] |
4 Cute Python Functions for Working with Dirty Data | by Onel Harrison | Towards Data Science
|
Coalesce
Safe Get
Dig
Safe Cast
Conclusion
This function comes in handy when there are one or more possible values that could be assigned to a variable or used in a given situation and there is a known preference for which value among the options should be selected for use if it’s available.
If you have been writing SQL queries of at least a moderate complexity, the purpose of a coalesce function may already be clear to you. But for those who are unfamiliar with it, a motivating example may be instructive.
Let’s say we’re working with a subset of the response data for a story retrieved from Medium’s Stories API, and we want to extract a link to the featured image for a story. However, we would prefer to extract the link for the image with the highest available resolution.
story = { "image": { "image_url_large": "https://cdn.images.site/large.png", "image_url_medium": "https://cdn.images.site/medium.png", "image_url_small": "https://cdn.images.site/small.png" },}
In this case, the following code might suffice.
featured_image_url = story["image"]["image_url_large"]
But, imagine that sometimes no image URLs are returned from the API (e.g. for stories that do not include any images) or the URL for each image size is present only some of the time.
We could write a series of if statements and use dict.get to safely extract a URL. However, the coalesce function defined above makes it so that we can extract the featured image URL quite simply and safely.
featured_image_url = Noneif story.get("image"): featured_image_url = coalesce( story1.get("image").get("image_url_large"), story1.get("image").get("image_url_medium"), story1.get("image").get("image_url_small") )
We could even forgo the presence check for the image field if the following is more to our liking. It’s certainly more appealing to look at.
featured_image_url = coalesce( story.get("image", {}).get("image_url_large"), story.get("image", {}).get("image_url_medium"), story.get("image", {}).get("image_url_small"))
It is worth noting that a similar, but not equivalent, behavior is achievable by using Python’s or operator and relying on Python’s truthiness semantics.
featured_image_url = ( story.get("image", {}).get("image_url_large") or story.get("image", {}).get("image_url_medium") or story.get("image", {}).get("image_url_small"))
This would produce the correct result for our example, but it would fail in a situation where an empty string or zero are valid values that could be extracted. That is because empty string and zero are falsy values in Python.
In that case, we would need a function like our coalesce that is stricter about what values it considers to mean “nothing,” which is only the None value.
When working with JSON-style data, we extract values from the dict and list data structures as naturally as the sun rises and sets each day.
This means it can be an inconvenience not having a unified interface through which we can extract values from both types of collections.
The safe_get function beautifully provides that unified interface while also freeing us from wrapping our extraction code with error handling logic since the safe_get function simply returns None (or a provided default) if a value is not found.
With our implementation of safe_get, we could update our code for extracting the URL of the highest resolution image for a story’s featured image to be more functional in style.
featured_image_url = coalesce( safe_get(safe_get(story, "image", {}), "image_url_large"), safe_get(safe_get(story, "image", {}), "image_url_medium"), safe_get(safe_get(story, "image", {}), "image_url_small"))
As previously mentioned though, we also get a unified interface for extracting data from both dict and list data structures. So let’s demonstrate that.
Let’s again assume the data below is from Medium’s Stories API.
featured_stories = [ {"title": "Python: One Problem, Several Lessons", "description": "...", "body": "...", "image": {}, "stats": {},}, {"title": "Improving Code Quality in Python Codebases", "description": "...", "body": "...", "image": {}, "stats": {},}, {"title": "How to recursively reverse a linked list", "description": "...", "body": "...", "image": {}, "stats": {},},]
With this data, we’re interested in extracting the third featured story for a given Medium publication or user. Why? Because the saying “third time’s the charm” is one of our operating principles.
However, not every publication or user will have three or more stories from which we can pick the third one. But we don’t mind. We can optimistically write our extraction code using our safe_get function.
third_featured_story = safe_get(featured_stories, 2) # 0-index 👨🏿🏫
If there is no third featured story, we’ll get back None from safe_get and be on our way.
Another great use for safe_get is as a building block function — for example, as seen in our implementation of the following dig function.
The dig function can be used to extract values from potentially nested dict and list data structures. It’s quite useful in data extraction and transformation because we often need to flatten nested data so that we can store it as structured data in a database.
I have spent the major of my time in data engineering (so far) using the Ruby programming language. Ruby has the Array#dig and Hash#dig methods, which make picking values from potentially nested dict and list data structures, in which values could be missing, quite easy. However, this functionality is not natively available in Python, so we have to build it ourselves.
Side note: A Python list corresponds to a Ruby Array, and a Python dict corresponds to a Ruby Hash.
Here is a reminder of what the implementation of our safe_get function looks like. We will be using it as a helper function in our implementation of dig which follows.
Now here is our implementation of the dig function using safe_get as a helper function.
We can once again update our code for extracting the URL of the highest resolution image for a story’s featured image using our dig function.
featured_image_url = coalesce( dig(story, "image", "image_url_large"), dig(story, "image", "image_url_medium"), dig(story, "image", "image_url_small"))
But let us go a bit further. Take the following setup for instance. We have nested dict and list data, and as indicated by the types on the attributes of the MediumStory class, there are some attributes (marked as Optional) that we do not always expect values to be present for.
Now, let’s write some code to extract and flatten this nested story data into our Python class.
This function hardly needs a motivating example. It’s useful when we would prefer getting None (or some default value we set) if we fail to convert a value from one type to another.
One example that readily comes to mind is the conversion of a string value to a numeric value. Such a conversion would typically fail if unacceptable inputs such as empty string are provided, but with safe_cast we can suppress the exceptions and specify a default value if necessary. Examine the following code for how safe_cast might come in handy.
In this article, we looked at 4 Python functions that can help us safely extract or transform values from dirty data.
coalesce allows us to pick the first present (not-None) value among its arguments.
safe_get provides a unified interface that allows us to safely extract data from dict or list data structures.
dig lets us to reach into and extract values from potentially nested dict and list data structures.
safe_cast allows us to safely convert a value from one type to another.
Each of these functions is implemented in a way that minimizes the clutter of error handling logic by allowing us to pick a reasonable default return value (or None) in case we encounter a data extraction or transformation failure.
Additionally, they make it easy for us to extract data from the two most common data structures (dict and list), which are also what we get when we serialize JSON, the most popular data interchange format, for processing.
Thank you for reading!
Python: One Problem, Several Lessons
Improving Code Quality in Python Codebases
How to recursively reverse a linked list
Watch videos covering a variety of topics in Computing at OnelTalksTech.com
StackOverflow user Artisom Rudzenk for the safe_cast code snippet
StackOverflow user pilcrow for the coalesce code snippet
|
[
{
"code": null,
"e": 181,
"s": 172,
"text": "Coalesce"
},
{
"code": null,
"e": 190,
"s": 181,
"text": "Safe Get"
},
{
"code": null,
"e": 194,
"s": 190,
"text": "Dig"
},
{
"code": null,
"e": 204,
"s": 194,
"text": "Safe Cast"
},
{
"code": null,
"e": 215,
"s": 204,
"text": "Conclusion"
},
{
"code": null,
"e": 465,
"s": 215,
"text": "This function comes in handy when there are one or more possible values that could be assigned to a variable or used in a given situation and there is a known preference for which value among the options should be selected for use if it’s available."
},
{
"code": null,
"e": 684,
"s": 465,
"text": "If you have been writing SQL queries of at least a moderate complexity, the purpose of a coalesce function may already be clear to you. But for those who are unfamiliar with it, a motivating example may be instructive."
},
{
"code": null,
"e": 955,
"s": 684,
"text": "Let’s say we’re working with a subset of the response data for a story retrieved from Medium’s Stories API, and we want to extract a link to the featured image for a story. However, we would prefer to extract the link for the image with the highest available resolution."
},
{
"code": null,
"e": 1176,
"s": 955,
"text": "story = { \"image\": { \"image_url_large\": \"https://cdn.images.site/large.png\", \"image_url_medium\": \"https://cdn.images.site/medium.png\", \"image_url_small\": \"https://cdn.images.site/small.png\" },}"
},
{
"code": null,
"e": 1224,
"s": 1176,
"text": "In this case, the following code might suffice."
},
{
"code": null,
"e": 1279,
"s": 1224,
"text": "featured_image_url = story[\"image\"][\"image_url_large\"]"
},
{
"code": null,
"e": 1462,
"s": 1279,
"text": "But, imagine that sometimes no image URLs are returned from the API (e.g. for stories that do not include any images) or the URL for each image size is present only some of the time."
},
{
"code": null,
"e": 1670,
"s": 1462,
"text": "We could write a series of if statements and use dict.get to safely extract a URL. However, the coalesce function defined above makes it so that we can extract the featured image URL quite simply and safely."
},
{
"code": null,
"e": 1910,
"s": 1670,
"text": "featured_image_url = Noneif story.get(\"image\"): featured_image_url = coalesce( story1.get(\"image\").get(\"image_url_large\"), story1.get(\"image\").get(\"image_url_medium\"), story1.get(\"image\").get(\"image_url_small\") )"
},
{
"code": null,
"e": 2051,
"s": 1910,
"text": "We could even forgo the presence check for the image field if the following is more to our liking. It’s certainly more appealing to look at."
},
{
"code": null,
"e": 2233,
"s": 2051,
"text": "featured_image_url = coalesce( story.get(\"image\", {}).get(\"image_url_large\"), story.get(\"image\", {}).get(\"image_url_medium\"), story.get(\"image\", {}).get(\"image_url_small\"))"
},
{
"code": null,
"e": 2387,
"s": 2233,
"text": "It is worth noting that a similar, but not equivalent, behavior is achievable by using Python’s or operator and relying on Python’s truthiness semantics."
},
{
"code": null,
"e": 2565,
"s": 2387,
"text": "featured_image_url = ( story.get(\"image\", {}).get(\"image_url_large\") or story.get(\"image\", {}).get(\"image_url_medium\") or story.get(\"image\", {}).get(\"image_url_small\"))"
},
{
"code": null,
"e": 2791,
"s": 2565,
"text": "This would produce the correct result for our example, but it would fail in a situation where an empty string or zero are valid values that could be extracted. That is because empty string and zero are falsy values in Python."
},
{
"code": null,
"e": 2945,
"s": 2791,
"text": "In that case, we would need a function like our coalesce that is stricter about what values it considers to mean “nothing,” which is only the None value."
},
{
"code": null,
"e": 3086,
"s": 2945,
"text": "When working with JSON-style data, we extract values from the dict and list data structures as naturally as the sun rises and sets each day."
},
{
"code": null,
"e": 3223,
"s": 3086,
"text": "This means it can be an inconvenience not having a unified interface through which we can extract values from both types of collections."
},
{
"code": null,
"e": 3468,
"s": 3223,
"text": "The safe_get function beautifully provides that unified interface while also freeing us from wrapping our extraction code with error handling logic since the safe_get function simply returns None (or a provided default) if a value is not found."
},
{
"code": null,
"e": 3646,
"s": 3468,
"text": "With our implementation of safe_get, we could update our code for extracting the URL of the highest resolution image for a story’s featured image to be more functional in style."
},
{
"code": null,
"e": 3864,
"s": 3646,
"text": "featured_image_url = coalesce( safe_get(safe_get(story, \"image\", {}), \"image_url_large\"), safe_get(safe_get(story, \"image\", {}), \"image_url_medium\"), safe_get(safe_get(story, \"image\", {}), \"image_url_small\"))"
},
{
"code": null,
"e": 4016,
"s": 3864,
"text": "As previously mentioned though, we also get a unified interface for extracting data from both dict and list data structures. So let’s demonstrate that."
},
{
"code": null,
"e": 4080,
"s": 4016,
"text": "Let’s again assume the data below is from Medium’s Stories API."
},
{
"code": null,
"e": 4514,
"s": 4080,
"text": "featured_stories = [ {\"title\": \"Python: One Problem, Several Lessons\", \"description\": \"...\", \"body\": \"...\", \"image\": {}, \"stats\": {},}, {\"title\": \"Improving Code Quality in Python Codebases\", \"description\": \"...\", \"body\": \"...\", \"image\": {}, \"stats\": {},}, {\"title\": \"How to recursively reverse a linked list\", \"description\": \"...\", \"body\": \"...\", \"image\": {}, \"stats\": {},},]"
},
{
"code": null,
"e": 4711,
"s": 4514,
"text": "With this data, we’re interested in extracting the third featured story for a given Medium publication or user. Why? Because the saying “third time’s the charm” is one of our operating principles."
},
{
"code": null,
"e": 4916,
"s": 4711,
"text": "However, not every publication or user will have three or more stories from which we can pick the third one. But we don’t mind. We can optimistically write our extraction code using our safe_get function."
},
{
"code": null,
"e": 4984,
"s": 4916,
"text": "third_featured_story = safe_get(featured_stories, 2) # 0-index 👨🏿🏫"
},
{
"code": null,
"e": 5074,
"s": 4984,
"text": "If there is no third featured story, we’ll get back None from safe_get and be on our way."
},
{
"code": null,
"e": 5213,
"s": 5074,
"text": "Another great use for safe_get is as a building block function — for example, as seen in our implementation of the following dig function."
},
{
"code": null,
"e": 5474,
"s": 5213,
"text": "The dig function can be used to extract values from potentially nested dict and list data structures. It’s quite useful in data extraction and transformation because we often need to flatten nested data so that we can store it as structured data in a database."
},
{
"code": null,
"e": 5845,
"s": 5474,
"text": "I have spent the major of my time in data engineering (so far) using the Ruby programming language. Ruby has the Array#dig and Hash#dig methods, which make picking values from potentially nested dict and list data structures, in which values could be missing, quite easy. However, this functionality is not natively available in Python, so we have to build it ourselves."
},
{
"code": null,
"e": 5945,
"s": 5845,
"text": "Side note: A Python list corresponds to a Ruby Array, and a Python dict corresponds to a Ruby Hash."
},
{
"code": null,
"e": 6113,
"s": 5945,
"text": "Here is a reminder of what the implementation of our safe_get function looks like. We will be using it as a helper function in our implementation of dig which follows."
},
{
"code": null,
"e": 6201,
"s": 6113,
"text": "Now here is our implementation of the dig function using safe_get as a helper function."
},
{
"code": null,
"e": 6343,
"s": 6201,
"text": "We can once again update our code for extracting the URL of the highest resolution image for a story’s featured image using our dig function."
},
{
"code": null,
"e": 6504,
"s": 6343,
"text": "featured_image_url = coalesce( dig(story, \"image\", \"image_url_large\"), dig(story, \"image\", \"image_url_medium\"), dig(story, \"image\", \"image_url_small\"))"
},
{
"code": null,
"e": 6783,
"s": 6504,
"text": "But let us go a bit further. Take the following setup for instance. We have nested dict and list data, and as indicated by the types on the attributes of the MediumStory class, there are some attributes (marked as Optional) that we do not always expect values to be present for."
},
{
"code": null,
"e": 6879,
"s": 6783,
"text": "Now, let’s write some code to extract and flatten this nested story data into our Python class."
},
{
"code": null,
"e": 7061,
"s": 6879,
"text": "This function hardly needs a motivating example. It’s useful when we would prefer getting None (or some default value we set) if we fail to convert a value from one type to another."
},
{
"code": null,
"e": 7411,
"s": 7061,
"text": "One example that readily comes to mind is the conversion of a string value to a numeric value. Such a conversion would typically fail if unacceptable inputs such as empty string are provided, but with safe_cast we can suppress the exceptions and specify a default value if necessary. Examine the following code for how safe_cast might come in handy."
},
{
"code": null,
"e": 7529,
"s": 7411,
"text": "In this article, we looked at 4 Python functions that can help us safely extract or transform values from dirty data."
},
{
"code": null,
"e": 7612,
"s": 7529,
"text": "coalesce allows us to pick the first present (not-None) value among its arguments."
},
{
"code": null,
"e": 7723,
"s": 7612,
"text": "safe_get provides a unified interface that allows us to safely extract data from dict or list data structures."
},
{
"code": null,
"e": 7823,
"s": 7723,
"text": "dig lets us to reach into and extract values from potentially nested dict and list data structures."
},
{
"code": null,
"e": 7895,
"s": 7823,
"text": "safe_cast allows us to safely convert a value from one type to another."
},
{
"code": null,
"e": 8127,
"s": 7895,
"text": "Each of these functions is implemented in a way that minimizes the clutter of error handling logic by allowing us to pick a reasonable default return value (or None) in case we encounter a data extraction or transformation failure."
},
{
"code": null,
"e": 8349,
"s": 8127,
"text": "Additionally, they make it easy for us to extract data from the two most common data structures (dict and list), which are also what we get when we serialize JSON, the most popular data interchange format, for processing."
},
{
"code": null,
"e": 8372,
"s": 8349,
"text": "Thank you for reading!"
},
{
"code": null,
"e": 8409,
"s": 8372,
"text": "Python: One Problem, Several Lessons"
},
{
"code": null,
"e": 8452,
"s": 8409,
"text": "Improving Code Quality in Python Codebases"
},
{
"code": null,
"e": 8493,
"s": 8452,
"text": "How to recursively reverse a linked list"
},
{
"code": null,
"e": 8569,
"s": 8493,
"text": "Watch videos covering a variety of topics in Computing at OnelTalksTech.com"
},
{
"code": null,
"e": 8635,
"s": 8569,
"text": "StackOverflow user Artisom Rudzenk for the safe_cast code snippet"
}
] |
Python has a Built-in Database — Here’s How to use it | by Dario Radečić | Towards Data Science
|
Databases are a great, secure, and reliable way to store data. All major relational databases have something in common — SQL — a language to manipulate databases, tables, and data. SQL is a broad topic to cover, especially when dealing with different database vendors, such as Microsoft, IBM, or Oracle, so let’s start with SQLite — the most lightweight database system.
So, what is SQLite? I’m glad you’ve asked. It’s a library that provides us with a database or relational database management system. The term ‘Lite’ means ‘Lightweight,’ which means it’s light for setup and administration in the database world.
Why should I care? Because you can get a database experience without the need for downloading software or creating a cloud database, and then figuring out how to connect with Python. It’s not the most secure option, sure, but it still beats CSVs and Excel files by a large margin, because everyone can’t alter the data.
Today’s article is structured as follows:
Problem overview
Creating tables
Create, read, update, delete
Test time
Conclusion
So we’ll cover the basics — how to create tables, insert data, update data, delete data, fetch all data, and fetch data based on a condition. It’s everything you need to build applications.
Do you love movies? Yeah, me too. We’ll focus on just that today, by creating a database and a table to store movie titles and additional information. After we make the table, we’ll need to declare a couple of functions:
To insert movies
To get all movies
To get a single movie
To update a single movie
To delete a single movie
It sounds like a lot, but it isn’t. We’ll use Python to communicate with the SQLite database, and we’ll fetch movie info from IMDB.com.
Awesome! Let’s get started!
We can’t store data in the database directly — we need tables. Databases store tables and tables store data. Our procedure is as follows — create a movies table only if it doesn’t exist already. That will require two SQL queries, one to check if the table with a given name exists, and the other to create a table.
First, we need to import the SQLite library, establish a database connection, and create a cursor. The following snippet does it:
import sqlite3 conn = sqlite3.connect('movies.db') c = conn.cursor()
The movies.db database will get created if it doesn’t exist, and if it does, only a connection gets established.
Next, we’ll declare a function that checks if a table exists. The table name gets passed as a function parameter, and it returns True if the table exists, and False otherwise:
def table_exists(table_name): c.execute('''SELECT count(name) FROM sqlite_master WHERE TYPE = 'table' AND name = '{}' '''.format(table_name)) if c.fetchone()[0] == 1: return True return False
The newer f-strings don’t work for some reason, so we have to dial back to the older syntax — not an issue, but keep that in mind. The next step is to use the declared function to check if a table exists, and to create it if it doesn’t. The following snippet does it:
if not table_exists('movies'): c.execute(''' CREATE TABLE movies( movie_id INTEGER, name TEXT, release_year INTEGER, genre TEXT, rating REAL ) ''')
Awesome! This section ends here, and we’ll get to the fun stuff next.
Okay, we have everything configured, and now is the time to work with data. To start, we need a function that inserts a movie to the table (the Create part). It is quite an easy one to write, as we need to execute a single INSERT statement and commit the transaction. Here’s the code:
def insert_movie(movie_id, name, release_year, genre, rating): c.execute(''' INSERT INTO movies (movie_id, name, release_year, genre, rating) VALUES(?, ?, ?, ?, ?) ''', (movie_id, name, release_year, genre, rating)) conn.commit()
And that’s it! We’ll keep the testing part for later, and now we’ll continue with the Read part.
We’ll declare two functions here — first to get all movies and second to get only a single one, specified by the movie ID. You can easily condense the logic into a single function, but I’ve chosen to go with this approach.
Here’s the function for fetching all of the movies:
def get_movies(): c.execute('''SELECT * FROM movies''') data = [] for row in c.fetchall(): data.append(row) return data
And the snippet to fetch a single movie:
def get_movie(movie_id): c.execute('''SELECT * FROM movies WHERE movie_id = {}'''.format(movie_id)) data = [] for row in c.fetchall(): data.append(row) return data
Great! The Update part comes next. This one is trickier. We want to update elements according to a given movie ID, but what will we update? Do we declare a particular function for every field? That doesn’t sound right. We’ll perform the update with a dictionary.
Let me elaborate. Our update function will accept two parameters:
movie ID — the ID of a movie you want to update
update dictionary — key/value pairs to update
Keys in the update dictionary must be named according to the table columns, or the exception gets raised. Also, we need to handle the update of numeric and textual fields. It’s the trickiest function thus far, but you can handle it:
def update_movie(movie_id, update_dict): valid_keys = ['name', 'release_year', 'genre', 'rating'] for key in update_dict.keys(): if key not in valid_keys: raise Exception('Invalid field name!') for key in update_dict.keys(): if type(update_dict[key]) == str: stmt = '''UPDATE movies SET {} = '{}' WHERE movie_id = {}'''.format(key, update_dict[key], movie_id) else: stmt = '''UPDATE movies SET {} = '{}' WHERE movie_id = {}'''.format(key, update_dict[key], movie_id) c.execute(stmt) conn.commit()
See? It wasn’t that hard. Let’s finish with the Delete part. It is much simpler than the previous one, as we only need to execute a single statement and commit the transaction. Here’s the code:
def delete_movie(movie_id): c.execute('''DELETE FROM movies WHERE movie_id = {}'''.format(movie_id)) conn.commit()
And that concludes this part. We’ll test our functions next.
To start, let’s insert a couple of movies:
insert_movie(1, 'Titanic', 1997, 'Drama', 7.8) insert_movie(2, 'The Day After Tomorrow', 2004, 'Action', 6.4) insert_movie(3, '2012', 2009, 'Action', 5.8) insert_movie(4, 'Men in Black', 1997, 'Action', 7.3) insert_movie(5, 'World War Z', 2013, 'Romance', 10)
Executing these five lines doesn’t output anything to the console, which is expected — we’re only inserting data to the table. Next, we’ll use our predefined function to grab all movies:
print(get_movies())
Awesome! Let’s now get only a single movie:
print(get_movie(2))
That was pretty easy. Now we’ll see how to update a movie. The last one inserted, World War Z, was intentionally given a rating of 10 and a Romance genre, so let’s change that:
update_movie(5, {'genre': 'Horror', 'rating': 7.0})
Now things make sense. The only thing left to do is to delete a movie — let’s see how to do that:
delete_movie(3)
That doesn’t return anything — as expected. We can quickly get all of the movies to see if the delete function works:
And that does it — everything works as advertised. Let’s wrap things up in the next section.
I hope it was easy to follow along. We covered the basics and left a lot of things untouched. It’s still enough to build basic, database-driven applications or APIs, but more on APIs some other time.
Feel free to expand this, add new functions or tables, or to improve overall code quality.
Thanks for reading.
Join my private email list for more helpful insights.
Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you.
medium.com
Originally published at https://betterdatascience.com on October 1, 2020.
|
[
{
"code": null,
"e": 542,
"s": 171,
"text": "Databases are a great, secure, and reliable way to store data. All major relational databases have something in common — SQL — a language to manipulate databases, tables, and data. SQL is a broad topic to cover, especially when dealing with different database vendors, such as Microsoft, IBM, or Oracle, so let’s start with SQLite — the most lightweight database system."
},
{
"code": null,
"e": 787,
"s": 542,
"text": "So, what is SQLite? I’m glad you’ve asked. It’s a library that provides us with a database or relational database management system. The term ‘Lite’ means ‘Lightweight,’ which means it’s light for setup and administration in the database world."
},
{
"code": null,
"e": 1107,
"s": 787,
"text": "Why should I care? Because you can get a database experience without the need for downloading software or creating a cloud database, and then figuring out how to connect with Python. It’s not the most secure option, sure, but it still beats CSVs and Excel files by a large margin, because everyone can’t alter the data."
},
{
"code": null,
"e": 1149,
"s": 1107,
"text": "Today’s article is structured as follows:"
},
{
"code": null,
"e": 1166,
"s": 1149,
"text": "Problem overview"
},
{
"code": null,
"e": 1182,
"s": 1166,
"text": "Creating tables"
},
{
"code": null,
"e": 1211,
"s": 1182,
"text": "Create, read, update, delete"
},
{
"code": null,
"e": 1221,
"s": 1211,
"text": "Test time"
},
{
"code": null,
"e": 1232,
"s": 1221,
"text": "Conclusion"
},
{
"code": null,
"e": 1422,
"s": 1232,
"text": "So we’ll cover the basics — how to create tables, insert data, update data, delete data, fetch all data, and fetch data based on a condition. It’s everything you need to build applications."
},
{
"code": null,
"e": 1643,
"s": 1422,
"text": "Do you love movies? Yeah, me too. We’ll focus on just that today, by creating a database and a table to store movie titles and additional information. After we make the table, we’ll need to declare a couple of functions:"
},
{
"code": null,
"e": 1660,
"s": 1643,
"text": "To insert movies"
},
{
"code": null,
"e": 1678,
"s": 1660,
"text": "To get all movies"
},
{
"code": null,
"e": 1700,
"s": 1678,
"text": "To get a single movie"
},
{
"code": null,
"e": 1725,
"s": 1700,
"text": "To update a single movie"
},
{
"code": null,
"e": 1750,
"s": 1725,
"text": "To delete a single movie"
},
{
"code": null,
"e": 1886,
"s": 1750,
"text": "It sounds like a lot, but it isn’t. We’ll use Python to communicate with the SQLite database, and we’ll fetch movie info from IMDB.com."
},
{
"code": null,
"e": 1914,
"s": 1886,
"text": "Awesome! Let’s get started!"
},
{
"code": null,
"e": 2229,
"s": 1914,
"text": "We can’t store data in the database directly — we need tables. Databases store tables and tables store data. Our procedure is as follows — create a movies table only if it doesn’t exist already. That will require two SQL queries, one to check if the table with a given name exists, and the other to create a table."
},
{
"code": null,
"e": 2359,
"s": 2229,
"text": "First, we need to import the SQLite library, establish a database connection, and create a cursor. The following snippet does it:"
},
{
"code": null,
"e": 2428,
"s": 2359,
"text": "import sqlite3 conn = sqlite3.connect('movies.db') c = conn.cursor()"
},
{
"code": null,
"e": 2541,
"s": 2428,
"text": "The movies.db database will get created if it doesn’t exist, and if it does, only a connection gets established."
},
{
"code": null,
"e": 2717,
"s": 2541,
"text": "Next, we’ll declare a function that checks if a table exists. The table name gets passed as a function parameter, and it returns True if the table exists, and False otherwise:"
},
{
"code": null,
"e": 2929,
"s": 2717,
"text": "def table_exists(table_name): c.execute('''SELECT count(name) FROM sqlite_master WHERE TYPE = 'table' AND name = '{}' '''.format(table_name)) if c.fetchone()[0] == 1: return True return False"
},
{
"code": null,
"e": 3197,
"s": 2929,
"text": "The newer f-strings don’t work for some reason, so we have to dial back to the older syntax — not an issue, but keep that in mind. The next step is to use the declared function to check if a table exists, and to create it if it doesn’t. The following snippet does it:"
},
{
"code": null,
"e": 3429,
"s": 3197,
"text": "if not table_exists('movies'): c.execute(''' CREATE TABLE movies( movie_id INTEGER, name TEXT, release_year INTEGER, genre TEXT, rating REAL ) ''')"
},
{
"code": null,
"e": 3499,
"s": 3429,
"text": "Awesome! This section ends here, and we’ll get to the fun stuff next."
},
{
"code": null,
"e": 3784,
"s": 3499,
"text": "Okay, we have everything configured, and now is the time to work with data. To start, we need a function that inserts a movie to the table (the Create part). It is quite an easy one to write, as we need to execute a single INSERT statement and commit the transaction. Here’s the code:"
},
{
"code": null,
"e": 4022,
"s": 3784,
"text": "def insert_movie(movie_id, name, release_year, genre, rating): c.execute(''' INSERT INTO movies (movie_id, name, release_year, genre, rating) VALUES(?, ?, ?, ?, ?) ''', (movie_id, name, release_year, genre, rating)) conn.commit()"
},
{
"code": null,
"e": 4119,
"s": 4022,
"text": "And that’s it! We’ll keep the testing part for later, and now we’ll continue with the Read part."
},
{
"code": null,
"e": 4342,
"s": 4119,
"text": "We’ll declare two functions here — first to get all movies and second to get only a single one, specified by the movie ID. You can easily condense the logic into a single function, but I’ve chosen to go with this approach."
},
{
"code": null,
"e": 4394,
"s": 4342,
"text": "Here’s the function for fetching all of the movies:"
},
{
"code": null,
"e": 4538,
"s": 4394,
"text": "def get_movies(): c.execute('''SELECT * FROM movies''') data = [] for row in c.fetchall(): data.append(row) return data"
},
{
"code": null,
"e": 4579,
"s": 4538,
"text": "And the snippet to fetch a single movie:"
},
{
"code": null,
"e": 4768,
"s": 4579,
"text": "def get_movie(movie_id): c.execute('''SELECT * FROM movies WHERE movie_id = {}'''.format(movie_id)) data = [] for row in c.fetchall(): data.append(row) return data"
},
{
"code": null,
"e": 5031,
"s": 4768,
"text": "Great! The Update part comes next. This one is trickier. We want to update elements according to a given movie ID, but what will we update? Do we declare a particular function for every field? That doesn’t sound right. We’ll perform the update with a dictionary."
},
{
"code": null,
"e": 5097,
"s": 5031,
"text": "Let me elaborate. Our update function will accept two parameters:"
},
{
"code": null,
"e": 5145,
"s": 5097,
"text": "movie ID — the ID of a movie you want to update"
},
{
"code": null,
"e": 5191,
"s": 5145,
"text": "update dictionary — key/value pairs to update"
},
{
"code": null,
"e": 5424,
"s": 5191,
"text": "Keys in the update dictionary must be named according to the table columns, or the exception gets raised. Also, we need to handle the update of numeric and textual fields. It’s the trickiest function thus far, but you can handle it:"
},
{
"code": null,
"e": 6006,
"s": 5424,
"text": "def update_movie(movie_id, update_dict): valid_keys = ['name', 'release_year', 'genre', 'rating'] for key in update_dict.keys(): if key not in valid_keys: raise Exception('Invalid field name!') for key in update_dict.keys(): if type(update_dict[key]) == str: stmt = '''UPDATE movies SET {} = '{}' WHERE movie_id = {}'''.format(key, update_dict[key], movie_id) else: stmt = '''UPDATE movies SET {} = '{}' WHERE movie_id = {}'''.format(key, update_dict[key], movie_id) c.execute(stmt) conn.commit()"
},
{
"code": null,
"e": 6200,
"s": 6006,
"text": "See? It wasn’t that hard. Let’s finish with the Delete part. It is much simpler than the previous one, as we only need to execute a single statement and commit the transaction. Here’s the code:"
},
{
"code": null,
"e": 6323,
"s": 6200,
"text": "def delete_movie(movie_id): c.execute('''DELETE FROM movies WHERE movie_id = {}'''.format(movie_id)) conn.commit()"
},
{
"code": null,
"e": 6384,
"s": 6323,
"text": "And that concludes this part. We’ll test our functions next."
},
{
"code": null,
"e": 6427,
"s": 6384,
"text": "To start, let’s insert a couple of movies:"
},
{
"code": null,
"e": 6687,
"s": 6427,
"text": "insert_movie(1, 'Titanic', 1997, 'Drama', 7.8) insert_movie(2, 'The Day After Tomorrow', 2004, 'Action', 6.4) insert_movie(3, '2012', 2009, 'Action', 5.8) insert_movie(4, 'Men in Black', 1997, 'Action', 7.3) insert_movie(5, 'World War Z', 2013, 'Romance', 10)"
},
{
"code": null,
"e": 6874,
"s": 6687,
"text": "Executing these five lines doesn’t output anything to the console, which is expected — we’re only inserting data to the table. Next, we’ll use our predefined function to grab all movies:"
},
{
"code": null,
"e": 6894,
"s": 6874,
"text": "print(get_movies())"
},
{
"code": null,
"e": 6938,
"s": 6894,
"text": "Awesome! Let’s now get only a single movie:"
},
{
"code": null,
"e": 6958,
"s": 6938,
"text": "print(get_movie(2))"
},
{
"code": null,
"e": 7135,
"s": 6958,
"text": "That was pretty easy. Now we’ll see how to update a movie. The last one inserted, World War Z, was intentionally given a rating of 10 and a Romance genre, so let’s change that:"
},
{
"code": null,
"e": 7187,
"s": 7135,
"text": "update_movie(5, {'genre': 'Horror', 'rating': 7.0})"
},
{
"code": null,
"e": 7285,
"s": 7187,
"text": "Now things make sense. The only thing left to do is to delete a movie — let’s see how to do that:"
},
{
"code": null,
"e": 7301,
"s": 7285,
"text": "delete_movie(3)"
},
{
"code": null,
"e": 7419,
"s": 7301,
"text": "That doesn’t return anything — as expected. We can quickly get all of the movies to see if the delete function works:"
},
{
"code": null,
"e": 7512,
"s": 7419,
"text": "And that does it — everything works as advertised. Let’s wrap things up in the next section."
},
{
"code": null,
"e": 7712,
"s": 7512,
"text": "I hope it was easy to follow along. We covered the basics and left a lot of things untouched. It’s still enough to build basic, database-driven applications or APIs, but more on APIs some other time."
},
{
"code": null,
"e": 7803,
"s": 7712,
"text": "Feel free to expand this, add new functions or tables, or to improve overall code quality."
},
{
"code": null,
"e": 7823,
"s": 7803,
"text": "Thanks for reading."
},
{
"code": null,
"e": 7877,
"s": 7823,
"text": "Join my private email list for more helpful insights."
},
{
"code": null,
"e": 8060,
"s": 7877,
"text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you."
},
{
"code": null,
"e": 8071,
"s": 8060,
"text": "medium.com"
}
] |
Google Maps - UI Controls
|
Google Maps provides a User Interface with various controls to let the user interact with the map. We can add, customize, and disable these controls.
Here is a list of the default controls provided by Google Maps −
Zoom − To increase and decease the zoom level of the map, we will have a slider with + and − buttons, by default. This slider will be located at the corner of left hand side of the map.
Zoom − To increase and decease the zoom level of the map, we will have a slider with + and − buttons, by default. This slider will be located at the corner of left hand side of the map.
Pan − Just above the zoom slider, there will be a pan control for panning the map.
Pan − Just above the zoom slider, there will be a pan control for panning the map.
Map Type − You can locate this control at the top right corner of the map. It provides map type options such as Satellite, Roadmap, and Terrain. Users can choose any of these maps.
Map Type − You can locate this control at the top right corner of the map. It provides map type options such as Satellite, Roadmap, and Terrain. Users can choose any of these maps.
Street view − Between the pan icon and the zoom slider, we have a pegman icon. Users can drag this icon and place at a particular location to get its street view.
Street view − Between the pan icon and the zoom slider, we have a pegman icon. Users can drag this icon and place at a particular location to get its street view.
Here is an example where you can observe the default UI controls provided by Google Maps −
We can disable the default UI controls provided by Google Maps simply by making the disableDefaultUI value true in the map options.
The following example shows how to disable the default UI controls provided by Google Maps.
<!DOCTYPE html>
<html>
<head>
<script src = "https://maps.googleapis.com/maps/api/js"></script>
<script>
function loadMap() {
var mapOptions = {
center:new google.maps.LatLng(17.609993, 83.221436),
zoom:5,
mapTypeId:google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true
};
var map = new google.maps.Map(document.getElementById("sample"),mapOptions);
}
</script>
</head>
<body onload = "loadMap()">
<div id = "sample" style = "width:580px; height:400px;"></div>
</body>
</html>
It will produce the following output −
In addition to these default controls, Google Maps also provides three more controls as listed below.
Scale − The Scale control displays a map scale element. This control is not enabled by default.
Scale − The Scale control displays a map scale element. This control is not enabled by default.
Rotate − The Rotate control contains a small circular icon which allows you to rotate maps containing oblique imagery. This control appears by default at the top left corner of the map. (See 45° Imagery for more information.)
Rotate − The Rotate control contains a small circular icon which allows you to rotate maps containing oblique imagery. This control appears by default at the top left corner of the map. (See 45° Imagery for more information.)
Overview − To increase and decease the zoom level of the map, we have a slider with + and − buttons, by default. This slider is located at the left corner of the map.
Overview − To increase and decease the zoom level of the map, we have a slider with + and − buttons, by default. This slider is located at the left corner of the map.
In the map options, we can enable and disable any of the controls provided by Google Maps as shown below −
{
panControl: boolean,
zoomControl: boolean,
mapTypeControl: boolean,
scaleControl: boolean,
streetViewControl: boolean,
overviewMapControl: boolean
}
The following code shows how to enable all the controls −
<!DOCTYPE html>
<html>
<head>
<script src = "https://maps.googleapis.com/maps/api/js"></script>
<script>
function loadMap() {
var mapOptions = {
center:new google.maps.LatLng(19.373341, 78.662109),
zoom:5,
panControl: true,
zoomControl: true,
scaleControl: true,
mapTypeControl:true,
streetViewControl:true,
overviewMapControl:true,
rotateControl:true
}
var map = new google.maps.Map(document.getElementById("sample"),mapOptions);
}
</script>
</head>
<body onload = "loadMap()">
<div id = "sample" style = "width:580px; height:400px;"></div>
</body>
</html>
It will produce the following output −
We can change the appearance of Google Maps controls using its control options. For example, the zoom control can be either reduced or enlarged in size. The MapType control appearance can be varied to a horizontal bar or a drop-down menu. Given below is a list of Control options for Zoom and MapType controls.
google.maps.ZoomControlStyle.SMALL
google.maps.ZoomControlStyle.LARGE
google.maps.ZoomControlStyle.DEFAULT
google.maps.MapTypeControlStyle.HORIZONTAL_BAR
google.maps.MapTypeControlStyle.DROPDOWN_MENU
google.maps.MapTypeControlStyle.DEFAULT
The following example demonstrates how to use the control options −
<!DOCTYPE html>
<html>
<head>
<script src = "https://maps.googleapis.com/maps/api/js"></script>
<script>
function loadMap() {
var mapOptions = {
center:new google.maps.LatLng(19.373341, 78.662109),
zoom:5,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU, mapTypeIds: [
google.maps.MapTypeId.ROADMAP,
google.maps.MapTypeId.TERRAIN
]
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
}
}
var map = new google.maps.Map(document.getElementById("sample"),mapOptions);
}
</script>
</head>
<body onload = "loadMap()">
<div id = "sample" style = "width:580px; height:400px;"></div>
</body>
</html>
It produces the following output −
You can change the position of the controls by adding the following line in the control options.
position:google.maps.ControlPosition.Desired_Position,
Here is the list of available positions where a control can be placed on a map −
TOP_CENTER
TOP_LEFT
TOP_RIGHT
LEFT_TOP
RIGHT_TOP
LEFT_CENTER
RIGHT_CENTER
LEFT_BOTTOM
RIGHT_BOTTOM
BOTTOM_CENTER
BOTTOM_LEFT
BOTTOM_RIGHT
The following example shows how to place the MapTypeid control at the top centre of the map and how to place the zoom control at the bottom centre of the map.
<!DOCTYPE html>
<html>
<head>
<script src = "https://maps.googleapis.com/maps/api/js"></script>
<script>
function loadMap() {
var mapOptions = {
center:new google.maps.LatLng(19.373341, 78.662109),
zoom:5,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
position:google.maps.ControlPosition.TOP_CENTER,
mapTypeIds: [
google.maps.MapTypeId.ROADMAP,
google.maps.MapTypeId.TERRAIN
]
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL,
position:google.maps.ControlPosition.BOTTOM_CENTER
}
}
var map = new google.maps.Map(document.getElementById("sample"),mapOptions);
}
</script>
</head>
<body onload = "loadMap()">
<div id = "sample" style = "width:580px; height:400px;"></div>
</body>
</html>
It produces the following output −
20 Lectures
2.5 hours
Asif Hussain
7 Lectures
1 hours
Aditya Kulkarni
33 Lectures
2.5 hours
Sasha Miller
22 Lectures
1.5 hours
Zach Miller
16 Lectures
1.5 hours
Sasha Miller
23 Lectures
2.5 hours
Sasha Miller
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1982,
"s": 1832,
"text": "Google Maps provides a User Interface with various controls to let the user interact with the map. We can add, customize, and disable these controls."
},
{
"code": null,
"e": 2047,
"s": 1982,
"text": "Here is a list of the default controls provided by Google Maps −"
},
{
"code": null,
"e": 2233,
"s": 2047,
"text": "Zoom − To increase and decease the zoom level of the map, we will have a slider with + and − buttons, by default. This slider will be located at the corner of left hand side of the map."
},
{
"code": null,
"e": 2419,
"s": 2233,
"text": "Zoom − To increase and decease the zoom level of the map, we will have a slider with + and − buttons, by default. This slider will be located at the corner of left hand side of the map."
},
{
"code": null,
"e": 2502,
"s": 2419,
"text": "Pan − Just above the zoom slider, there will be a pan control for panning the map."
},
{
"code": null,
"e": 2585,
"s": 2502,
"text": "Pan − Just above the zoom slider, there will be a pan control for panning the map."
},
{
"code": null,
"e": 2766,
"s": 2585,
"text": "Map Type − You can locate this control at the top right corner of the map. It provides map type options such as Satellite, Roadmap, and Terrain. Users can choose any of these maps."
},
{
"code": null,
"e": 2947,
"s": 2766,
"text": "Map Type − You can locate this control at the top right corner of the map. It provides map type options such as Satellite, Roadmap, and Terrain. Users can choose any of these maps."
},
{
"code": null,
"e": 3110,
"s": 2947,
"text": "Street view − Between the pan icon and the zoom slider, we have a pegman icon. Users can drag this icon and place at a particular location to get its street view."
},
{
"code": null,
"e": 3273,
"s": 3110,
"text": "Street view − Between the pan icon and the zoom slider, we have a pegman icon. Users can drag this icon and place at a particular location to get its street view."
},
{
"code": null,
"e": 3364,
"s": 3273,
"text": "Here is an example where you can observe the default UI controls provided by Google Maps −"
},
{
"code": null,
"e": 3496,
"s": 3364,
"text": "We can disable the default UI controls provided by Google Maps simply by making the disableDefaultUI value true in the map options."
},
{
"code": null,
"e": 3588,
"s": 3496,
"text": "The following example shows how to disable the default UI controls provided by Google Maps."
},
{
"code": null,
"e": 4247,
"s": 3588,
"text": "<!DOCTYPE html>\n<html>\n \n <head>\n <script src = \"https://maps.googleapis.com/maps/api/js\"></script>\n \n <script>\n function loadMap() {\n\t\t\t\n var mapOptions = {\n center:new google.maps.LatLng(17.609993, 83.221436),\n zoom:5,\n mapTypeId:google.maps.MapTypeId.ROADMAP,\n disableDefaultUI: true\n };\n\t\t\t\t\n var map = new google.maps.Map(document.getElementById(\"sample\"),mapOptions);\n }\n </script>\n \n </head>\n \n <body onload = \"loadMap()\">\n <div id = \"sample\" style = \"width:580px; height:400px;\"></div>\n </body>\n\n</html>"
},
{
"code": null,
"e": 4286,
"s": 4247,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 4388,
"s": 4286,
"text": "In addition to these default controls, Google Maps also provides three more controls as listed below."
},
{
"code": null,
"e": 4484,
"s": 4388,
"text": "Scale − The Scale control displays a map scale element. This control is not enabled by default."
},
{
"code": null,
"e": 4580,
"s": 4484,
"text": "Scale − The Scale control displays a map scale element. This control is not enabled by default."
},
{
"code": null,
"e": 4806,
"s": 4580,
"text": "Rotate − The Rotate control contains a small circular icon which allows you to rotate maps containing oblique imagery. This control appears by default at the top left corner of the map. (See 45° Imagery for more information.)"
},
{
"code": null,
"e": 5032,
"s": 4806,
"text": "Rotate − The Rotate control contains a small circular icon which allows you to rotate maps containing oblique imagery. This control appears by default at the top left corner of the map. (See 45° Imagery for more information.)"
},
{
"code": null,
"e": 5199,
"s": 5032,
"text": "Overview − To increase and decease the zoom level of the map, we have a slider with + and − buttons, by default. This slider is located at the left corner of the map."
},
{
"code": null,
"e": 5366,
"s": 5199,
"text": "Overview − To increase and decease the zoom level of the map, we have a slider with + and − buttons, by default. This slider is located at the left corner of the map."
},
{
"code": null,
"e": 5473,
"s": 5366,
"text": "In the map options, we can enable and disable any of the controls provided by Google Maps as shown below −"
},
{
"code": null,
"e": 5642,
"s": 5473,
"text": "{\n panControl: boolean,\n zoomControl: boolean,\n mapTypeControl: boolean,\n scaleControl: boolean,\n streetViewControl: boolean,\n overviewMapControl: boolean\n}"
},
{
"code": null,
"e": 5700,
"s": 5642,
"text": "The following code shows how to enable all the controls −"
},
{
"code": null,
"e": 6515,
"s": 5700,
"text": "<!DOCTYPE html>\n<html>\n \n <head>\n <script src = \"https://maps.googleapis.com/maps/api/js\"></script>\n \n <script>\n function loadMap() {\n\t\t\t\n var mapOptions = {\n center:new google.maps.LatLng(19.373341, 78.662109),\n zoom:5,\n panControl: true,\n zoomControl: true,\n scaleControl: true,\n mapTypeControl:true,\n streetViewControl:true,\n overviewMapControl:true,\n rotateControl:true\n }\n\t\t\t\t\n var map = new google.maps.Map(document.getElementById(\"sample\"),mapOptions);\n }\n </script>\n \n </head>\n \n <body onload = \"loadMap()\">\n <div id = \"sample\" style = \"width:580px; height:400px;\"></div>\n </body>\n\n</html>"
},
{
"code": null,
"e": 6554,
"s": 6515,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 6865,
"s": 6554,
"text": "We can change the appearance of Google Maps controls using its control options. For example, the zoom control can be either reduced or enlarged in size. The MapType control appearance can be varied to a horizontal bar or a drop-down menu. Given below is a list of Control options for Zoom and MapType controls."
},
{
"code": null,
"e": 6900,
"s": 6865,
"text": "google.maps.ZoomControlStyle.SMALL"
},
{
"code": null,
"e": 6935,
"s": 6900,
"text": "google.maps.ZoomControlStyle.LARGE"
},
{
"code": null,
"e": 6972,
"s": 6935,
"text": "google.maps.ZoomControlStyle.DEFAULT"
},
{
"code": null,
"e": 7019,
"s": 6972,
"text": "google.maps.MapTypeControlStyle.HORIZONTAL_BAR"
},
{
"code": null,
"e": 7065,
"s": 7019,
"text": "google.maps.MapTypeControlStyle.DROPDOWN_MENU"
},
{
"code": null,
"e": 7105,
"s": 7065,
"text": "google.maps.MapTypeControlStyle.DEFAULT"
},
{
"code": null,
"e": 7173,
"s": 7105,
"text": "The following example demonstrates how to use the control options −"
},
{
"code": null,
"e": 8230,
"s": 7173,
"text": "<!DOCTYPE html>\n<html>\n \n <head>\n <script src = \"https://maps.googleapis.com/maps/api/js\"></script>\n \n <script>\n function loadMap() {\n\t\t\t\n var mapOptions = {\n center:new google.maps.LatLng(19.373341, 78.662109),\n zoom:5,\n mapTypeControl: true,\n \n mapTypeControlOptions: {\n style: google.maps.MapTypeControlStyle.DROPDOWN_MENU, mapTypeIds: [\n google.maps.MapTypeId.ROADMAP,\n google.maps.MapTypeId.TERRAIN\n ]\n },\n\t\t\t\t\t\n zoomControl: true,\n \n zoomControlOptions: {\n style: google.maps.ZoomControlStyle.SMALL\n }\n }\n\t\t\t\t\n var map = new google.maps.Map(document.getElementById(\"sample\"),mapOptions);\n }\n </script>\n \n </head>\n \n <body onload = \"loadMap()\">\n <div id = \"sample\" style = \"width:580px; height:400px;\"></div>\n </body>\n \n</html>"
},
{
"code": null,
"e": 8265,
"s": 8230,
"text": "It produces the following output −"
},
{
"code": null,
"e": 8362,
"s": 8265,
"text": "You can change the position of the controls by adding the following line in the control options."
},
{
"code": null,
"e": 8418,
"s": 8362,
"text": "position:google.maps.ControlPosition.Desired_Position,\n"
},
{
"code": null,
"e": 8499,
"s": 8418,
"text": "Here is the list of available positions where a control can be placed on a map −"
},
{
"code": null,
"e": 8510,
"s": 8499,
"text": "TOP_CENTER"
},
{
"code": null,
"e": 8519,
"s": 8510,
"text": "TOP_LEFT"
},
{
"code": null,
"e": 8529,
"s": 8519,
"text": "TOP_RIGHT"
},
{
"code": null,
"e": 8538,
"s": 8529,
"text": "LEFT_TOP"
},
{
"code": null,
"e": 8548,
"s": 8538,
"text": "RIGHT_TOP"
},
{
"code": null,
"e": 8560,
"s": 8548,
"text": "LEFT_CENTER"
},
{
"code": null,
"e": 8573,
"s": 8560,
"text": "RIGHT_CENTER"
},
{
"code": null,
"e": 8585,
"s": 8573,
"text": "LEFT_BOTTOM"
},
{
"code": null,
"e": 8598,
"s": 8585,
"text": "RIGHT_BOTTOM"
},
{
"code": null,
"e": 8612,
"s": 8598,
"text": "BOTTOM_CENTER"
},
{
"code": null,
"e": 8624,
"s": 8612,
"text": "BOTTOM_LEFT"
},
{
"code": null,
"e": 8637,
"s": 8624,
"text": "BOTTOM_RIGHT"
},
{
"code": null,
"e": 8796,
"s": 8637,
"text": "The following example shows how to place the MapTypeid control at the top centre of the map and how to place the zoom control at the bottom centre of the map."
},
{
"code": null,
"e": 10028,
"s": 8796,
"text": "<!DOCTYPE html>\n<html>\n \n <head>\n <script src = \"https://maps.googleapis.com/maps/api/js\"></script>\n \n <script>\n function loadMap() {\n\t\t\t\n var mapOptions = {\n center:new google.maps.LatLng(19.373341, 78.662109),\n zoom:5,\n mapTypeControl: true,\n \n mapTypeControlOptions: {\n style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,\n position:google.maps.ControlPosition.TOP_CENTER,\n \n mapTypeIds: [\n google.maps.MapTypeId.ROADMAP,\n google.maps.MapTypeId.TERRAIN\n ]\n },\n\t\t\t\t\t\n zoomControl: true,\n \n zoomControlOptions: {\n style: google.maps.ZoomControlStyle.SMALL,\n position:google.maps.ControlPosition.BOTTOM_CENTER\n }\n }\n\t\t\t\t\n var map = new google.maps.Map(document.getElementById(\"sample\"),mapOptions);\n }\n </script>\n \n </head>\n \n <body onload = \"loadMap()\">\n <div id = \"sample\" style = \"width:580px; height:400px;\"></div>\n </body>\n \n</html> "
},
{
"code": null,
"e": 10063,
"s": 10028,
"text": "It produces the following output −"
},
{
"code": null,
"e": 10098,
"s": 10063,
"text": "\n 20 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 10112,
"s": 10098,
"text": " Asif Hussain"
},
{
"code": null,
"e": 10144,
"s": 10112,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 10161,
"s": 10144,
"text": " Aditya Kulkarni"
},
{
"code": null,
"e": 10196,
"s": 10161,
"text": "\n 33 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 10210,
"s": 10196,
"text": " Sasha Miller"
},
{
"code": null,
"e": 10245,
"s": 10210,
"text": "\n 22 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 10258,
"s": 10245,
"text": " Zach Miller"
},
{
"code": null,
"e": 10293,
"s": 10258,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 10307,
"s": 10293,
"text": " Sasha Miller"
},
{
"code": null,
"e": 10342,
"s": 10307,
"text": "\n 23 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 10356,
"s": 10342,
"text": " Sasha Miller"
},
{
"code": null,
"e": 10363,
"s": 10356,
"text": " Print"
},
{
"code": null,
"e": 10374,
"s": 10363,
"text": " Add Notes"
}
] |
C++ Fstream Library - is_open Function
|
Returns whether the stream is currently associated to a file. If streams can be associated to files by a successful call to member open or directly on construction, and disassociated by calling close or on destruction. The file association of a stream is kept by its internal stream buffer: Internally, then the function calls rdbuf()->is_open().
Following is the declaration for fstream::is_open.
bool is_open();
bool is_open() const;
It returns true, if a file is open and associated with this stream object or else returns false.
Strong guarantee − if an exception is thrown, there are no changes in the stream.
Accesses the fstream object.
Accesses the fstream object.
Concurrent access to the same stream may introduce data races.
Concurrent access to the same stream may introduce data races.
In below example explains about fstream is_open function.
#include <iostream>
#include <fstream>
int main () {
std::fstream fs;
fs.open ("test.txt");
if (fs.is_open()) {
fs << "lorem ipsum";
std::cout << "Operation successfully performed\n";
fs.close();
} else {
std::cout << "Error opening file";
}
return 0;
}
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2950,
"s": 2603,
"text": "Returns whether the stream is currently associated to a file. If streams can be associated to files by a successful call to member open or directly on construction, and disassociated by calling close or on destruction. The file association of a stream is kept by its internal stream buffer: Internally, then the function calls rdbuf()->is_open()."
},
{
"code": null,
"e": 3001,
"s": 2950,
"text": "Following is the declaration for fstream::is_open."
},
{
"code": null,
"e": 3017,
"s": 3001,
"text": "bool is_open();"
},
{
"code": null,
"e": 3039,
"s": 3017,
"text": "bool is_open() const;"
},
{
"code": null,
"e": 3136,
"s": 3039,
"text": "It returns true, if a file is open and associated with this stream object or else returns false."
},
{
"code": null,
"e": 3218,
"s": 3136,
"text": "Strong guarantee − if an exception is thrown, there are no changes in the stream."
},
{
"code": null,
"e": 3247,
"s": 3218,
"text": "Accesses the fstream object."
},
{
"code": null,
"e": 3276,
"s": 3247,
"text": "Accesses the fstream object."
},
{
"code": null,
"e": 3339,
"s": 3276,
"text": "Concurrent access to the same stream may introduce data races."
},
{
"code": null,
"e": 3402,
"s": 3339,
"text": "Concurrent access to the same stream may introduce data races."
},
{
"code": null,
"e": 3460,
"s": 3402,
"text": "In below example explains about fstream is_open function."
},
{
"code": null,
"e": 3768,
"s": 3460,
"text": "#include <iostream> \n#include <fstream> \n\nint main () {\n std::fstream fs;\n fs.open (\"test.txt\");\n if (fs.is_open()) {\n fs << \"lorem ipsum\";\n std::cout << \"Operation successfully performed\\n\";\n fs.close();\n } else {\n std::cout << \"Error opening file\";\n }\n return 0;\n}"
},
{
"code": null,
"e": 3775,
"s": 3768,
"text": " Print"
},
{
"code": null,
"e": 3786,
"s": 3775,
"text": " Add Notes"
}
] |
How do I stop a MySQL decimal field from being rounded?
|
You can stop rounding decimal field with the help of DECIMAL() function. Here is the demo of a rounded decimal field. For our example, let us first create a demo table
mysql> create table stopRoundingDemo
-> (
-> Amount DECIMAL(7)
-> );
Query OK, 0 rows affected (0.67 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into stopRoundingDemo values(7836.783);
Query OK, 1 row affected, 1 warning (0.43 sec)
mysql> insert into stopRoundingDemo values(1737.67);
Query OK, 1 row affected, 1 warning (0.23 sec)
mysql> insert into stopRoundingDemo values(110.50);
Query OK, 1 row affected, 1 warning (0.33 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from stopRoundingDemo;
The following is the output
+--------+
| Amount |
+--------+
| 7837 |
| 1738 |
| 111 |
+--------+
3 rows in set (0.08 sec)
In the above sample output, the decimal is rounded.
Now, we will see how to stop decimal being rounded. For that, let us first create a new table and set the DECIMAL type in a way that would give the result without round off
mysql> create table stopRoundingDemo2
-> (
-> Amount DECIMAL(10,4)
-> );
Query OK, 0 rows affected (0.81 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into stopRoundingDemo2 values(7836.783);
Query OK, 1 row affected (0.14 sec)
mysql> insert into stopRoundingDemo2 values(1737.67);
Query OK, 1 row affected (0.14 sec)
mysql> insert into stopRoundingDemo2 values(110.50);
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from stopRoundingDemo2;
The output is as follows
+-----------+
| Amount |
+-----------+
| 7836.7830 |
| 1737.6700 |
| 110.5000 |
+-----------+
3 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1230,
"s": 1062,
"text": "You can stop rounding decimal field with the help of DECIMAL() function. Here is the demo of a rounded decimal field. For our example, let us first create a demo table"
},
{
"code": null,
"e": 1345,
"s": 1230,
"text": "mysql> create table stopRoundingDemo\n -> (\n -> Amount DECIMAL(7)\n -> );\nQuery OK, 0 rows affected (0.67 sec)"
},
{
"code": null,
"e": 1426,
"s": 1345,
"text": "Insert some records in the table using insert command. The query is as follows −"
},
{
"code": null,
"e": 1726,
"s": 1426,
"text": "mysql> insert into stopRoundingDemo values(7836.783);\nQuery OK, 1 row affected, 1 warning (0.43 sec)\nmysql> insert into stopRoundingDemo values(1737.67);\nQuery OK, 1 row affected, 1 warning (0.23 sec)\nmysql> insert into stopRoundingDemo values(110.50);\nQuery OK, 1 row affected, 1 warning (0.33 sec)"
},
{
"code": null,
"e": 1811,
"s": 1726,
"text": "Display all records from the table using select statement. The query is as follows −"
},
{
"code": null,
"e": 1849,
"s": 1811,
"text": "mysql> select *from stopRoundingDemo;"
},
{
"code": null,
"e": 1877,
"s": 1849,
"text": "The following is the output"
},
{
"code": null,
"e": 1979,
"s": 1877,
"text": "+--------+\n| Amount |\n+--------+\n| 7837 |\n| 1738 |\n| 111 |\n+--------+\n3 rows in set (0.08 sec)"
},
{
"code": null,
"e": 2031,
"s": 1979,
"text": "In the above sample output, the decimal is rounded."
},
{
"code": null,
"e": 2204,
"s": 2031,
"text": "Now, we will see how to stop decimal being rounded. For that, let us first create a new table and set the DECIMAL type in a way that would give the result without round off"
},
{
"code": null,
"e": 2323,
"s": 2204,
"text": "mysql> create table stopRoundingDemo2\n -> (\n -> Amount DECIMAL(10,4)\n -> );\nQuery OK, 0 rows affected (0.81 sec)"
},
{
"code": null,
"e": 2404,
"s": 2323,
"text": "Insert some records in the table using insert command. The query is as follows −"
},
{
"code": null,
"e": 2674,
"s": 2404,
"text": "mysql> insert into stopRoundingDemo2 values(7836.783);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into stopRoundingDemo2 values(1737.67);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into stopRoundingDemo2 values(110.50);\nQuery OK, 1 row affected (0.16 sec)"
},
{
"code": null,
"e": 2759,
"s": 2674,
"text": "Display all records from the table using select statement. The query is as follows −"
},
{
"code": null,
"e": 2798,
"s": 2759,
"text": "mysql> select *from stopRoundingDemo2;"
},
{
"code": null,
"e": 2823,
"s": 2798,
"text": "The output is as follows"
},
{
"code": null,
"e": 2946,
"s": 2823,
"text": "+-----------+\n| Amount |\n+-----------+\n| 7836.7830 |\n| 1737.6700 |\n| 110.5000 |\n+-----------+\n3 rows in set (0.00 sec)"
}
] |
Statistics in Spark SQL explained | by David Vrba | Towards Data Science
|
Spark SQL optimizer uses two types of optimizations: rule-based and cost-based. The former relies on heuristic rules while the latter can use some statistical properties of the data. In this article, we will explain how these statistics are used in Spark under the hood and we will see in which situations they are useful and how to take advantage of them.
Most of the optimizations that Spark does are based on some heuristic rules that do not take into account the properties of the data that are being processed. For example, the PredicatePushDown rule is based on a heuristic rule which assumes that it is better to first reduce the data by filtering and then apply some computation on it. There are however some situations in which Spark can also use some statistical information about the data in order to come up with yet a better plan and this is often referred to as the cost-based optimization or CBO. In this article, we will explore it more in detail.
To see the statistics of a table we first need to compute them by running a SQL statement (notice that all the SQL statements can be executed in Spark using the sql() function spark.sql(sql_statement_as_string)):
ANALYZE TABLE table_name COMPUTE STATISTICS
After this, the table level statistics are computed and saved in metastore and we can see them by calling
DESCRIBE EXTENDED table_name
This is going to show us some properties of the table including the table-level statistics. There are two metrics available, namely the rowCount and sizeInBytes:
Apart from these table-level statistics there are also column-level statistics and to compute and see them we can call:
ANALYZE TABLE table_name COMPUTE STATISTICS FOR COLUMNS col_nameDESCRIBE EXTENDED table_name column_name
This is going to show us a table like this (the column used in this example is user_id):
So as you can see, there are various metrics for the column, such as min/max values, number of null values, number of distinct values (which is approximated), and some others.
Since Spark 3.0 there is one more option on how to display the stats and see it not only for the table but for the actual query that we want to run. This can be done by using the new mode argument of the explain function:
spark.table(table_name).explain(mode="cost")
This is going to show us two query plans, namely the physical plan and also the optimized logical plan which will now contain also the information about the statistics as you can see in the image below:
The point is that now you can see the statistics for each operator in the plan, so you can see what are the estimates of the stats after various transformations. The stats are first computed by the Relation operator which is a so-called leaf node and each leaf node is responsible to compute the stats somehow, and then they are propagated through the plan according to some rules.
In the next, we will see how the leaf node computes the stats and how the propagation works.
There are three ways of how the leaf node can compute the statistics. The first (and best) way is that the stats are taken from the metastore. The second option is that Spark will use InMemoryFileIndex which calls Hadoop API under the hood to gather the size of each file in the datasource and sum it up to get the total sizeInBytes (in this option only this one metric would be computed). And finally, the last way is that Spark would use a default value for the sizeInBytes metric which is given by the spark.sql.defaultSizeInBytes configuration setting and the default of this setting is 8 EiB, so basically Spark will overestimate the size for the Relation as much as possible (and again only this one metric will be used). Which of these three options takes place can be described by this diagram:
This diagram is a tree where each node is a condition and if the condition is true, we go in the direction of T (True) otherwise we go in the direction of F (False). The leaves represent the actual way how the stats will be computed, so for example InMemoryFI means that only sizeInBytes will be computed by calling the Hadoop API. On the other hand, Stats from M means that the statistics will be taken from the metastore, however, notice that on the left side of the tree all the stats will be taken from the metastore but on the right side only one metric sizeInBytes will be taken. The leaf CatalogFileIndex represents the last case where the default value 8 EiB for the sizeInBytes will be used.
In the diagram we have altogether four conditions, the first determines how the data is accessed: if we read the data as a table df=spark.table(table_name) then we go to the left, otherwise, we go to the right. The next condition is whether the cost-based optimizer (CBO) is turned On or Off. This is given by the configuration setting spark.sql.cbo.enabled and the default value is False (still in Spark 3.0). The third condition asks if the stats were computed in metastore by running the analyze table command (ATC) and finally the last condition is whether the table is partitioned or not.
The best scenario occurs if we read the data as a table, if the cost-based optimizer is On, and if we first run ATC, in that case, all the statistics will be taken from the metastore (except for the sizeInBytes which is computed from the rowCount as described below). On the other hand, the worst situation with the worst estimates happens when we also access the data as a table, but if the ATC didn’t run and moreover the table is partitioned, in this case, the default sizeInBytes is taken from the configuration property and the estimates will be very imprecise. Notice that for the worst-case scenario it is irrelevant whether the CBO is On or Off. Also notice that if the table is not partitioned, Spark will actually compute at least the sizeInBytes using the Hadoop API so the table partitioning has a direct impact on how the stats are computed in the leaf node of the query plan.
Once the statistics are computed in the leaf node, they can be propagated to other nodes in the query plan. There are two ways of how this propagation can happen. The first way (let’s call it the Old way) is rather basic and only one metric, namely sizeInBytes, is propagated and here the rules by which the metric is adjusted on various operators are very basic. For instance, the Filter operator doesn’t adjust the value at all as you can see in this example:
( spark.table(table_name) .filter(col("user_id") < 0)).explain(mode="cost")
In this query, we filter for all records where the user_id is negative, and there are actually no such records, but Spark doesn’t have this information available because that would require to use also column-level statistics and they are not used in this Old way. So as you can see from the query plan, there is only sizeInBytes propagated and it stays the same on both operators. In other words, we can say that Spark thinks that after applying the Filter, the size of the data doesn’t change:
The second way of stats propagation (let’s call it the New way) is more mature, it is available since Spark 2.2 and it requires having the CBO turned ON. It also requires to have the stats computed in metastore with ATC. Here all the stats are propagated and if we provide also the column level metrics, Spark can compute the selectivity for the Filter operator and compute a better estimate:
As you can see, the stats on the Filter operator changed, the rowCount is now zero and the sizeInBytes is 1B which is the minimum value. From the column level stats of the user_id column, Spark was able to see that there are no records with the negative value of user_id and is able to reflect that in the query plan.
In this New way, to compute the sizeInBytes, Spark first computes the size of a single row based on the data types information for each column and then multiplies by the rowCount to get the final sizeInBytes. If the rowCount is zero, the sizeInBytes is set to 1 to avoid division by zero in some other stats computation. This is also how the sizeInBytes is adjusted on the Project operator (Spark knows what columns will be projected, so again it computes the size of a single row first).
At this moment we have an idea of how the stats are computed and propagated through the plan, let’s now finally see how they are also used during the query planning to achieve a more optimal plan. There are two places where these statistics are used. The first one is the JoinSelection strategy where Spark decides which algorithm will be used for joining two DataFrames (see my other article where I describe this more in detail). The basic logic is that if one of the DataFrames is smaller than a certain threshold, Spark will use BroadcastHashJoin (BHJ), because it is a very efficient algorithm if the broadcasted DataFrame is very small. The threshold is given by spark.sql.autoBroadcastJoinThreshold configuration setting which default value is 10 MB. So here having a good estimate for the size of the DataFrame can help to choose a more optimal algorithm for the join.
The second place where stats are used is also related to joins and namely, it is the joinReorder rule. Using this rule Spark can find the most optimal order in which DataFrames will be joined (if you join more than two DataFrames). This rule is by default turned off and if you want to use it you have to enable it by this configuration setting:
spark.conf.set("spark.sql.cbo.joinReorder.enabled", True)
because the default value is False. The maximum number of DataFrames for which this can be used is controlled by this property:
spark.conf.set("spark.sql.cbo.joinReorder.dp.threshold", n)
where the default value of n is 12.
Well, we have seen that if a table is partitioned and we don’t run ATC, Spark will overestimate the size by using the default value (which is very large — 8 EiB). So in a situation where we join lots of tables and some of these tables are partitioned and rather small, so they could be good candidates for BHJ, in that case, it makes sense to run for them ATC. Also, we have to remember that if a table is appended or overwritten, the stats will be deleted, so we have to run ATC again. In some environments, having the stats in metastore up to date might be complicated. A partial solution to this problem provides adaptive query execution — a new feature in Spark 3.0.
In Spark 3.0 a new feature Adaptive Query Execution (AQE) was released and it uses statistics in an even more enhanced way. If the AQE is enabled (by default it is not), the statistics are recomputed after each stage is executed during runtime. This leads to more precise stats estimates and a better ability to decide whether BHJ can be used or not. AQE itself is quite a big topic and we can cover it in a separate article.
In this article, we have seen how statistical information about data is used by Spark in order to achieve a more optimal execution plan. We have seen that there are three ways how the stats are computed in the first node of the query plan (in a so-called leaf node) and then how this information can be propagated through the plan. We pointed out a special caveat related to partitioned tables which are small and may be good candidates for broadcasting in joins. If we don’t run the analyze table command for them, Spark will overestimate the size of these tables and the broadcast join will be hardly achieved. We also showed that having better propagation of the statistics through the plan requires having the cost-based optimizer enabled and column statistics computed especially for those columns that are used in filtering conditions.
|
[
{
"code": null,
"e": 529,
"s": 172,
"text": "Spark SQL optimizer uses two types of optimizations: rule-based and cost-based. The former relies on heuristic rules while the latter can use some statistical properties of the data. In this article, we will explain how these statistics are used in Spark under the hood and we will see in which situations they are useful and how to take advantage of them."
},
{
"code": null,
"e": 1136,
"s": 529,
"text": "Most of the optimizations that Spark does are based on some heuristic rules that do not take into account the properties of the data that are being processed. For example, the PredicatePushDown rule is based on a heuristic rule which assumes that it is better to first reduce the data by filtering and then apply some computation on it. There are however some situations in which Spark can also use some statistical information about the data in order to come up with yet a better plan and this is often referred to as the cost-based optimization or CBO. In this article, we will explore it more in detail."
},
{
"code": null,
"e": 1349,
"s": 1136,
"text": "To see the statistics of a table we first need to compute them by running a SQL statement (notice that all the SQL statements can be executed in Spark using the sql() function spark.sql(sql_statement_as_string)):"
},
{
"code": null,
"e": 1393,
"s": 1349,
"text": "ANALYZE TABLE table_name COMPUTE STATISTICS"
},
{
"code": null,
"e": 1499,
"s": 1393,
"text": "After this, the table level statistics are computed and saved in metastore and we can see them by calling"
},
{
"code": null,
"e": 1528,
"s": 1499,
"text": "DESCRIBE EXTENDED table_name"
},
{
"code": null,
"e": 1690,
"s": 1528,
"text": "This is going to show us some properties of the table including the table-level statistics. There are two metrics available, namely the rowCount and sizeInBytes:"
},
{
"code": null,
"e": 1810,
"s": 1690,
"text": "Apart from these table-level statistics there are also column-level statistics and to compute and see them we can call:"
},
{
"code": null,
"e": 1915,
"s": 1810,
"text": "ANALYZE TABLE table_name COMPUTE STATISTICS FOR COLUMNS col_nameDESCRIBE EXTENDED table_name column_name"
},
{
"code": null,
"e": 2004,
"s": 1915,
"text": "This is going to show us a table like this (the column used in this example is user_id):"
},
{
"code": null,
"e": 2180,
"s": 2004,
"text": "So as you can see, there are various metrics for the column, such as min/max values, number of null values, number of distinct values (which is approximated), and some others."
},
{
"code": null,
"e": 2402,
"s": 2180,
"text": "Since Spark 3.0 there is one more option on how to display the stats and see it not only for the table but for the actual query that we want to run. This can be done by using the new mode argument of the explain function:"
},
{
"code": null,
"e": 2447,
"s": 2402,
"text": "spark.table(table_name).explain(mode=\"cost\")"
},
{
"code": null,
"e": 2650,
"s": 2447,
"text": "This is going to show us two query plans, namely the physical plan and also the optimized logical plan which will now contain also the information about the statistics as you can see in the image below:"
},
{
"code": null,
"e": 3032,
"s": 2650,
"text": "The point is that now you can see the statistics for each operator in the plan, so you can see what are the estimates of the stats after various transformations. The stats are first computed by the Relation operator which is a so-called leaf node and each leaf node is responsible to compute the stats somehow, and then they are propagated through the plan according to some rules."
},
{
"code": null,
"e": 3125,
"s": 3032,
"text": "In the next, we will see how the leaf node computes the stats and how the propagation works."
},
{
"code": null,
"e": 3928,
"s": 3125,
"text": "There are three ways of how the leaf node can compute the statistics. The first (and best) way is that the stats are taken from the metastore. The second option is that Spark will use InMemoryFileIndex which calls Hadoop API under the hood to gather the size of each file in the datasource and sum it up to get the total sizeInBytes (in this option only this one metric would be computed). And finally, the last way is that Spark would use a default value for the sizeInBytes metric which is given by the spark.sql.defaultSizeInBytes configuration setting and the default of this setting is 8 EiB, so basically Spark will overestimate the size for the Relation as much as possible (and again only this one metric will be used). Which of these three options takes place can be described by this diagram:"
},
{
"code": null,
"e": 4629,
"s": 3928,
"text": "This diagram is a tree where each node is a condition and if the condition is true, we go in the direction of T (True) otherwise we go in the direction of F (False). The leaves represent the actual way how the stats will be computed, so for example InMemoryFI means that only sizeInBytes will be computed by calling the Hadoop API. On the other hand, Stats from M means that the statistics will be taken from the metastore, however, notice that on the left side of the tree all the stats will be taken from the metastore but on the right side only one metric sizeInBytes will be taken. The leaf CatalogFileIndex represents the last case where the default value 8 EiB for the sizeInBytes will be used."
},
{
"code": null,
"e": 5223,
"s": 4629,
"text": "In the diagram we have altogether four conditions, the first determines how the data is accessed: if we read the data as a table df=spark.table(table_name) then we go to the left, otherwise, we go to the right. The next condition is whether the cost-based optimizer (CBO) is turned On or Off. This is given by the configuration setting spark.sql.cbo.enabled and the default value is False (still in Spark 3.0). The third condition asks if the stats were computed in metastore by running the analyze table command (ATC) and finally the last condition is whether the table is partitioned or not."
},
{
"code": null,
"e": 6113,
"s": 5223,
"text": "The best scenario occurs if we read the data as a table, if the cost-based optimizer is On, and if we first run ATC, in that case, all the statistics will be taken from the metastore (except for the sizeInBytes which is computed from the rowCount as described below). On the other hand, the worst situation with the worst estimates happens when we also access the data as a table, but if the ATC didn’t run and moreover the table is partitioned, in this case, the default sizeInBytes is taken from the configuration property and the estimates will be very imprecise. Notice that for the worst-case scenario it is irrelevant whether the CBO is On or Off. Also notice that if the table is not partitioned, Spark will actually compute at least the sizeInBytes using the Hadoop API so the table partitioning has a direct impact on how the stats are computed in the leaf node of the query plan."
},
{
"code": null,
"e": 6575,
"s": 6113,
"text": "Once the statistics are computed in the leaf node, they can be propagated to other nodes in the query plan. There are two ways of how this propagation can happen. The first way (let’s call it the Old way) is rather basic and only one metric, namely sizeInBytes, is propagated and here the rules by which the metric is adjusted on various operators are very basic. For instance, the Filter operator doesn’t adjust the value at all as you can see in this example:"
},
{
"code": null,
"e": 6653,
"s": 6575,
"text": "( spark.table(table_name) .filter(col(\"user_id\") < 0)).explain(mode=\"cost\")"
},
{
"code": null,
"e": 7148,
"s": 6653,
"text": "In this query, we filter for all records where the user_id is negative, and there are actually no such records, but Spark doesn’t have this information available because that would require to use also column-level statistics and they are not used in this Old way. So as you can see from the query plan, there is only sizeInBytes propagated and it stays the same on both operators. In other words, we can say that Spark thinks that after applying the Filter, the size of the data doesn’t change:"
},
{
"code": null,
"e": 7541,
"s": 7148,
"text": "The second way of stats propagation (let’s call it the New way) is more mature, it is available since Spark 2.2 and it requires having the CBO turned ON. It also requires to have the stats computed in metastore with ATC. Here all the stats are propagated and if we provide also the column level metrics, Spark can compute the selectivity for the Filter operator and compute a better estimate:"
},
{
"code": null,
"e": 7859,
"s": 7541,
"text": "As you can see, the stats on the Filter operator changed, the rowCount is now zero and the sizeInBytes is 1B which is the minimum value. From the column level stats of the user_id column, Spark was able to see that there are no records with the negative value of user_id and is able to reflect that in the query plan."
},
{
"code": null,
"e": 8348,
"s": 7859,
"text": "In this New way, to compute the sizeInBytes, Spark first computes the size of a single row based on the data types information for each column and then multiplies by the rowCount to get the final sizeInBytes. If the rowCount is zero, the sizeInBytes is set to 1 to avoid division by zero in some other stats computation. This is also how the sizeInBytes is adjusted on the Project operator (Spark knows what columns will be projected, so again it computes the size of a single row first)."
},
{
"code": null,
"e": 9225,
"s": 8348,
"text": "At this moment we have an idea of how the stats are computed and propagated through the plan, let’s now finally see how they are also used during the query planning to achieve a more optimal plan. There are two places where these statistics are used. The first one is the JoinSelection strategy where Spark decides which algorithm will be used for joining two DataFrames (see my other article where I describe this more in detail). The basic logic is that if one of the DataFrames is smaller than a certain threshold, Spark will use BroadcastHashJoin (BHJ), because it is a very efficient algorithm if the broadcasted DataFrame is very small. The threshold is given by spark.sql.autoBroadcastJoinThreshold configuration setting which default value is 10 MB. So here having a good estimate for the size of the DataFrame can help to choose a more optimal algorithm for the join."
},
{
"code": null,
"e": 9571,
"s": 9225,
"text": "The second place where stats are used is also related to joins and namely, it is the joinReorder rule. Using this rule Spark can find the most optimal order in which DataFrames will be joined (if you join more than two DataFrames). This rule is by default turned off and if you want to use it you have to enable it by this configuration setting:"
},
{
"code": null,
"e": 9629,
"s": 9571,
"text": "spark.conf.set(\"spark.sql.cbo.joinReorder.enabled\", True)"
},
{
"code": null,
"e": 9757,
"s": 9629,
"text": "because the default value is False. The maximum number of DataFrames for which this can be used is controlled by this property:"
},
{
"code": null,
"e": 9817,
"s": 9757,
"text": "spark.conf.set(\"spark.sql.cbo.joinReorder.dp.threshold\", n)"
},
{
"code": null,
"e": 9853,
"s": 9817,
"text": "where the default value of n is 12."
},
{
"code": null,
"e": 10524,
"s": 9853,
"text": "Well, we have seen that if a table is partitioned and we don’t run ATC, Spark will overestimate the size by using the default value (which is very large — 8 EiB). So in a situation where we join lots of tables and some of these tables are partitioned and rather small, so they could be good candidates for BHJ, in that case, it makes sense to run for them ATC. Also, we have to remember that if a table is appended or overwritten, the stats will be deleted, so we have to run ATC again. In some environments, having the stats in metastore up to date might be complicated. A partial solution to this problem provides adaptive query execution — a new feature in Spark 3.0."
},
{
"code": null,
"e": 10950,
"s": 10524,
"text": "In Spark 3.0 a new feature Adaptive Query Execution (AQE) was released and it uses statistics in an even more enhanced way. If the AQE is enabled (by default it is not), the statistics are recomputed after each stage is executed during runtime. This leads to more precise stats estimates and a better ability to decide whether BHJ can be used or not. AQE itself is quite a big topic and we can cover it in a separate article."
}
] |
Difference between private, public, and protected modifiers in C++
|
Data hiding is one of the important features of Object Oriented Programming which allows preventing the functions of a program to access directly the internal representation of a class type. The access restriction to the class members is specified by the labeled access modifiers − public, private, and protected sections within the class body.
The default access for members and classes is private.
class Base {
public:
// public members go here
protected:
// protected members go here
private:
// private members go here
};
A public member is accessible from anywhere outside the class but within a program. You can set and get the value of public variables without any member.
A private member variable or function cannot be accessed, or even viewed from outside the class. Only the class and friend functions can access private members.
A protected member variable or function is very similar to a private member but it provided one additional benefit that they can be accessed in child classes which are called derived classes.
|
[
{
"code": null,
"e": 1407,
"s": 1062,
"text": "Data hiding is one of the important features of Object Oriented Programming which allows preventing the functions of a program to access directly the internal representation of a class type. The access restriction to the class members is specified by the labeled access modifiers − public, private, and protected sections within the class body."
},
{
"code": null,
"e": 1462,
"s": 1407,
"text": "The default access for members and classes is private."
},
{
"code": null,
"e": 1598,
"s": 1462,
"text": "class Base {\npublic:\n // public members go here\nprotected:\n\n // protected members go here\nprivate:\n // private members go here\n};"
},
{
"code": null,
"e": 1752,
"s": 1598,
"text": "A public member is accessible from anywhere outside the class but within a program. You can set and get the value of public variables without any member."
},
{
"code": null,
"e": 1913,
"s": 1752,
"text": "A private member variable or function cannot be accessed, or even viewed from outside the class. Only the class and friend functions can access private members."
},
{
"code": null,
"e": 2105,
"s": 1913,
"text": "A protected member variable or function is very similar to a private member but it provided one additional benefit that they can be accessed in child classes which are called derived classes."
}
] |
Change the curdate() (current date) format in MySQL
|
The current date format is ‘YYYY-mm-dd’. To change current date format, you can use date_format().
Let us first display the current date −
mysql> select curdate();
This will produce the following output −
+------------+
| curdate() |
+------------+
| 2019-08-08 |
+------------+
1 row in set (0.00 sec)
Following is the query to change curdate() (current date) format −
mysql> select date_format(curdate(), '%m/%d/%Y');
This will produce the following output −
+------------------------------------+
| date_format(curdate(), '%m/%d/%Y') |
+------------------------------------+
| 08/08/2019 |
+------------------------------------+
1 row in set (0.00 sec)
Let us first create a table −
mysql> create table DemoTable (
ArrivalDate date
);
Query OK, 0 rows affected (0.50 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('2019-01-10');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('2016-12-18');
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------------+
| ArrivalDate |
+-------------+
| 2019-01-10 |
| 2016-12-18 |
+-------------+
2 rows in set (0.00 sec)
Following is the query to change date format −
mysql> select date_format(ArrivalDate, '%m/%d/%Y') from DemoTable;
This will produce the following output −
+--------------------------------------+
| date_format(ArrivalDate, '%m/%d/%Y') |
+--------------------------------------+
| 01/10/2019 |
| 12/18/2016 |
+--------------------------------------+
2 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1161,
"s": 1062,
"text": "The current date format is ‘YYYY-mm-dd’. To change current date format, you can use date_format()."
},
{
"code": null,
"e": 1201,
"s": 1161,
"text": "Let us first display the current date −"
},
{
"code": null,
"e": 1226,
"s": 1201,
"text": "mysql> select curdate();"
},
{
"code": null,
"e": 1267,
"s": 1226,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1366,
"s": 1267,
"text": "+------------+\n| curdate() |\n+------------+\n| 2019-08-08 |\n+------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 1433,
"s": 1366,
"text": "Following is the query to change curdate() (current date) format −"
},
{
"code": null,
"e": 1483,
"s": 1433,
"text": "mysql> select date_format(curdate(), '%m/%d/%Y');"
},
{
"code": null,
"e": 1524,
"s": 1483,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1743,
"s": 1524,
"text": "+------------------------------------+\n| date_format(curdate(), '%m/%d/%Y') |\n+------------------------------------+\n| 08/08/2019 |\n+------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 1773,
"s": 1743,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1865,
"s": 1773,
"text": "mysql> create table DemoTable (\n ArrivalDate date\n);\nQuery OK, 0 rows affected (0.50 sec)"
},
{
"code": null,
"e": 1921,
"s": 1865,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 2095,
"s": 1921,
"text": "mysql> insert into DemoTable values('2019-01-10');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into DemoTable values('2016-12-18');\nQuery OK, 1 row affected (0.12 sec)"
},
{
"code": null,
"e": 2155,
"s": 2095,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 2186,
"s": 2155,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2227,
"s": 2186,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2348,
"s": 2227,
"text": "+-------------+\n| ArrivalDate |\n+-------------+\n| 2019-01-10 |\n| 2016-12-18 |\n+-------------+\n2 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2395,
"s": 2348,
"text": "Following is the query to change date format −"
},
{
"code": null,
"e": 2462,
"s": 2395,
"text": "mysql> select date_format(ArrivalDate, '%m/%d/%Y') from DemoTable;"
},
{
"code": null,
"e": 2503,
"s": 2462,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2774,
"s": 2503,
"text": "+--------------------------------------+\n| date_format(ArrivalDate, '%m/%d/%Y') |\n+--------------------------------------+\n| 01/10/2019 |\n| 12/18/2016 |\n+--------------------------------------+\n2 rows in set (0.00 sec)"
}
] |
How to Predict Business Success & Failure | by Nadim Kawwa | Towards Data Science
|
Starting a business is no trivial task, there are many expenses to consider such as sunk costs, overhead, and loans. Metrics for success include but are not limited to growth, sales revenue, customer retention, and balance sheets.
The viability of a business is first and foremost dependent on one axiom: that it stays open.
This topic is a primary interest for businesses who must remain viable and customers who expect good and reliable services. It is also important in the field of finance where lenders must justify giving out loans, and might be obligated by law to explain why applications are denied.
We therefore formulate the motivation and purpose of this endeavor as follows: Can we predict if a business is open or closed? What are the main indicators of viability?
In this article we are going to solve for this question using the Yelp Dataset, a collection of relational data about local businesses across the USA and Canada. It contains a large volume of comprehensive information:
6,685,900 reviews
192,609 businesses
10 metropolitan areas
1,223,094 tips
The Yelp dataset is therefore an excellent case study on how aptly engineered features, coupled with machine learning models, can predict the success of a business beyond traditional approaches such as balance sheets.
In the next part , we are going to present each segment of the dataset as given and draw features from it:
Businesses: (business.json) This dataset contains business relevant data including location data, restaurant attributes, and cuisine categories.
Reviews: (Review.json) This dataset contains full review text data including the user_id that wrote the review, and the business_id the review is written for.
Checkin: (Checkin.json) This dataset contains the check ins for businesses where available.
The business.json file contains business data including location data, attributes, and categories. The snippet below shows its configuration:
{ // string, 22 character unique string business id "business_id": "tnhfDv5Il8EaGSXZGiuQGg", // string, the business's name "name": "Garaje", // string, the full address of the business "address": "475 3rd St", // string, the city "city": "San Francisco", // string, 2 character state code, if applicable "state": "CA", // string, the postal code "postal code": "94107", // float, latitude "latitude": 37.7817529521, // float, longitude "longitude": -122.39612197, // float, star rating, rounded to half-stars "stars": 4.5, // integer, number of reviews "review_count": 1198, // integer, 0 or 1 for closed or open, respectively "is_open": 1, // object, business attributes to values. note: some attribute values might be objects "attributes": { "RestaurantsTakeOut": true, "BusinessParking": { "garage": false, "street": true, "validated": false, "lot": false, "valet": false }, }, // an array of strings of business categories "categories": [ "Mexican", "Burgers", "Gastropubs" ], // an object of key day to value hours, hours are using a 24hr clock "hours": { "Monday": "10:00-21:00", "Tuesday": "10:00-21:00", "Friday": "10:00-21:00", "Wednesday": "10:00-21:00", "Thursday": "10:00-21:00", "Sunday": "11:00-18:00", "Saturday": "10:00-21:00" }}
The target variable is the is_open such as 0 indicates closed and 1 indicates open.
As a first approach we need to explode the nested attributes into its corresponding values. For example within the attributes feature we have a binary encoding for RestaurantsTakeOut and we need to further expand the BusinessParking feature.
Within the attributes feature we can engineer categorical variables such that with numerical values. For example NoiseLevel is a string input with values:
very_loud
loud
average
quiet
NaN
It’s therefore possible to encode these string features with numeric values, for example a scale that represents noise levels. We can repeat same exercise for attributes such as AgesAllowed, Alcohol, RestaurantsAttire, and others.
Furthermore, the categories feature contains a list of strings that are not mutually exclusive. It is possible for a businesses to fall under Mexican, Burgers, and Gastropubs. Therefore these are encoded as binary features.
In a simple case of natural language processing, we notice that ~1000 businesses are named Starbucks and ~800 are named McDonalds . We therefore define the binary chain feature such as 1 indicates that this business is part of a chain, and such that a name must appear at least 5 times to be considered a chain.
We use the latitude and longitude features in order to draw geodetic features from the datataset. We use the minimum bounding box method in order to query all other businesses in a given radius. In the context of this project we set the radius to 2 kilometers, as a reasonable distance customers are willing to walk between businesses.
From geodetic data we can define features such as density which is the amount of businesses in the queried circle. In addition we can compare each business against its surroundings by applying a Z-Score Normalization. For example the Z-score of a business’ price is its the difference between the price and the mean of the group, divided by the standard deviation.
For feature engineering, it can be helpful to draw information beyond the dataset. Each business has its corresponding postal code in USA and Canadian formats.
That being said the IRS releases Individual Income Statistics and Canada’s Bureau of Statistics releases income data. Although not specific to the business itself, the income of the locality can play a role in viability.
In order to preserve the privacy of citizens, the IRS does not release exact income figures, instead the data is categorical. For example a value of 3 indicates income between $50,000–75000 and 5 is between $100,000–200,000.
Hence we can match each zip code with the corresponding median household income, making sure to covert Canadian Dollars to USA currency and binning Canadian income data per the IRS method.
The review.json file contains full review text data including the user_id that wrote the review and the business_id the review is written for.
Below is a snippet laying out the attributes:
{ // string, 22 character unique review id "review_id": "zdSx_SD6obEhz9VrW9uAWA", // string, 22 character unique user id, maps to the user in user.json "user_id": "Ha3iJu77CxlrFm-vQRs_8g", // string, 22 character business id, maps to business in business.json "business_id": "tnhfDv5Il8EaGSXZGiuQGg", // integer, star rating "stars": 4, // string, date formatted YYYY-MM-DD "date": "2016-03-09", // string, the review itself "text": "Great place to hang out after work: the prices are decent, and the ambience is fun. It's a bit loud, but very lively. The staff is friendly, and the food is good. They have a good selection of drinks.", // integer, number of useful votes received "useful": 0, // integer, number of funny votes received "funny": 0, // integer, number of cool votes received "cool": 0}
We can aggregate by business_id and be done with the feature engineering. However given that each impression has a time stamp associated with it, we can directly measure the changes associated with a given location.
The mean of user star ratings return the average business score. Grouping by year can help us see how the business features are changing by year. Are they improving or lagging behind?
The first question to ask is where are those ~192,000 businesses located? Per the plot below: Vegas baby!
Contrary to the plot above, the majority of businesses are located in Arizona as shown below:
Furthermore we can see that the majority of businesses have a rating between 3.0 and 4.5, such that the mean is around 3.5.
Finally we want to compare the distribution of the positive/negative label across business types by plotting counts and color hue by target variable. Restaurants account for the large majority of businesses and have the highest proportion of closed businesses.
The checkin.json file lists all checkins for businesses where available:
{ // string, 22 character business id, maps to business in business.json "business_id": "tnhfDv5Il8EaGSXZGiuQGg" // string which is a comma-separated list of timestamps for each checkin, each with format YYYY-MM-DD HH:MM:SS "date": "2016-04-26 19:49:16, 2016-08-30 18:36:57, 2016-10-15 02:45:18, 2016-11-18 01:54:50, 2017-04-20 18:39:06, 2017-05-03 17:58:02"}
As a first step, we can explore trends in checkins as shown in the plot below, where the y-axis corresponds to the number of checkins aggregated over all the years and split by 30min intervals. For example this plot tells us that the peak average checkin from Saturday-Sunday night occurs around 8PM whilst providing a confidence interval.
On a more macro scale we can also explore checkins in December, which contains a lot of seasonality. In the plot below, the highlights correspond to weekends.
From the data we can extract what is the average monthly checkin. In addition we define the span as the time in seconds between the first and the last checkin: The longer a business has been open, the higher the probability it will remain open (see Sunrise Problem).
The question we are trying to solve for falls under supervised learning. Given the heavily imbalanced nature of the target variable, we omit scoring based on accuracy and consider the following metrics:
Precision
Recall
F1 Score
Area Under Curve
In a preliminary round, we apply several supervised learning algorithms. The top performers were in ascending order:
Logistic regression
Gradient boosted trees
Random forest
XGBoost
In the following sections we will elaborate more on individual techniques that were coupled together to produce reliable results.
The intent of feature engineering is to have numerical representation of data that can be directly fed into an algorithm. The first step is to split the data between training and testing sets.
In addition we apply min-max feature scaling that is fitted on the training data only to avoid model leakage. The training and testing data are then transformed using that fit.
The method also known as GridSearchCV is popular with data scientists because it is so comprehensive. By combining cross validation with grid search, we obtain tuned hyperparameters.
Certain algorithms such as tree based models perform poorly in high dimensional spaces. Having too many features might also entail noisy features.
The first approach used to detect noisy features is via logistic regression’s L1 feature selection, which gives a weight of 0 to useless features. The second approach is using the featexp package in order to identify noisy features.
Ultimately the most interpretable method was permutation for feature importance. In this context we permute a given feature and calculate the change in the model’s prediction error. A feature is ‘important’ if shuffling it significantly changes the error on the model, and is ‘unimportant’ if the error remains unchanged.
Finally the most impactful aspect of the project was dealing with the imbalanced target variable. Recall that only about ~20% of businesses are listed as closed.
In practical terms this means that the minority class is overwhelmed by the majority class such that the algorithm does not have enough minority observations to draw decisions, or that the minority class is swamped by the majority.
One way to address this is via undersampling: keep the minority class as is and draw an equal number of observations at random from the majority class. Conversely oversampling works slightly better: duplicate the minority class until the dataset is balanced.
In either choice of sampling, it is crucial to apply it only on the training data. Sampling the test data is a common pitfall, since it equates to misconstruing reality.
The table below summarizes several model performances. Across the board, all models are better at predicting open businesses (Class 1) rather than shuttered ones (Class 0).
Overall we can see tree based models tend to perform best with AUC hovering at 0.75.
That being said model interpretability is as important, if not more, than model performance. We must therefore dive deeper into each model to understand what are the main features driving our decisions.
The table below shows the top 5 most important features for the models.
Interestingly enough within a same model such as logistic regression, being a Restaurant can be a positive or negative weight depending on the sampling method.
We also notice some expected features such as RestaurantsPriceRange2 which relate to price, and some peculiar ones such as AcceptsInsurance and BikeParking. In the case of insurance, the feature might be important to businesses such as massage parlors or doctors’ clinics.
In the winning model, the following features are crucial for business success:
Be a Restaurant
Service lunch
Also serve dinner
Your RestaurantsPriceRange2 matters
Be a chain
The main features for XGBoost were obtained from the feature_importances_ attribute. However we wish to find a way to explain our output and how to optimize for business success.
For this study we use the SHAP (SHapley Additive exPlanation) package to derive individualized feature attributions. Shapley values are primarily used on a per-prediction basis to help with explainability, and answer questions like “What caused my business to be marked as being closed?”
To justify the use of SHAP, we present the plot_importance method in XGBoost that produces three different interpretations based on the importance type.
weight the number of times a feature appears in a tree
gain the average gain of splits which use the feature
cover the average coverage of splits which use the feature where coverage is defined as the number of samples affected by the split
In the plot below we show the mean absolute value of the SHAP values. The x-axis shows the average magnitude change in the model output when a feature is hidden from the model. Given that hiding a feature changes depending on what other features are also hidden, Shapley values are used to enforce consistency and accuracy.
The plot below is a density scatter plot of SHAP values for each feature to identify how much impact each feature has on the model output for each observation in the dataset. The summary plot combines feature importance with feature effects. Each point on the summary plot is a Shapley value for a feature and an instance. The position on the y-axis is determined by the feature and on the x-axis by the Shapley value. The color represents the value of the feature from low to high.
The coloring by feature shows us that having your stars_change (average change in stars rating over time) increase is a good predictor to stay open. For review_count (the number of reviews) not having a lot can harm you, however having a high reiew_count can also mean a high volume of negative reviews. For the third most important feature useful (total count of useful review votes), it appears to be a positive indicator for success.
The plot also allows us to to identify outliers since overlapping points are jittered in y-axis direction, so we get a sense of the distribution of the Shapley values per feature. For a particular subset of businesses, having a high count of useful can actually be an indicator of closing soon. For example, it is not unheard of for someone to comment “Stay away from the chicken, seemed undercooked”.
SHAP dependence plots are an additional visualization to show the effect of a single feature across the whole dataset. Contrary to partial dependence plots, SHAP account for the interaction effects present in the features, and are only defined in regions of the input space supported by data.
The plot below applies to review_density (normalized review count of business versus all others within 2km radius).
In the plot above the vertical dispersion is driven by interaction effects and another feature, here RestaurantsGoodForGroups , is chosen for coloring to highlight possible interactions. We can see here that having a higher review count relative to other businesses is a good indicator for success. In addition, being good for groups tends to correlate positively with review_density.
The correlation matrix below ties into the plot from above. We can notice a positive correlation between review_density and RestaurantsGoodForGroups.
Knowing if a business will close its doors or stay open is a study entrepreneurs take before investing. With machine learning, we are able to identify features that can predict for the original question of this article. We were also able to provide model interpretability on a per-user basis.
Although a comprehensive answer to the problem might not be obtained, the solution nonetheless offers a path forward. Businesses can use the model interpretations to optimize for success and know the metrics they need to improve upon.
Looking forward we can take advantage of the text information within the review.json file. A sample NLP exercise would be to extract sentiments or group of words in function of time or location that indicate business performance.
The project was made possible thanks to sharpestminds.com and Aditya Subramanian. For an in depth view of the process with corresponding code, head to the GitHub repository:
|
[
{
"code": null,
"e": 402,
"s": 171,
"text": "Starting a business is no trivial task, there are many expenses to consider such as sunk costs, overhead, and loans. Metrics for success include but are not limited to growth, sales revenue, customer retention, and balance sheets."
},
{
"code": null,
"e": 496,
"s": 402,
"text": "The viability of a business is first and foremost dependent on one axiom: that it stays open."
},
{
"code": null,
"e": 780,
"s": 496,
"text": "This topic is a primary interest for businesses who must remain viable and customers who expect good and reliable services. It is also important in the field of finance where lenders must justify giving out loans, and might be obligated by law to explain why applications are denied."
},
{
"code": null,
"e": 950,
"s": 780,
"text": "We therefore formulate the motivation and purpose of this endeavor as follows: Can we predict if a business is open or closed? What are the main indicators of viability?"
},
{
"code": null,
"e": 1169,
"s": 950,
"text": "In this article we are going to solve for this question using the Yelp Dataset, a collection of relational data about local businesses across the USA and Canada. It contains a large volume of comprehensive information:"
},
{
"code": null,
"e": 1187,
"s": 1169,
"text": "6,685,900 reviews"
},
{
"code": null,
"e": 1206,
"s": 1187,
"text": "192,609 businesses"
},
{
"code": null,
"e": 1228,
"s": 1206,
"text": "10 metropolitan areas"
},
{
"code": null,
"e": 1243,
"s": 1228,
"text": "1,223,094 tips"
},
{
"code": null,
"e": 1461,
"s": 1243,
"text": "The Yelp dataset is therefore an excellent case study on how aptly engineered features, coupled with machine learning models, can predict the success of a business beyond traditional approaches such as balance sheets."
},
{
"code": null,
"e": 1568,
"s": 1461,
"text": "In the next part , we are going to present each segment of the dataset as given and draw features from it:"
},
{
"code": null,
"e": 1713,
"s": 1568,
"text": "Businesses: (business.json) This dataset contains business relevant data including location data, restaurant attributes, and cuisine categories."
},
{
"code": null,
"e": 1872,
"s": 1713,
"text": "Reviews: (Review.json) This dataset contains full review text data including the user_id that wrote the review, and the business_id the review is written for."
},
{
"code": null,
"e": 1964,
"s": 1872,
"text": "Checkin: (Checkin.json) This dataset contains the check ins for businesses where available."
},
{
"code": null,
"e": 2106,
"s": 1964,
"text": "The business.json file contains business data including location data, attributes, and categories. The snippet below shows its configuration:"
},
{
"code": null,
"e": 3592,
"s": 2106,
"text": "{ // string, 22 character unique string business id \"business_id\": \"tnhfDv5Il8EaGSXZGiuQGg\", // string, the business's name \"name\": \"Garaje\", // string, the full address of the business \"address\": \"475 3rd St\", // string, the city \"city\": \"San Francisco\", // string, 2 character state code, if applicable \"state\": \"CA\", // string, the postal code \"postal code\": \"94107\", // float, latitude \"latitude\": 37.7817529521, // float, longitude \"longitude\": -122.39612197, // float, star rating, rounded to half-stars \"stars\": 4.5, // integer, number of reviews \"review_count\": 1198, // integer, 0 or 1 for closed or open, respectively \"is_open\": 1, // object, business attributes to values. note: some attribute values might be objects \"attributes\": { \"RestaurantsTakeOut\": true, \"BusinessParking\": { \"garage\": false, \"street\": true, \"validated\": false, \"lot\": false, \"valet\": false }, }, // an array of strings of business categories \"categories\": [ \"Mexican\", \"Burgers\", \"Gastropubs\" ], // an object of key day to value hours, hours are using a 24hr clock \"hours\": { \"Monday\": \"10:00-21:00\", \"Tuesday\": \"10:00-21:00\", \"Friday\": \"10:00-21:00\", \"Wednesday\": \"10:00-21:00\", \"Thursday\": \"10:00-21:00\", \"Sunday\": \"11:00-18:00\", \"Saturday\": \"10:00-21:00\" }}"
},
{
"code": null,
"e": 3676,
"s": 3592,
"text": "The target variable is the is_open such as 0 indicates closed and 1 indicates open."
},
{
"code": null,
"e": 3918,
"s": 3676,
"text": "As a first approach we need to explode the nested attributes into its corresponding values. For example within the attributes feature we have a binary encoding for RestaurantsTakeOut and we need to further expand the BusinessParking feature."
},
{
"code": null,
"e": 4073,
"s": 3918,
"text": "Within the attributes feature we can engineer categorical variables such that with numerical values. For example NoiseLevel is a string input with values:"
},
{
"code": null,
"e": 4083,
"s": 4073,
"text": "very_loud"
},
{
"code": null,
"e": 4088,
"s": 4083,
"text": "loud"
},
{
"code": null,
"e": 4096,
"s": 4088,
"text": "average"
},
{
"code": null,
"e": 4102,
"s": 4096,
"text": "quiet"
},
{
"code": null,
"e": 4106,
"s": 4102,
"text": "NaN"
},
{
"code": null,
"e": 4337,
"s": 4106,
"text": "It’s therefore possible to encode these string features with numeric values, for example a scale that represents noise levels. We can repeat same exercise for attributes such as AgesAllowed, Alcohol, RestaurantsAttire, and others."
},
{
"code": null,
"e": 4561,
"s": 4337,
"text": "Furthermore, the categories feature contains a list of strings that are not mutually exclusive. It is possible for a businesses to fall under Mexican, Burgers, and Gastropubs. Therefore these are encoded as binary features."
},
{
"code": null,
"e": 4873,
"s": 4561,
"text": "In a simple case of natural language processing, we notice that ~1000 businesses are named Starbucks and ~800 are named McDonalds . We therefore define the binary chain feature such as 1 indicates that this business is part of a chain, and such that a name must appear at least 5 times to be considered a chain."
},
{
"code": null,
"e": 5209,
"s": 4873,
"text": "We use the latitude and longitude features in order to draw geodetic features from the datataset. We use the minimum bounding box method in order to query all other businesses in a given radius. In the context of this project we set the radius to 2 kilometers, as a reasonable distance customers are willing to walk between businesses."
},
{
"code": null,
"e": 5574,
"s": 5209,
"text": "From geodetic data we can define features such as density which is the amount of businesses in the queried circle. In addition we can compare each business against its surroundings by applying a Z-Score Normalization. For example the Z-score of a business’ price is its the difference between the price and the mean of the group, divided by the standard deviation."
},
{
"code": null,
"e": 5734,
"s": 5574,
"text": "For feature engineering, it can be helpful to draw information beyond the dataset. Each business has its corresponding postal code in USA and Canadian formats."
},
{
"code": null,
"e": 5955,
"s": 5734,
"text": "That being said the IRS releases Individual Income Statistics and Canada’s Bureau of Statistics releases income data. Although not specific to the business itself, the income of the locality can play a role in viability."
},
{
"code": null,
"e": 6180,
"s": 5955,
"text": "In order to preserve the privacy of citizens, the IRS does not release exact income figures, instead the data is categorical. For example a value of 3 indicates income between $50,000–75000 and 5 is between $100,000–200,000."
},
{
"code": null,
"e": 6369,
"s": 6180,
"text": "Hence we can match each zip code with the corresponding median household income, making sure to covert Canadian Dollars to USA currency and binning Canadian income data per the IRS method."
},
{
"code": null,
"e": 6512,
"s": 6369,
"text": "The review.json file contains full review text data including the user_id that wrote the review and the business_id the review is written for."
},
{
"code": null,
"e": 6558,
"s": 6512,
"text": "Below is a snippet laying out the attributes:"
},
{
"code": null,
"e": 7414,
"s": 6558,
"text": "{ // string, 22 character unique review id \"review_id\": \"zdSx_SD6obEhz9VrW9uAWA\", // string, 22 character unique user id, maps to the user in user.json \"user_id\": \"Ha3iJu77CxlrFm-vQRs_8g\", // string, 22 character business id, maps to business in business.json \"business_id\": \"tnhfDv5Il8EaGSXZGiuQGg\", // integer, star rating \"stars\": 4, // string, date formatted YYYY-MM-DD \"date\": \"2016-03-09\", // string, the review itself \"text\": \"Great place to hang out after work: the prices are decent, and the ambience is fun. It's a bit loud, but very lively. The staff is friendly, and the food is good. They have a good selection of drinks.\", // integer, number of useful votes received \"useful\": 0, // integer, number of funny votes received \"funny\": 0, // integer, number of cool votes received \"cool\": 0}"
},
{
"code": null,
"e": 7630,
"s": 7414,
"text": "We can aggregate by business_id and be done with the feature engineering. However given that each impression has a time stamp associated with it, we can directly measure the changes associated with a given location."
},
{
"code": null,
"e": 7814,
"s": 7630,
"text": "The mean of user star ratings return the average business score. Grouping by year can help us see how the business features are changing by year. Are they improving or lagging behind?"
},
{
"code": null,
"e": 7920,
"s": 7814,
"text": "The first question to ask is where are those ~192,000 businesses located? Per the plot below: Vegas baby!"
},
{
"code": null,
"e": 8014,
"s": 7920,
"text": "Contrary to the plot above, the majority of businesses are located in Arizona as shown below:"
},
{
"code": null,
"e": 8138,
"s": 8014,
"text": "Furthermore we can see that the majority of businesses have a rating between 3.0 and 4.5, such that the mean is around 3.5."
},
{
"code": null,
"e": 8399,
"s": 8138,
"text": "Finally we want to compare the distribution of the positive/negative label across business types by plotting counts and color hue by target variable. Restaurants account for the large majority of businesses and have the highest proportion of closed businesses."
},
{
"code": null,
"e": 8472,
"s": 8399,
"text": "The checkin.json file lists all checkins for businesses where available:"
},
{
"code": null,
"e": 8844,
"s": 8472,
"text": "{ // string, 22 character business id, maps to business in business.json \"business_id\": \"tnhfDv5Il8EaGSXZGiuQGg\" // string which is a comma-separated list of timestamps for each checkin, each with format YYYY-MM-DD HH:MM:SS \"date\": \"2016-04-26 19:49:16, 2016-08-30 18:36:57, 2016-10-15 02:45:18, 2016-11-18 01:54:50, 2017-04-20 18:39:06, 2017-05-03 17:58:02\"}"
},
{
"code": null,
"e": 9184,
"s": 8844,
"text": "As a first step, we can explore trends in checkins as shown in the plot below, where the y-axis corresponds to the number of checkins aggregated over all the years and split by 30min intervals. For example this plot tells us that the peak average checkin from Saturday-Sunday night occurs around 8PM whilst providing a confidence interval."
},
{
"code": null,
"e": 9343,
"s": 9184,
"text": "On a more macro scale we can also explore checkins in December, which contains a lot of seasonality. In the plot below, the highlights correspond to weekends."
},
{
"code": null,
"e": 9610,
"s": 9343,
"text": "From the data we can extract what is the average monthly checkin. In addition we define the span as the time in seconds between the first and the last checkin: The longer a business has been open, the higher the probability it will remain open (see Sunrise Problem)."
},
{
"code": null,
"e": 9813,
"s": 9610,
"text": "The question we are trying to solve for falls under supervised learning. Given the heavily imbalanced nature of the target variable, we omit scoring based on accuracy and consider the following metrics:"
},
{
"code": null,
"e": 9823,
"s": 9813,
"text": "Precision"
},
{
"code": null,
"e": 9830,
"s": 9823,
"text": "Recall"
},
{
"code": null,
"e": 9839,
"s": 9830,
"text": "F1 Score"
},
{
"code": null,
"e": 9856,
"s": 9839,
"text": "Area Under Curve"
},
{
"code": null,
"e": 9973,
"s": 9856,
"text": "In a preliminary round, we apply several supervised learning algorithms. The top performers were in ascending order:"
},
{
"code": null,
"e": 9993,
"s": 9973,
"text": "Logistic regression"
},
{
"code": null,
"e": 10016,
"s": 9993,
"text": "Gradient boosted trees"
},
{
"code": null,
"e": 10030,
"s": 10016,
"text": "Random forest"
},
{
"code": null,
"e": 10038,
"s": 10030,
"text": "XGBoost"
},
{
"code": null,
"e": 10168,
"s": 10038,
"text": "In the following sections we will elaborate more on individual techniques that were coupled together to produce reliable results."
},
{
"code": null,
"e": 10361,
"s": 10168,
"text": "The intent of feature engineering is to have numerical representation of data that can be directly fed into an algorithm. The first step is to split the data between training and testing sets."
},
{
"code": null,
"e": 10538,
"s": 10361,
"text": "In addition we apply min-max feature scaling that is fitted on the training data only to avoid model leakage. The training and testing data are then transformed using that fit."
},
{
"code": null,
"e": 10721,
"s": 10538,
"text": "The method also known as GridSearchCV is popular with data scientists because it is so comprehensive. By combining cross validation with grid search, we obtain tuned hyperparameters."
},
{
"code": null,
"e": 10868,
"s": 10721,
"text": "Certain algorithms such as tree based models perform poorly in high dimensional spaces. Having too many features might also entail noisy features."
},
{
"code": null,
"e": 11101,
"s": 10868,
"text": "The first approach used to detect noisy features is via logistic regression’s L1 feature selection, which gives a weight of 0 to useless features. The second approach is using the featexp package in order to identify noisy features."
},
{
"code": null,
"e": 11423,
"s": 11101,
"text": "Ultimately the most interpretable method was permutation for feature importance. In this context we permute a given feature and calculate the change in the model’s prediction error. A feature is ‘important’ if shuffling it significantly changes the error on the model, and is ‘unimportant’ if the error remains unchanged."
},
{
"code": null,
"e": 11585,
"s": 11423,
"text": "Finally the most impactful aspect of the project was dealing with the imbalanced target variable. Recall that only about ~20% of businesses are listed as closed."
},
{
"code": null,
"e": 11817,
"s": 11585,
"text": "In practical terms this means that the minority class is overwhelmed by the majority class such that the algorithm does not have enough minority observations to draw decisions, or that the minority class is swamped by the majority."
},
{
"code": null,
"e": 12076,
"s": 11817,
"text": "One way to address this is via undersampling: keep the minority class as is and draw an equal number of observations at random from the majority class. Conversely oversampling works slightly better: duplicate the minority class until the dataset is balanced."
},
{
"code": null,
"e": 12246,
"s": 12076,
"text": "In either choice of sampling, it is crucial to apply it only on the training data. Sampling the test data is a common pitfall, since it equates to misconstruing reality."
},
{
"code": null,
"e": 12419,
"s": 12246,
"text": "The table below summarizes several model performances. Across the board, all models are better at predicting open businesses (Class 1) rather than shuttered ones (Class 0)."
},
{
"code": null,
"e": 12504,
"s": 12419,
"text": "Overall we can see tree based models tend to perform best with AUC hovering at 0.75."
},
{
"code": null,
"e": 12707,
"s": 12504,
"text": "That being said model interpretability is as important, if not more, than model performance. We must therefore dive deeper into each model to understand what are the main features driving our decisions."
},
{
"code": null,
"e": 12779,
"s": 12707,
"text": "The table below shows the top 5 most important features for the models."
},
{
"code": null,
"e": 12939,
"s": 12779,
"text": "Interestingly enough within a same model such as logistic regression, being a Restaurant can be a positive or negative weight depending on the sampling method."
},
{
"code": null,
"e": 13212,
"s": 12939,
"text": "We also notice some expected features such as RestaurantsPriceRange2 which relate to price, and some peculiar ones such as AcceptsInsurance and BikeParking. In the case of insurance, the feature might be important to businesses such as massage parlors or doctors’ clinics."
},
{
"code": null,
"e": 13291,
"s": 13212,
"text": "In the winning model, the following features are crucial for business success:"
},
{
"code": null,
"e": 13307,
"s": 13291,
"text": "Be a Restaurant"
},
{
"code": null,
"e": 13321,
"s": 13307,
"text": "Service lunch"
},
{
"code": null,
"e": 13339,
"s": 13321,
"text": "Also serve dinner"
},
{
"code": null,
"e": 13375,
"s": 13339,
"text": "Your RestaurantsPriceRange2 matters"
},
{
"code": null,
"e": 13386,
"s": 13375,
"text": "Be a chain"
},
{
"code": null,
"e": 13565,
"s": 13386,
"text": "The main features for XGBoost were obtained from the feature_importances_ attribute. However we wish to find a way to explain our output and how to optimize for business success."
},
{
"code": null,
"e": 13853,
"s": 13565,
"text": "For this study we use the SHAP (SHapley Additive exPlanation) package to derive individualized feature attributions. Shapley values are primarily used on a per-prediction basis to help with explainability, and answer questions like “What caused my business to be marked as being closed?”"
},
{
"code": null,
"e": 14006,
"s": 13853,
"text": "To justify the use of SHAP, we present the plot_importance method in XGBoost that produces three different interpretations based on the importance type."
},
{
"code": null,
"e": 14061,
"s": 14006,
"text": "weight the number of times a feature appears in a tree"
},
{
"code": null,
"e": 14115,
"s": 14061,
"text": "gain the average gain of splits which use the feature"
},
{
"code": null,
"e": 14247,
"s": 14115,
"text": "cover the average coverage of splits which use the feature where coverage is defined as the number of samples affected by the split"
},
{
"code": null,
"e": 14571,
"s": 14247,
"text": "In the plot below we show the mean absolute value of the SHAP values. The x-axis shows the average magnitude change in the model output when a feature is hidden from the model. Given that hiding a feature changes depending on what other features are also hidden, Shapley values are used to enforce consistency and accuracy."
},
{
"code": null,
"e": 15054,
"s": 14571,
"text": "The plot below is a density scatter plot of SHAP values for each feature to identify how much impact each feature has on the model output for each observation in the dataset. The summary plot combines feature importance with feature effects. Each point on the summary plot is a Shapley value for a feature and an instance. The position on the y-axis is determined by the feature and on the x-axis by the Shapley value. The color represents the value of the feature from low to high."
},
{
"code": null,
"e": 15491,
"s": 15054,
"text": "The coloring by feature shows us that having your stars_change (average change in stars rating over time) increase is a good predictor to stay open. For review_count (the number of reviews) not having a lot can harm you, however having a high reiew_count can also mean a high volume of negative reviews. For the third most important feature useful (total count of useful review votes), it appears to be a positive indicator for success."
},
{
"code": null,
"e": 15893,
"s": 15491,
"text": "The plot also allows us to to identify outliers since overlapping points are jittered in y-axis direction, so we get a sense of the distribution of the Shapley values per feature. For a particular subset of businesses, having a high count of useful can actually be an indicator of closing soon. For example, it is not unheard of for someone to comment “Stay away from the chicken, seemed undercooked”."
},
{
"code": null,
"e": 16186,
"s": 15893,
"text": "SHAP dependence plots are an additional visualization to show the effect of a single feature across the whole dataset. Contrary to partial dependence plots, SHAP account for the interaction effects present in the features, and are only defined in regions of the input space supported by data."
},
{
"code": null,
"e": 16302,
"s": 16186,
"text": "The plot below applies to review_density (normalized review count of business versus all others within 2km radius)."
},
{
"code": null,
"e": 16687,
"s": 16302,
"text": "In the plot above the vertical dispersion is driven by interaction effects and another feature, here RestaurantsGoodForGroups , is chosen for coloring to highlight possible interactions. We can see here that having a higher review count relative to other businesses is a good indicator for success. In addition, being good for groups tends to correlate positively with review_density."
},
{
"code": null,
"e": 16837,
"s": 16687,
"text": "The correlation matrix below ties into the plot from above. We can notice a positive correlation between review_density and RestaurantsGoodForGroups."
},
{
"code": null,
"e": 17130,
"s": 16837,
"text": "Knowing if a business will close its doors or stay open is a study entrepreneurs take before investing. With machine learning, we are able to identify features that can predict for the original question of this article. We were also able to provide model interpretability on a per-user basis."
},
{
"code": null,
"e": 17365,
"s": 17130,
"text": "Although a comprehensive answer to the problem might not be obtained, the solution nonetheless offers a path forward. Businesses can use the model interpretations to optimize for success and know the metrics they need to improve upon."
},
{
"code": null,
"e": 17595,
"s": 17365,
"text": "Looking forward we can take advantage of the text information within the review.json file. A sample NLP exercise would be to extract sentiments or group of words in function of time or location that indicate business performance."
}
] |
Packages in C#
|
As an alternative of Packages in Java, the C# language has namespace.
Packages are used in Java in order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.
A namespace is designed for providing a way to keep one set of names separate from another. The class names declared in one namespace does not conflict with the same class names declared in another.
A namespace definition begins with the keyword namespace followed by the namespace name. The following shows how to work with namespace in C# −
using System;
namespace first_space {
class namespace_cl {
public void func() {
Console.WriteLine("Inside first_space");
}
}
}
namespace second_space {
class namespace_cl {
public void func() {
Console.WriteLine("Inside second_space");
}
}
}
class TestClass {
static void Main(string[] args) {
first_space.namespace_cl fc = new first_space.namespace_cl();
second_space.namespace_cl sc = new second_space.namespace_cl();
fc.func();
sc.func();
Console.ReadKey();
}
}
|
[
{
"code": null,
"e": 1132,
"s": 1062,
"text": "As an alternative of Packages in Java, the C# language has namespace."
},
{
"code": null,
"e": 1318,
"s": 1132,
"text": "Packages are used in Java in order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc."
},
{
"code": null,
"e": 1517,
"s": 1318,
"text": "A namespace is designed for providing a way to keep one set of names separate from another. The class names declared in one namespace does not conflict with the same class names declared in another."
},
{
"code": null,
"e": 1661,
"s": 1517,
"text": "A namespace definition begins with the keyword namespace followed by the namespace name. The following shows how to work with namespace in C# −"
},
{
"code": null,
"e": 2220,
"s": 1661,
"text": "using System;\n\nnamespace first_space {\n class namespace_cl {\n public void func() {\n Console.WriteLine(\"Inside first_space\");\n }\n }\n}\n\nnamespace second_space {\n class namespace_cl {\n public void func() {\n Console.WriteLine(\"Inside second_space\");\n }\n }\n}\n\nclass TestClass {\n static void Main(string[] args) {\n first_space.namespace_cl fc = new first_space.namespace_cl();\n second_space.namespace_cl sc = new second_space.namespace_cl();\n\n fc.func();\n sc.func();\n Console.ReadKey();\n }\n}"
}
] |
Set existing column as Primary Key in MySQL?
|
You can set primary key on an existing column in MySQL with the help of alter command.
The syntax is as follows to add primary key to an existing column.
ALTER TABLE yourTableName ADD PRIMARY KEY(yourColumnName);
To set existing column as primary key, let us first create a table. The query to create a table −
mysql> create table AddingPrimaryKeyDemo
−> (
−> UniversityId int,
−> UniversityName varchar(200)
−> );
Query OK, 0 rows affected (1.16 sec)
Look at the above query, I haven’t added primary key. Let us check the same with the help of DESC command. The query is as follows −
mysql> desc AddingPrimaryKeyDemo;
The following is the output −
+----------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------------+--------------+------+-----+---------+-------+
| UniversityId | int(11) | YES | | NULL | |
| UniversityName | varchar(200) | YES | | NULL | |
+----------------+--------------+------+-----+---------+-------+
2 rows in set (0.09 sec)
Now you can set existing column as primary key with the help of the syntax discussed in the beginning. The query to add primary key is as follows −
mysql> alter table AddingPrimaryKeyDemo add primary key(UniversityId);
Query OK, 0 rows affected (1.48 sec)
Records: 0 Duplicates: 0 Warnings: 0
Now I have added primary to existing column ‘UniversityId’. The following command will give a result that would check the existence of primary key on column ‘UniversityId’.
mysql> desc AddingPrimaryKeyDemo;
The following is the output −
+----------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------------+--------------+------+-----+---------+-------+
| UniversityId | int(11) | NO | PRI | NULL | |
| UniversityName | varchar(200) | YES | | NULL | |
+----------------+--------------+------+-----+---------+-------+
2 rows in set (0.04 sec)
We can see “PRI” above, therefore Primary Key successfully added.
|
[
{
"code": null,
"e": 1149,
"s": 1062,
"text": "You can set primary key on an existing column in MySQL with the help of alter command."
},
{
"code": null,
"e": 1216,
"s": 1149,
"text": "The syntax is as follows to add primary key to an existing column."
},
{
"code": null,
"e": 1275,
"s": 1216,
"text": "ALTER TABLE yourTableName ADD PRIMARY KEY(yourColumnName);"
},
{
"code": null,
"e": 1373,
"s": 1275,
"text": "To set existing column as primary key, let us first create a table. The query to create a table −"
},
{
"code": null,
"e": 1532,
"s": 1373,
"text": "mysql> create table AddingPrimaryKeyDemo\n −> (\n −> UniversityId int,\n −> UniversityName varchar(200)\n −> );\nQuery OK, 0 rows affected (1.16 sec)"
},
{
"code": null,
"e": 1665,
"s": 1532,
"text": "Look at the above query, I haven’t added primary key. Let us check the same with the help of DESC command. The query is as follows −"
},
{
"code": null,
"e": 1699,
"s": 1665,
"text": "mysql> desc AddingPrimaryKeyDemo;"
},
{
"code": null,
"e": 1729,
"s": 1699,
"text": "The following is the output −"
},
{
"code": null,
"e": 2144,
"s": 1729,
"text": "+----------------+--------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+----------------+--------------+------+-----+---------+-------+\n| UniversityId | int(11) | YES | | NULL | |\n| UniversityName | varchar(200) | YES | | NULL | |\n+----------------+--------------+------+-----+---------+-------+\n2 rows in set (0.09 sec)"
},
{
"code": null,
"e": 2292,
"s": 2144,
"text": "Now you can set existing column as primary key with the help of the syntax discussed in the beginning. The query to add primary key is as follows −"
},
{
"code": null,
"e": 2437,
"s": 2292,
"text": "mysql> alter table AddingPrimaryKeyDemo add primary key(UniversityId);\nQuery OK, 0 rows affected (1.48 sec)\nRecords: 0 Duplicates: 0 Warnings: 0"
},
{
"code": null,
"e": 2610,
"s": 2437,
"text": "Now I have added primary to existing column ‘UniversityId’. The following command will give a result that would check the existence of primary key on column ‘UniversityId’."
},
{
"code": null,
"e": 2644,
"s": 2610,
"text": "mysql> desc AddingPrimaryKeyDemo;"
},
{
"code": null,
"e": 2674,
"s": 2644,
"text": "The following is the output −"
},
{
"code": null,
"e": 3089,
"s": 2674,
"text": "+----------------+--------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+----------------+--------------+------+-----+---------+-------+\n| UniversityId | int(11) | NO | PRI | NULL | |\n| UniversityName | varchar(200) | YES | | NULL | |\n+----------------+--------------+------+-----+---------+-------+\n2 rows in set (0.04 sec)"
},
{
"code": null,
"e": 3155,
"s": 3089,
"text": "We can see “PRI” above, therefore Primary Key successfully added."
}
] |
Android - Sensors
|
Most of the android devices have built-in sensors that measure motion, orientation, and various environmental condition. The android platform supports three broad categories of sensors.
Motion Sensors
Environmental sensors
Position sensors
Some of the sensors are hardware based and some are software based sensors. Whatever the sensor is, android allows us to get the raw data from these sensors and use it in our application. For this android provides us with some classes.
Android provides SensorManager and Sensor classes to use the sensors in our application. In order to use sensors, first thing you need to do is to instantiate the object of SensorManager class. It can be achieved as follows.
SensorManager sMgr;
sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE);
The next thing you need to do is to instantiate the object of Sensor class by calling the getDefaultSensor() method of the SensorManager class. Its syntax is given below −
Sensor light;
light = sMgr.getDefaultSensor(Sensor.TYPE_LIGHT);
Once that sensor is declared , you need to register its listener and override two methods which are onAccuracyChanged and onSensorChanged. Its syntax is as follows −
sMgr.registerListener(this, light,SensorManager.SENSOR_DELAY_NORMAL);
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
}
You can get a list of sensors supported by your device by calling the getSensorList method, which will return a list of sensors containing their name and version number and much more information. You can then iterate the list to get the information. Its syntax is given below −
sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE);
List<Sensor> list = sMgr.getSensorList(Sensor.TYPE_ALL);
for(Sensor sensor: list){
}
Apart from the these methods, there are other methods provided by the SensorManager class for managing sensors framework. These methods are listed below −
getDefaultSensor(int type)
This method get the default sensor for a given type.
getInclination(float[] I)
This method computes the geomagnetic inclination angle in radians from the inclination matrix.
registerListener(SensorListener listener, int sensors, int rate)
This method registers a listener for the sensor
unregisterListener(SensorEventListener listener, Sensor sensor)
This method unregisters a listener for the sensors with which it is registered.
getOrientation(float[] R, float[] values)
This method computes the device's orientation based on the rotation matrix.
getAltitude(float p0, float p)
This method computes the Altitude in meters from the atmospheric pressure and the pressure at sea level.
Here is an example demonstrating the use of SensorManager class. It creates a basic application that allows you to view the list of sensors on your device.
To experiment with this example , you can run this on an actual device or in an emulator.
Following is the content of the modified MainActivity.java.
package com.example.sairamkrishna.myapplication;
import android.app.Activity;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import java.util.List;
import android.hardware.Sensor;
import android.hardware.SensorManager;
public class MainActivity extends Activity {
TextView tv1=null;
private SensorManager mSensorManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView) findViewById(R.id.textView2);
tv1.setVisibility(View.GONE);
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
List<Sensor> mList= mSensorManager.getSensorList(Sensor.TYPE_ALL);
for (int i = 1; i < mList.size(); i++) {
tv1.setVisibility(View.VISIBLE);
tv1.append("\n" + mList.get(i).getName() + "\n" + mList.get(i).getVendor() + "\n" + mList.get(i).getVersion());
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Following is the modified content of the xml 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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:transitionGroup="true">
<TextView android:text="Sensor " android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:theme="@style/Base.TextAppearance.AppCompat" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="@+id/textView2"
android:layout_below="@+id/imageView"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
Following is the content of the res/values/string.xml.
<resources>
<string name="app_name">My Application</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
</resources>
Following is the content of AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<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 our application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −
Now if you will look at your device screen, you will see the list of sensors supported by your device along with their name and version and other information.
If you would run this application on different devices, the output would be different because the output depends upon the number of sensors supported by your device.
46 Lectures
7.5 hours
Aditya Dua
32 Lectures
3.5 hours
Sharad Kumar
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3793,
"s": 3607,
"text": "Most of the android devices have built-in sensors that measure motion, orientation, and various environmental condition. The android platform supports three broad categories of sensors."
},
{
"code": null,
"e": 3808,
"s": 3793,
"text": "Motion Sensors"
},
{
"code": null,
"e": 3830,
"s": 3808,
"text": "Environmental sensors"
},
{
"code": null,
"e": 3847,
"s": 3830,
"text": "Position sensors"
},
{
"code": null,
"e": 4083,
"s": 3847,
"text": "Some of the sensors are hardware based and some are software based sensors. Whatever the sensor is, android allows us to get the raw data from these sensors and use it in our application. For this android provides us with some classes."
},
{
"code": null,
"e": 4308,
"s": 4083,
"text": "Android provides SensorManager and Sensor classes to use the sensors in our application. In order to use sensors, first thing you need to do is to instantiate the object of SensorManager class. It can be achieved as follows."
},
{
"code": null,
"e": 4390,
"s": 4308,
"text": "SensorManager sMgr;\nsMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE);\n"
},
{
"code": null,
"e": 4562,
"s": 4390,
"text": "The next thing you need to do is to instantiate the object of Sensor class by calling the getDefaultSensor() method of the SensorManager class. Its syntax is given below −"
},
{
"code": null,
"e": 4627,
"s": 4562,
"text": "Sensor light;\nlight = sMgr.getDefaultSensor(Sensor.TYPE_LIGHT);\n"
},
{
"code": null,
"e": 4793,
"s": 4627,
"text": "Once that sensor is declared , you need to register its listener and override two methods which are onAccuracyChanged and onSensorChanged. Its syntax is as follows −"
},
{
"code": null,
"e": 4979,
"s": 4793,
"text": "sMgr.registerListener(this, light,SensorManager.SENSOR_DELAY_NORMAL);\npublic void onAccuracyChanged(Sensor sensor, int accuracy) {\n}\n\npublic void onSensorChanged(SensorEvent event) {\n}\n"
},
{
"code": null,
"e": 5257,
"s": 4979,
"text": "You can get a list of sensors supported by your device by calling the getSensorList method, which will return a list of sensors containing their name and version number and much more information. You can then iterate the list to get the information. Its syntax is given below −"
},
{
"code": null,
"e": 5403,
"s": 5257,
"text": "sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE);\nList<Sensor> list = sMgr.getSensorList(Sensor.TYPE_ALL);\nfor(Sensor sensor: list){\n}"
},
{
"code": null,
"e": 5558,
"s": 5403,
"text": "Apart from the these methods, there are other methods provided by the SensorManager class for managing sensors framework. These methods are listed below −"
},
{
"code": null,
"e": 5585,
"s": 5558,
"text": "getDefaultSensor(int type)"
},
{
"code": null,
"e": 5638,
"s": 5585,
"text": "This method get the default sensor for a given type."
},
{
"code": null,
"e": 5664,
"s": 5638,
"text": "getInclination(float[] I)"
},
{
"code": null,
"e": 5759,
"s": 5664,
"text": "This method computes the geomagnetic inclination angle in radians from the inclination matrix."
},
{
"code": null,
"e": 5824,
"s": 5759,
"text": "registerListener(SensorListener listener, int sensors, int rate)"
},
{
"code": null,
"e": 5872,
"s": 5824,
"text": "This method registers a listener for the sensor"
},
{
"code": null,
"e": 5936,
"s": 5872,
"text": "unregisterListener(SensorEventListener listener, Sensor sensor)"
},
{
"code": null,
"e": 6016,
"s": 5936,
"text": "This method unregisters a listener for the sensors with which it is registered."
},
{
"code": null,
"e": 6058,
"s": 6016,
"text": "getOrientation(float[] R, float[] values)"
},
{
"code": null,
"e": 6134,
"s": 6058,
"text": "This method computes the device's orientation based on the rotation matrix."
},
{
"code": null,
"e": 6165,
"s": 6134,
"text": "getAltitude(float p0, float p)"
},
{
"code": null,
"e": 6270,
"s": 6165,
"text": "This method computes the Altitude in meters from the atmospheric pressure and the pressure at sea level."
},
{
"code": null,
"e": 6426,
"s": 6270,
"text": "Here is an example demonstrating the use of SensorManager class. It creates a basic application that allows you to view the list of sensors on your device."
},
{
"code": null,
"e": 6516,
"s": 6426,
"text": "To experiment with this example , you can run this on an actual device or in an emulator."
},
{
"code": null,
"e": 6576,
"s": 6516,
"text": "Following is the content of the modified MainActivity.java."
},
{
"code": null,
"e": 8422,
"s": 6576,
"text": "package com.example.sairamkrishna.myapplication;\n\nimport android.app.Activity;\nimport android.hardware.SensorManager;\nimport android.os.Bundle;\n\nimport android.util.Log;\n\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\n\nimport android.widget.TextView;\n\nimport java.util.List;\nimport android.hardware.Sensor;\nimport android.hardware.SensorManager;\n\npublic class MainActivity extends Activity {\n TextView tv1=null;\n private SensorManager mSensorManager;\n @Override\n \n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n \n tv1 = (TextView) findViewById(R.id.textView2);\n tv1.setVisibility(View.GONE);\n \n mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);\n List<Sensor> mList= mSensorManager.getSensorList(Sensor.TYPE_ALL);\n \n for (int i = 1; i < mList.size(); i++) {\n tv1.setVisibility(View.VISIBLE);\n tv1.append(\"\\n\" + mList.get(i).getName() + \"\\n\" + mList.get(i).getVendor() + \"\\n\" + mList.get(i).getVersion());\n }\n }\n\t\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n // Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu.menu_main, menu);\n return true;\n }\n \n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n // Handle action bar item clicks here. The action bar will\n // automatically handle clicks on the Home/Up button, so long\n // as you specify a parent activity in AndroidManifest.xml.\n \n int id = item.getItemId();\n \n //noinspection SimplifiableIfStatement\n if (id == R.id.action_settings) {\n return true;\n }\n return super.onOptionsItemSelected(item);\n }\n}"
},
{
"code": null,
"e": 8486,
"s": 8422,
"text": "Following is the modified content of the xml activity_main.xml."
},
{
"code": null,
"e": 10373,
"s": 8486,
"text": "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n android:paddingRight=\"@dimen/activity_horizontal_margin\"\n android:paddingTop=\"@dimen/activity_vertical_margin\"\n android:paddingBottom=\"@dimen/activity_vertical_margin\"\n tools:context=\".MainActivity\"\n android:transitionGroup=\"true\">\n \n <TextView android:text=\"Sensor \" android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/textview\"\n android:textSize=\"35dp\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\" />\n \n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Tutorials point\"\n android:id=\"@+id/textView\"\n android:layout_below=\"@+id/textview\"\n android:layout_centerHorizontal=\"true\"\n android:textColor=\"#ff7aff24\"\n android:textSize=\"35dp\" />\n \n <ImageView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/imageView\"\n android:src=\"@drawable/abc\"\n android:layout_below=\"@+id/textView\"\n android:layout_centerHorizontal=\"true\"\n android:theme=\"@style/Base.TextAppearance.AppCompat\" />\n \n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"New Text\"\n android:id=\"@+id/textView2\"\n android:layout_below=\"@+id/imageView\"\n android:layout_alignParentBottom=\"true\"\n android:layout_alignParentRight=\"true\"\n android:layout_alignParentEnd=\"true\"\n android:layout_alignParentLeft=\"true\"\n android:layout_alignParentStart=\"true\" />\n\n</RelativeLayout>"
},
{
"code": null,
"e": 10428,
"s": 10373,
"text": "Following is the content of the res/values/string.xml."
},
{
"code": null,
"e": 10608,
"s": 10428,
"text": "<resources>\n <string name=\"app_name\">My Application</string>\n <string name=\"hello_world\">Hello world!</string>\n <string name=\"action_settings\">Settings</string>\n</resources>"
},
{
"code": null,
"e": 10662,
"s": 10608,
"text": "Following is the content of AndroidManifest.xml file."
},
{
"code": null,
"e": 11363,
"s": 10662,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.sairamkrishna.myapplication\" >\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:theme=\"@style/AppTheme\" >\n \n <activity\n android:name=\".MainActivity\"\n android:label=\"@string/app_name\" >\n \n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n \n </activity>\n \n </application>\n</manifest>"
},
{
"code": null,
"e": 11756,
"s": 11363,
"text": "Let's try to run our application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −"
},
{
"code": null,
"e": 11915,
"s": 11756,
"text": "Now if you will look at your device screen, you will see the list of sensors supported by your device along with their name and version and other information."
},
{
"code": null,
"e": 12081,
"s": 11915,
"text": "If you would run this application on different devices, the output would be different because the output depends upon the number of sensors supported by your device."
},
{
"code": null,
"e": 12116,
"s": 12081,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 12128,
"s": 12116,
"text": " Aditya Dua"
},
{
"code": null,
"e": 12163,
"s": 12128,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 12177,
"s": 12163,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 12209,
"s": 12177,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 12226,
"s": 12209,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 12261,
"s": 12226,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 12278,
"s": 12261,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 12313,
"s": 12278,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 12330,
"s": 12313,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 12363,
"s": 12330,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 12380,
"s": 12363,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 12387,
"s": 12380,
"text": " Print"
},
{
"code": null,
"e": 12398,
"s": 12387,
"text": " Add Notes"
}
] |
Create HTML User Interface using Eel in Python - GeeksforGeeks
|
08 May, 2021
Eel is a Python library for making simple offline HTML/JS GUI apps, with full access to Python capabilities and libraries. Eel hosts a local webserver, then lets you annotate functions in Python so that they can be called from Javascript, and vice versa.
To install this module type the below command in the terminal.
pip install eel
First, create a project folder and make another folder called web under it. The web folder consists of all the website files. Create a main.py python file outside the web folder inside project folder.
This should build a folder like below :
Files and Folders
To use eel in the frontend javascript. Include the following code in the HTML file :
<script type=”text/javascript” src=”/eel.js”></script>
Including this library creates an eel object which can be used to communicate with the Python side. Any functions in the Python code which are decorated with @eel.expose like this:
@eel.expose
def function():
Any python function that is exposed using eel.expose can be called in the javascript like below :
eel.python_function_name()(callback);
Below is an example in which python has a function random_python which returns a random number between 1 and 100, Javascript calls the and then grabs the returned number and changes a div’s innerHTML.
The HTML file here is used to create a window that displays all the required attributes, the javascript file will be called by the HTML file to add dynamism to the window created. Python code is used to make this all work.
HTML file :
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Eel Example</title> <style> h1{ color: green; text-align: center; } .random_number{ margin: 50px; font-size: 150px; text-align: center; } button{ display: block; margin: 0 auto; } </style> </head> <body> <h1>Geeks for Geeks</h1> <div class="random_number"></div> <button>Get a Random number using Python</button> <script type="text/javascript" src="../eel.js"></script> <script src="./script.js"></script> </body></html>
script.js :
Javascript
// Onclick of the buttondocument.querySelector("button").onclick = function () { // Call python's random_python function eel.random_python()(function(number){ // Update the div with a random number returned by python document.querySelector(".random_number").innerHTML = number; })}
The main.py contains :
Python3
import eelfrom random import randint eel.init("web") # Exposing the random_python function to javascript@eel.expose def random_python(): print("Random function running") return randint(1,100) # Start the index.html fileeel.start("index.html")
Output :
Note: Here the javascript is calling the python function, when python returns the data it changes the div text.
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Python - Call function from another file
loops in python
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
Python Lambda Functions
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n08 May, 2021"
},
{
"code": null,
"e": 24156,
"s": 23901,
"text": "Eel is a Python library for making simple offline HTML/JS GUI apps, with full access to Python capabilities and libraries. Eel hosts a local webserver, then lets you annotate functions in Python so that they can be called from Javascript, and vice versa."
},
{
"code": null,
"e": 24219,
"s": 24156,
"text": "To install this module type the below command in the terminal."
},
{
"code": null,
"e": 24235,
"s": 24219,
"text": "pip install eel"
},
{
"code": null,
"e": 24436,
"s": 24235,
"text": "First, create a project folder and make another folder called web under it. The web folder consists of all the website files. Create a main.py python file outside the web folder inside project folder."
},
{
"code": null,
"e": 24477,
"s": 24436,
"text": "This should build a folder like below : "
},
{
"code": null,
"e": 24495,
"s": 24477,
"text": "Files and Folders"
},
{
"code": null,
"e": 24581,
"s": 24495,
"text": "To use eel in the frontend javascript. Include the following code in the HTML file : "
},
{
"code": null,
"e": 24636,
"s": 24581,
"text": "<script type=”text/javascript” src=”/eel.js”></script>"
},
{
"code": null,
"e": 24817,
"s": 24636,
"text": "Including this library creates an eel object which can be used to communicate with the Python side. Any functions in the Python code which are decorated with @eel.expose like this:"
},
{
"code": null,
"e": 24829,
"s": 24817,
"text": "@eel.expose"
},
{
"code": null,
"e": 24846,
"s": 24829,
"text": "def function(): "
},
{
"code": null,
"e": 24945,
"s": 24846,
"text": "Any python function that is exposed using eel.expose can be called in the javascript like below : "
},
{
"code": null,
"e": 24986,
"s": 24945,
"text": " eel.python_function_name()(callback); "
},
{
"code": null,
"e": 25187,
"s": 24986,
"text": "Below is an example in which python has a function random_python which returns a random number between 1 and 100, Javascript calls the and then grabs the returned number and changes a div’s innerHTML."
},
{
"code": null,
"e": 25410,
"s": 25187,
"text": "The HTML file here is used to create a window that displays all the required attributes, the javascript file will be called by the HTML file to add dynamism to the window created. Python code is used to make this all work."
},
{
"code": null,
"e": 25423,
"s": 25410,
"text": "HTML file : "
},
{
"code": null,
"e": 25428,
"s": 25423,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Eel Example</title> <style> h1{ color: green; text-align: center; } .random_number{ margin: 50px; font-size: 150px; text-align: center; } button{ display: block; margin: 0 auto; } </style> </head> <body> <h1>Geeks for Geeks</h1> <div class=\"random_number\"></div> <button>Get a Random number using Python</button> <script type=\"text/javascript\" src=\"../eel.js\"></script> <script src=\"./script.js\"></script> </body></html>",
"e": 26165,
"s": 25428,
"text": null
},
{
"code": null,
"e": 26178,
"s": 26165,
"text": "script.js : "
},
{
"code": null,
"e": 26189,
"s": 26178,
"text": "Javascript"
},
{
"code": "// Onclick of the buttondocument.querySelector(\"button\").onclick = function () { // Call python's random_python function eel.random_python()(function(number){ // Update the div with a random number returned by python document.querySelector(\".random_number\").innerHTML = number; })}",
"e": 26504,
"s": 26189,
"text": null
},
{
"code": null,
"e": 26528,
"s": 26504,
"text": "The main.py contains : "
},
{
"code": null,
"e": 26536,
"s": 26528,
"text": "Python3"
},
{
"code": "import eelfrom random import randint eel.init(\"web\") # Exposing the random_python function to javascript@eel.expose def random_python(): print(\"Random function running\") return randint(1,100) # Start the index.html fileeel.start(\"index.html\")",
"e": 26793,
"s": 26536,
"text": null
},
{
"code": null,
"e": 26802,
"s": 26793,
"text": "Output :"
},
{
"code": null,
"e": 26916,
"s": 26804,
"text": "Note: Here the javascript is calling the python function, when python returns the data it changes the div text."
},
{
"code": null,
"e": 26931,
"s": 26916,
"text": "python-modules"
},
{
"code": null,
"e": 26938,
"s": 26931,
"text": "Python"
},
{
"code": null,
"e": 27036,
"s": 26938,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27045,
"s": 27036,
"text": "Comments"
},
{
"code": null,
"e": 27058,
"s": 27045,
"text": "Old Comments"
},
{
"code": null,
"e": 27094,
"s": 27058,
"text": "Box Plot in Python using Matplotlib"
},
{
"code": null,
"e": 27117,
"s": 27094,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 27156,
"s": 27117,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27189,
"s": 27156,
"text": "Python | Convert set into a list"
},
{
"code": null,
"e": 27238,
"s": 27189,
"text": "Ways to filter Pandas DataFrame by column values"
},
{
"code": null,
"e": 27279,
"s": 27238,
"text": "Python - Call function from another file"
},
{
"code": null,
"e": 27295,
"s": 27279,
"text": "loops in python"
},
{
"code": null,
"e": 27346,
"s": 27295,
"text": "Multithreading in Python | Set 2 (Synchronization)"
},
{
"code": null,
"e": 27378,
"s": 27346,
"text": "Python Dictionary keys() method"
}
] |
Java Examples - Display a pie chart
|
How to display a pie chart using a frame?
Following example displays how to a display a piechart by making Slices class & creating arc depending on the slices.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;
import javax.swing.JFrame;
class Slice {
double value;
Color color;
public Slice(double value, Color color) {
this.value = value;
this.color = color;
}
}
class MyComponent extends JComponent {
Slice[] slices = {
new Slice(5, Color.black), new Slice(33, Color.green), new Slice(20, Color.yellow), new Slice(15, Color.red)
};
MyComponent() {}
public void paint(Graphics g) {
drawPie((Graphics2D) g, getBounds(), slices);
}
void drawPie(Graphics2D g, Rectangle area, Slice[] slices) {
double total = 0.0D;
for (int i = 0; i < slices.length; i++) {
total += slices[i].value;
}
double curValue = 0.0D;
int startAngle = 0;
for (int i = 0; i < slices.length; i++) {
startAngle = (int) (curValue * 360 / total);
int arcAngle = (int) (slices[i].value * 360 / total);
g.setColor(slices[i].color);
g.fillArc(area.x, area.y, area.width, area.height, startAngle, arcAngle);
curValue += slices[i].value;
}
}
}
public class Main {
public static void main(String[] argv) {
JFrame frame = new JFrame();
frame.getContentPane().add(new MyComponent());
frame.setSize(300, 200);
frame.setVisible(true);
}
}
The above code sample will produce the following result.
Displays a piechart in a frame.
The following is an example to display a pie chart using a frame.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;
import javax.swing.JFrame;
class Part {
double value;
Color color;
public Part(double value, Color color) {
this.value = value;
this.color = color;
}
}
class MyComponent extends JComponent {
Part[] slices = {
new Part(15, Color.yellow), new Part(30, Color.white), new Part(25, Color.blue), new Part(30, Color.red)
};
MyComponent() {
}
public void paint(Graphics g) {
drawPie((Graphics2D) g, getBounds(), slices);
}
void drawPie(Graphics2D g, Rectangle area, Part[] slices) {
double total = 0.0D;
for (int i = 0; i < slices.length; i++) {
total += slices[i].value;
}
double curValue = 0.0D;
int startAngle = 0;
for (int i = 0; i < slices.length; i++) {
startAngle = (int) (curValue * 360 / total);
int arcAngle = (int) (slices[i].value * 360 / total);
g.setColor(slices[i].color);
g.fillArc(area.x, area.y, area.width, area.height, startAngle, arcAngle);
curValue += slices[i].value;
}
}
}
public class Panel {
public static void main(String[] argv) {
JFrame frame = new JFrame();
frame.getContentPane().add(new MyComponent());
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2110,
"s": 2068,
"text": "How to display a pie chart using a frame?"
},
{
"code": null,
"e": 2228,
"s": 2110,
"text": "Following example displays how to a display a piechart by making Slices class & creating arc depending on the slices."
},
{
"code": null,
"e": 3644,
"s": 2228,
"text": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.Rectangle;\nimport javax.swing.JComponent;\nimport javax.swing.JFrame;\n\nclass Slice {\n double value;\n Color color;\n public Slice(double value, Color color) { \n this.value = value;\n this.color = color;\n }\n}\nclass MyComponent extends JComponent {\n Slice[] slices = { \n new Slice(5, Color.black), new Slice(33, Color.green), new Slice(20, Color.yellow), new Slice(15, Color.red) \n };\n MyComponent() {}\n public void paint(Graphics g) {\n drawPie((Graphics2D) g, getBounds(), slices);\n }\n void drawPie(Graphics2D g, Rectangle area, Slice[] slices) {\n double total = 0.0D;\n \n for (int i = 0; i < slices.length; i++) {\n total += slices[i].value;\n }\n double curValue = 0.0D;\n int startAngle = 0;\n for (int i = 0; i < slices.length; i++) {\n startAngle = (int) (curValue * 360 / total);\n int arcAngle = (int) (slices[i].value * 360 / total);\n g.setColor(slices[i].color);\n g.fillArc(area.x, area.y, area.width, area.height, startAngle, arcAngle);\n curValue += slices[i].value;\n }\n }\n}\npublic class Main {\n public static void main(String[] argv) {\n JFrame frame = new JFrame();\n frame.getContentPane().add(new MyComponent());\n frame.setSize(300, 200);\n frame.setVisible(true);\n }\n}"
},
{
"code": null,
"e": 3701,
"s": 3644,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 3734,
"s": 3701,
"text": "Displays a piechart in a frame.\n"
},
{
"code": null,
"e": 3800,
"s": 3734,
"text": "The following is an example to display a pie chart using a frame."
},
{
"code": null,
"e": 5222,
"s": 3800,
"text": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.Rectangle;\nimport javax.swing.JComponent;\nimport javax.swing.JFrame;\n\nclass Part {\n double value;\n Color color;\n \n public Part(double value, Color color) {\n this.value = value;\n this.color = color;\n }\n}\nclass MyComponent extends JComponent {\n Part[] slices = { \n new Part(15, Color.yellow), new Part(30, Color.white), new Part(25, Color.blue), new Part(30, Color.red) \n }; \n MyComponent() {\n }\n public void paint(Graphics g) {\n drawPie((Graphics2D) g, getBounds(), slices);\n } \n void drawPie(Graphics2D g, Rectangle area, Part[] slices) {\n double total = 0.0D;\n for (int i = 0; i < slices.length; i++) {\n total += slices[i].value;\n } \n double curValue = 0.0D;\n int startAngle = 0;\n for (int i = 0; i < slices.length; i++) {\n startAngle = (int) (curValue * 360 / total);\n int arcAngle = (int) (slices[i].value * 360 / total);\n \n g.setColor(slices[i].color);\n g.fillArc(area.x, area.y, area.width, area.height, startAngle, arcAngle);\n curValue += slices[i].value;\n } \n }\n}\npublic class Panel {\n public static void main(String[] argv) {\n JFrame frame = new JFrame();\n frame.getContentPane().add(new MyComponent());\n frame.setSize(300, 200);\n frame.setVisible(true);\n }\n}"
},
{
"code": null,
"e": 5229,
"s": 5222,
"text": " Print"
},
{
"code": null,
"e": 5240,
"s": 5229,
"text": " Add Notes"
}
] |
C Program to check if two given strings are isomorphic to each other - GeeksforGeeks
|
04 Oct, 2021
Given two strings str1 and str2, the task is to check if the two given strings are isomorphic to each other or not.
Two strings are said to be isomorphic if there is a one to one mapping possible for every character of str1 to every character of str2 and all occurrences of every character in str1 map to same character in str2.
Examples:
Input: str1 = “egg”, str2 = “add” Output: Yes Explanation: ‘e’ in str1 with ASCII value 101 is mapped to ‘a’ in str2 with ASCII value 97. ‘g’ in str1 with ASCII value 103 is mapped to ‘d’ in str2 with ASCII value 100.
Input: str1 = “eggs”, str2 = “add” Output: No
Hashing Approach: Refer to the previous post for the Hashmap based approach.
Time Complexity: O(N) Auxiliary Space: O(256)
ASCII-value based Approach: The idea is similar to that of the above approach. Follow the steps below to solve the problem:
Initialize two arrays of size 256.Iterate through characters of the given strings and increment the index equal to the ASCII value of the character at ith position.If the are no conflicts in the mapping of the characters, print Yes. Otherwise, print No.
Initialize two arrays of size 256.
Iterate through characters of the given strings and increment the index equal to the ASCII value of the character at ith position.
If the are no conflicts in the mapping of the characters, print Yes. Otherwise, print No.
Below is the implementation of the above approach:
C
// C Program to implement// the above approach #include <stdio.h>#include <string.h>#include <stdbool.h> // Function to check and return if strings// str1 and str2 are isomorphicbool areIsomorphic(char *str1, char *str2){ // If the length of the strings // are not equal if (strlen(str1) != strlen(str2)) { return false; } // Initialise two arrays int arr1[256] = { 0 }, arr2[256] = { 0 }; // Traversing both the strings for (int i = 0; i < strlen(str1); i++) { // If current characters don't map if (arr1[(int)str1[i]] != arr2[(int)str2[i]]) { return false; } // Increment the count of characters // at their respective ASCII indices arr1[(int)str1[i]]++; arr2[(int)str2[i]]++; } return true;} // Driver Codeint main(){ char s1[] = "aab", s2[] = "xxy"; if (areIsomorphic(s1, s2)) printf("Yes\n"); else printf("No\n"); return 0;}
Yes
Time Complexity: O(N) Auxiliary Space: O(256)
clintra
adnanirshad158
surindertarika1234
ASCII
C Programs
Hash
Mathematical
School Programming
Strings
Hash
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C Program to read contents of Whole File
Producer Consumer Problem in C
C program to find the length of a string
Exit codes in C/C++ with Examples
Difference between break and continue statement in C
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum
Hashing | Set 3 (Open Addressing)
|
[
{
"code": null,
"e": 24643,
"s": 24615,
"text": "\n04 Oct, 2021"
},
{
"code": null,
"e": 24760,
"s": 24643,
"text": "Given two strings str1 and str2, the task is to check if the two given strings are isomorphic to each other or not. "
},
{
"code": null,
"e": 24973,
"s": 24760,
"text": "Two strings are said to be isomorphic if there is a one to one mapping possible for every character of str1 to every character of str2 and all occurrences of every character in str1 map to same character in str2."
},
{
"code": null,
"e": 24983,
"s": 24973,
"text": "Examples:"
},
{
"code": null,
"e": 25202,
"s": 24983,
"text": "Input: str1 = “egg”, str2 = “add” Output: Yes Explanation: ‘e’ in str1 with ASCII value 101 is mapped to ‘a’ in str2 with ASCII value 97. ‘g’ in str1 with ASCII value 103 is mapped to ‘d’ in str2 with ASCII value 100. "
},
{
"code": null,
"e": 25250,
"s": 25202,
"text": "Input: str1 = “eggs”, str2 = “add” Output: No "
},
{
"code": null,
"e": 25328,
"s": 25250,
"text": "Hashing Approach: Refer to the previous post for the Hashmap based approach. "
},
{
"code": null,
"e": 25374,
"s": 25328,
"text": "Time Complexity: O(N) Auxiliary Space: O(256)"
},
{
"code": null,
"e": 25499,
"s": 25374,
"text": "ASCII-value based Approach: The idea is similar to that of the above approach. Follow the steps below to solve the problem: "
},
{
"code": null,
"e": 25753,
"s": 25499,
"text": "Initialize two arrays of size 256.Iterate through characters of the given strings and increment the index equal to the ASCII value of the character at ith position.If the are no conflicts in the mapping of the characters, print Yes. Otherwise, print No."
},
{
"code": null,
"e": 25788,
"s": 25753,
"text": "Initialize two arrays of size 256."
},
{
"code": null,
"e": 25919,
"s": 25788,
"text": "Iterate through characters of the given strings and increment the index equal to the ASCII value of the character at ith position."
},
{
"code": null,
"e": 26009,
"s": 25919,
"text": "If the are no conflicts in the mapping of the characters, print Yes. Otherwise, print No."
},
{
"code": null,
"e": 26061,
"s": 26009,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26063,
"s": 26061,
"text": "C"
},
{
"code": "// C Program to implement// the above approach #include <stdio.h>#include <string.h>#include <stdbool.h> // Function to check and return if strings// str1 and str2 are isomorphicbool areIsomorphic(char *str1, char *str2){ // If the length of the strings // are not equal if (strlen(str1) != strlen(str2)) { return false; } // Initialise two arrays int arr1[256] = { 0 }, arr2[256] = { 0 }; // Traversing both the strings for (int i = 0; i < strlen(str1); i++) { // If current characters don't map if (arr1[(int)str1[i]] != arr2[(int)str2[i]]) { return false; } // Increment the count of characters // at their respective ASCII indices arr1[(int)str1[i]]++; arr2[(int)str2[i]]++; } return true;} // Driver Codeint main(){ char s1[] = \"aab\", s2[] = \"xxy\"; if (areIsomorphic(s1, s2)) printf(\"Yes\\n\"); else printf(\"No\\n\"); return 0;}",
"e": 27029,
"s": 26063,
"text": null
},
{
"code": null,
"e": 27033,
"s": 27029,
"text": "Yes"
},
{
"code": null,
"e": 27081,
"s": 27035,
"text": "Time Complexity: O(N) Auxiliary Space: O(256)"
},
{
"code": null,
"e": 27089,
"s": 27081,
"text": "clintra"
},
{
"code": null,
"e": 27104,
"s": 27089,
"text": "adnanirshad158"
},
{
"code": null,
"e": 27123,
"s": 27104,
"text": "surindertarika1234"
},
{
"code": null,
"e": 27129,
"s": 27123,
"text": "ASCII"
},
{
"code": null,
"e": 27140,
"s": 27129,
"text": "C Programs"
},
{
"code": null,
"e": 27145,
"s": 27140,
"text": "Hash"
},
{
"code": null,
"e": 27158,
"s": 27145,
"text": "Mathematical"
},
{
"code": null,
"e": 27177,
"s": 27158,
"text": "School Programming"
},
{
"code": null,
"e": 27185,
"s": 27177,
"text": "Strings"
},
{
"code": null,
"e": 27190,
"s": 27185,
"text": "Hash"
},
{
"code": null,
"e": 27198,
"s": 27190,
"text": "Strings"
},
{
"code": null,
"e": 27211,
"s": 27198,
"text": "Mathematical"
},
{
"code": null,
"e": 27309,
"s": 27211,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27318,
"s": 27309,
"text": "Comments"
},
{
"code": null,
"e": 27331,
"s": 27318,
"text": "Old Comments"
},
{
"code": null,
"e": 27372,
"s": 27331,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 27403,
"s": 27372,
"text": "Producer Consumer Problem in C"
},
{
"code": null,
"e": 27444,
"s": 27403,
"text": "C program to find the length of a string"
},
{
"code": null,
"e": 27478,
"s": 27444,
"text": "Exit codes in C/C++ with Examples"
},
{
"code": null,
"e": 27531,
"s": 27478,
"text": "Difference between break and continue statement in C"
},
{
"code": null,
"e": 27616,
"s": 27531,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 27652,
"s": 27616,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 27683,
"s": 27652,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 27710,
"s": 27683,
"text": "Count pairs with given sum"
}
] |
Condition Coverage Testing
|
Condition coverage is also known as Predicate Coverage in which each one of the Boolean expression have been evaluated to both TRUE and FALSE.
if ((A || B) && C)
{
<< Few Statements >>
}
else
{
<< Few Statements >>
}
In order to ensure complete Condition coverage criteria for the above example, A, B and C should be evaluated at least once against "true" and "false".
So, in our example, the 3 following tests would be sufficient for 100% Condition coverage testing.
A = true | B = not eval | C = false
A = false | B = true | C = true
A = false | B = false | C = not eval
80 Lectures
7.5 hours
Arnab Chakraborty
10 Lectures
1 hours
Zach Miller
17 Lectures
1.5 hours
Zach Miller
60 Lectures
5 hours
John Shea
99 Lectures
10 hours
Daniel IT
62 Lectures
5 hours
GlobalETraining
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 5888,
"s": 5745,
"text": "Condition coverage is also known as Predicate Coverage in which each one of the Boolean expression have been evaluated to both TRUE and FALSE."
},
{
"code": null,
"e": 5967,
"s": 5888,
"text": "if ((A || B) && C)\n{\n << Few Statements >>\n}\nelse\n{\n << Few Statements >>\n}"
},
{
"code": null,
"e": 6119,
"s": 5967,
"text": "In order to ensure complete Condition coverage criteria for the above example, A, B and C should be evaluated at least once against \"true\" and \"false\"."
},
{
"code": null,
"e": 6332,
"s": 6119,
"text": "So, in our example, the 3 following tests would be sufficient for 100% Condition coverage testing.\nA = true | B = not eval | C = false\nA = false | B = true | C = true\nA = false | B = false | C = not eval\n"
},
{
"code": null,
"e": 6367,
"s": 6332,
"text": "\n 80 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 6386,
"s": 6367,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6419,
"s": 6386,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6432,
"s": 6419,
"text": " Zach Miller"
},
{
"code": null,
"e": 6467,
"s": 6432,
"text": "\n 17 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6480,
"s": 6467,
"text": " Zach Miller"
},
{
"code": null,
"e": 6513,
"s": 6480,
"text": "\n 60 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6524,
"s": 6513,
"text": " John Shea"
},
{
"code": null,
"e": 6558,
"s": 6524,
"text": "\n 99 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 6569,
"s": 6558,
"text": " Daniel IT"
},
{
"code": null,
"e": 6602,
"s": 6569,
"text": "\n 62 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6619,
"s": 6602,
"text": " GlobalETraining"
},
{
"code": null,
"e": 6626,
"s": 6619,
"text": " Print"
},
{
"code": null,
"e": 6637,
"s": 6626,
"text": " Add Notes"
}
] |
How to convert a JSON string to a bean using JSON-lib API in Java?
|
The JSON-lib
API is a java library to serialize and de-serialize java beans, maps, arrays, and collections in the JSON format. We need to convert a JSON string to a bean by converting a string to JSON object first then convert this to a java bean.
public static Object toBean(JSONObject jsonObject, Class beanClass)
In the below program, we can convert a JSON string to a bean.
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
public class ConvertJSONStringToBeanTest {
public static void main(String[] args) {
String jsonStr = "{\"firstName\": \"Adithya\", \"lastName\": \"Sai\", \"age\": 30, \"technology\": \"Java\"}";
JSONObject jsonObj = (JSONObject)JSONSerializer.toJSON(jsonStr); // convert String to JSON
System.out.println(jsonObj);
Student student = (Student)JSONObject.toBean(jsonObj, Student.class); // convert JSON to Bean
System.out.println(student.toString());
}
public static class Student {
private String firstName;
private String lastName;
private int age;
private String technology;
public Student() {
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getTechnology () {
return technology;
}
public void setTechnology(String technology) {
this.technology = technology;
}
public String toString() {
return "Student[ " +
"firstName = " + firstName +
", lastName = " + lastName +
", age = " + age +
", technology = " + technology +
" ]";
}
}
}
{"firstName":"Adithya","lastName":"Sai","age":30,"technology":"Java"}
Student[ firstName = Adithya, lastName = Sai, age = 30, technology = Java ]
|
[
{
"code": null,
"e": 1310,
"s": 1062,
"text": "The JSON-lib\nAPI is a java library to serialize and de-serialize java beans, maps, arrays, and collections in the JSON format. We need to convert a JSON string to a bean by converting a string to JSON object first then convert this to a java bean."
},
{
"code": null,
"e": 1378,
"s": 1310,
"text": "public static Object toBean(JSONObject jsonObject, Class beanClass)"
},
{
"code": null,
"e": 1440,
"s": 1378,
"text": "In the below program, we can convert a JSON string to a bean."
},
{
"code": null,
"e": 3053,
"s": 1440,
"text": "import net.sf.json.JSONObject;\nimport net.sf.json.JSONSerializer;\npublic class ConvertJSONStringToBeanTest {\n public static void main(String[] args) {\n String jsonStr = \"{\\\"firstName\\\": \\\"Adithya\\\", \\\"lastName\\\": \\\"Sai\\\", \\\"age\\\": 30, \\\"technology\\\": \\\"Java\\\"}\";\n JSONObject jsonObj = (JSONObject)JSONSerializer.toJSON(jsonStr); // convert String to JSON\n System.out.println(jsonObj);\n \n Student student = (Student)JSONObject.toBean(jsonObj, Student.class); // convert JSON to Bean\n System.out.println(student.toString());\n }\n public static class Student {\n private String firstName;\n private String lastName;\n private int age;\n private String technology;\n public Student() {\n }\n public String getFirstName() {\n return firstName;\n }\n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n public String getLastName() {\n return lastName;\n }\n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n public int getAge() {\n return age;\n }\n public void setAge(int age) {\n this.age = age;\n }\n public String getTechnology () {\n return technology;\n }\n public void setTechnology(String technology) {\n this.technology = technology;\n }\n public String toString() {\n return \"Student[ \" +\n \"firstName = \" + firstName +\n \", lastName = \" + lastName +\n \", age = \" + age +\n \", technology = \" + technology +\n \" ]\";\n }\n }\n}"
},
{
"code": null,
"e": 3199,
"s": 3053,
"text": "{\"firstName\":\"Adithya\",\"lastName\":\"Sai\",\"age\":30,\"technology\":\"Java\"}\nStudent[ firstName = Adithya, lastName = Sai, age = 30, technology = Java ]"
}
] |
jQuery submit() with Examples
|
The submit() method in jQuery is used to trigger the submit event. It occurs when a form is submitted.
The syntax is as follows −
$(selector).submit(func)
Above, the func parameter is the function to run when the submit event is triggered
Let us now see an example to implement the jQuery submit() method −
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("form").submit(function(){
alert("Form Submitted");
});
});
</script>
</head>
<body>
<h2>Login<h2>
<form action="">
Enter Username:
<input type="text"><br>
Enter Password:
<input type="password"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
This will produce the following output−
Click the “Submit” button −
|
[
{
"code": null,
"e": 1165,
"s": 1062,
"text": "The submit() method in jQuery is used to trigger the submit event. It occurs when a form is submitted."
},
{
"code": null,
"e": 1192,
"s": 1165,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 1217,
"s": 1192,
"text": "$(selector).submit(func)"
},
{
"code": null,
"e": 1301,
"s": 1217,
"text": "Above, the func parameter is the function to run when the submit event is triggered"
},
{
"code": null,
"e": 1369,
"s": 1301,
"text": "Let us now see an example to implement the jQuery submit() method −"
},
{
"code": null,
"e": 1380,
"s": 1369,
"text": " Live Demo"
},
{
"code": null,
"e": 1829,
"s": 1380,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"></script>\n<script>\n $(document).ready(function() {\n $(\"form\").submit(function(){\n alert(\"Form Submitted\");\n });\n });\n</script>\n</head>\n<body>\n<h2>Login<h2>\n<form action=\"\">\nEnter Username:\n<input type=\"text\"><br>\nEnter Password:\n<input type=\"password\"><br>\n<input type=\"submit\" value=\"Submit\">\n</form>\n</body>\n</html>"
},
{
"code": null,
"e": 1869,
"s": 1829,
"text": "This will produce the following output−"
},
{
"code": null,
"e": 1897,
"s": 1869,
"text": "Click the “Submit” button −"
}
] |
GATE | GATE-CS-2003 | Question 76 - GeeksforGeeks
|
20 Aug, 2021
Consider the following class definitions in a hypothetical Object Oriented language that supports inheritance and uses dynamic binding. The language should not be assumed to be either Java or C++, though the syntax is similar.
Class P
{
void f(int i)
{
print(i);
}
}
Class Q subclass of P
{
void f(int i)
{
print(2*i);
}
}
Now consider the following program fragment:
P x = new Q();
Q y = new Q();
P z = new Q();
x.f(1); ((P)y).f(1); z.f(1);
Here ((P)y) denotes a typecast of y to P. The output produced by executing the above program fragment will be(A) 1 2 1(B) 2 1 1(C) 2 1 2(D) 2 2 2Answer: (D)Explanation: Since the question itself tells us that the language uses dynamic binding therefore all the function calls should be considered only on the basic of type of object stored.Quiz of this Question
chaudharysatyam3976
satyam552000
GATE-CS-2003
GATE-GATE-CS-2003
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
|
[
{
"code": null,
"e": 25485,
"s": 25457,
"text": "\n20 Aug, 2021"
},
{
"code": null,
"e": 25712,
"s": 25485,
"text": "Consider the following class definitions in a hypothetical Object Oriented language that supports inheritance and uses dynamic binding. The language should not be assumed to be either Java or C++, though the syntax is similar."
},
{
"code": null,
"e": 25850,
"s": 25712,
"text": "Class P\n{\n void f(int i)\n {\n print(i);\n }\n}\n\nClass Q subclass of P\n{\n void f(int i)\n {\n print(2*i);\n }\n}\n"
},
{
"code": null,
"e": 25895,
"s": 25850,
"text": "Now consider the following program fragment:"
},
{
"code": null,
"e": 25970,
"s": 25895,
"text": "P x = new Q();\nQ y = new Q();\nP z = new Q();\nx.f(1); ((P)y).f(1); z.f(1); "
},
{
"code": null,
"e": 26332,
"s": 25970,
"text": "Here ((P)y) denotes a typecast of y to P. The output produced by executing the above program fragment will be(A) 1 2 1(B) 2 1 1(C) 2 1 2(D) 2 2 2Answer: (D)Explanation: Since the question itself tells us that the language uses dynamic binding therefore all the function calls should be considered only on the basic of type of object stored.Quiz of this Question"
},
{
"code": null,
"e": 26352,
"s": 26332,
"text": "chaudharysatyam3976"
},
{
"code": null,
"e": 26365,
"s": 26352,
"text": "satyam552000"
},
{
"code": null,
"e": 26378,
"s": 26365,
"text": "GATE-CS-2003"
},
{
"code": null,
"e": 26396,
"s": 26378,
"text": "GATE-GATE-CS-2003"
},
{
"code": null,
"e": 26401,
"s": 26396,
"text": "GATE"
},
{
"code": null,
"e": 26499,
"s": 26401,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26533,
"s": 26499,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 26567,
"s": 26533,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 26601,
"s": 26567,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 26634,
"s": 26601,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 26670,
"s": 26634,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 26704,
"s": 26670,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 26740,
"s": 26704,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 26774,
"s": 26740,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 26808,
"s": 26774,
"text": "GATE | GATE-CS-2009 | Question 38"
}
] |
Create transparent png image with Python - Pillow - GeeksforGeeks
|
24 Feb, 2021
To create a transparent png using Python3, the Pillow library is used. The Pillow library comes with python itself. If python is unable to find Pillow library then open the command prompt and run this command:-
pip install Pillow
Note: If you got any problem installing Pillow using pip, then install and setup pip first. For this check this article.
Approach:
1. import the Image module from the Pillow library
from PIL import Image
2. Open any image and get the RAGBAG values.
img = Image.open(‘image.png’)
rgba = img.convert(“RGBA”)
datas = rgba.getdata()
3. Change the color
Data will be an Imaging Core object containing thousands of tuples of RGBA values. To make transparent the background firstly we have to find the RGBA values of the background or any color we want to make transparent. Here in this image, the background color is black.
The RGB value of black is (0, 0, 0). Now we will loop through the data (RGBA values) and whenever we find a black pixel we will replace it with a transparent RGBA value which is ((255, 255, 255, 0), and the other colors will be unchanged. And we will store the values in a new list called newData.
newData = []
for item in datas:
if item[0] == 0 and item[1] == 0 and item[2] == 0:
newData.append((255, 255, 255, 0))
else:
newData.append(item)
4. Store the changed image
Store the newData into RGBA value and save the image as a png format(transparent image can’t be stored into jpg or jpeg format).
rgba.putdata(newData)
rgba.save(“transparent_image.png”, “PNG”)
Implementation:
Python3
from PIL import Image img = Image.open('image.png')rgba = img.convert("RGBA")datas = rgba.getdata() newData = []for item in datas: if item[0] == 0 and item[1] == 0 and item[2] == 0: # finding black colour by its RGB value # storing a transparent value when we find a black colour newData.append((255, 255, 255, 0)) else: newData.append(item) # other colours remain unchanged rgba.putdata(newData)rgba.save("transparent_image.png", "PNG")
Output:
Now taking the same image if we want to make the yellow color transparent we need to make the yellow pixels transparent. For this, we have to find the yellow color by its RBG values(255, 255, 0) and replace it with (255, 255, 255, 0).
The new code looks like this –
Python3
from PIL import Image img = Image.open('image.png')rgba = img.convert("RGBA")datas = rgba.getdata() newData = []for item in datas: if item[0] == 255 and item[1] == 255 and item[2] == 0: # finding yellow colour # replacing it with a transparent value newData.append((255, 255, 255, 0)) else: newData.append(item) rgba.putdata(newData)rgba.save("transparent_image.png", "PNG")
Output:
Here we make the yellow color transparent.
Picked
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
|
[
{
"code": null,
"e": 25791,
"s": 25763,
"text": "\n24 Feb, 2021"
},
{
"code": null,
"e": 26002,
"s": 25791,
"text": "To create a transparent png using Python3, the Pillow library is used. The Pillow library comes with python itself. If python is unable to find Pillow library then open the command prompt and run this command:-"
},
{
"code": null,
"e": 26021,
"s": 26002,
"text": "pip install Pillow"
},
{
"code": null,
"e": 26142,
"s": 26021,
"text": "Note: If you got any problem installing Pillow using pip, then install and setup pip first. For this check this article."
},
{
"code": null,
"e": 26152,
"s": 26142,
"text": "Approach:"
},
{
"code": null,
"e": 26203,
"s": 26152,
"text": "1. import the Image module from the Pillow library"
},
{
"code": null,
"e": 26225,
"s": 26203,
"text": "from PIL import Image"
},
{
"code": null,
"e": 26270,
"s": 26225,
"text": "2. Open any image and get the RAGBAG values."
},
{
"code": null,
"e": 26300,
"s": 26270,
"text": "img = Image.open(‘image.png’)"
},
{
"code": null,
"e": 26327,
"s": 26300,
"text": "rgba = img.convert(“RGBA”)"
},
{
"code": null,
"e": 26350,
"s": 26327,
"text": "datas = rgba.getdata()"
},
{
"code": null,
"e": 26371,
"s": 26350,
"text": "3. Change the color "
},
{
"code": null,
"e": 26641,
"s": 26371,
"text": "Data will be an Imaging Core object containing thousands of tuples of RGBA values. To make transparent the background firstly we have to find the RGBA values of the background or any color we want to make transparent. Here in this image, the background color is black. "
},
{
"code": null,
"e": 26940,
"s": 26641,
"text": "The RGB value of black is (0, 0, 0). Now we will loop through the data (RGBA values) and whenever we find a black pixel we will replace it with a transparent RGBA value which is ((255, 255, 255, 0), and the other colors will be unchanged. And we will store the values in a new list called newData."
},
{
"code": null,
"e": 26953,
"s": 26940,
"text": "newData = []"
},
{
"code": null,
"e": 26972,
"s": 26953,
"text": "for item in datas:"
},
{
"code": null,
"e": 27026,
"s": 26972,
"text": " if item[0] == 0 and item[1] == 0 and item[2] == 0:"
},
{
"code": null,
"e": 27068,
"s": 27026,
"text": " newData.append((255, 255, 255, 0))"
},
{
"code": null,
"e": 27077,
"s": 27068,
"text": " else:"
},
{
"code": null,
"e": 27104,
"s": 27077,
"text": " newData.append(item)"
},
{
"code": null,
"e": 27131,
"s": 27104,
"text": "4. Store the changed image"
},
{
"code": null,
"e": 27260,
"s": 27131,
"text": "Store the newData into RGBA value and save the image as a png format(transparent image can’t be stored into jpg or jpeg format)."
},
{
"code": null,
"e": 27282,
"s": 27260,
"text": "rgba.putdata(newData)"
},
{
"code": null,
"e": 27324,
"s": 27282,
"text": "rgba.save(“transparent_image.png”, “PNG”)"
},
{
"code": null,
"e": 27340,
"s": 27324,
"text": "Implementation:"
},
{
"code": null,
"e": 27348,
"s": 27340,
"text": "Python3"
},
{
"code": "from PIL import Image img = Image.open('image.png')rgba = img.convert(\"RGBA\")datas = rgba.getdata() newData = []for item in datas: if item[0] == 0 and item[1] == 0 and item[2] == 0: # finding black colour by its RGB value # storing a transparent value when we find a black colour newData.append((255, 255, 255, 0)) else: newData.append(item) # other colours remain unchanged rgba.putdata(newData)rgba.save(\"transparent_image.png\", \"PNG\")",
"e": 27818,
"s": 27348,
"text": null
},
{
"code": null,
"e": 27826,
"s": 27818,
"text": "Output:"
},
{
"code": null,
"e": 28061,
"s": 27826,
"text": "Now taking the same image if we want to make the yellow color transparent we need to make the yellow pixels transparent. For this, we have to find the yellow color by its RBG values(255, 255, 0) and replace it with (255, 255, 255, 0)."
},
{
"code": null,
"e": 28093,
"s": 28061,
"text": "The new code looks like this – "
},
{
"code": null,
"e": 28101,
"s": 28093,
"text": "Python3"
},
{
"code": "from PIL import Image img = Image.open('image.png')rgba = img.convert(\"RGBA\")datas = rgba.getdata() newData = []for item in datas: if item[0] == 255 and item[1] == 255 and item[2] == 0: # finding yellow colour # replacing it with a transparent value newData.append((255, 255, 255, 0)) else: newData.append(item) rgba.putdata(newData)rgba.save(\"transparent_image.png\", \"PNG\")",
"e": 28507,
"s": 28101,
"text": null
},
{
"code": null,
"e": 28515,
"s": 28507,
"text": "Output:"
},
{
"code": null,
"e": 28558,
"s": 28515,
"text": "Here we make the yellow color transparent."
},
{
"code": null,
"e": 28565,
"s": 28558,
"text": "Picked"
},
{
"code": null,
"e": 28576,
"s": 28565,
"text": "Python-pil"
},
{
"code": null,
"e": 28583,
"s": 28576,
"text": "Python"
},
{
"code": null,
"e": 28681,
"s": 28583,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28699,
"s": 28681,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28731,
"s": 28699,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28753,
"s": 28731,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28795,
"s": 28753,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28825,
"s": 28795,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28851,
"s": 28825,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28880,
"s": 28851,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28924,
"s": 28880,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 28961,
"s": 28924,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Basic Operators in Shell Scripting - GeeksforGeeks
|
06 Oct, 2021
There are 5 basic operators in bash/shell scripting:
Arithmetic Operators
Relational Operators
Boolean Operators
Bitwise Operators
File Test Operators
1. Arithmetic Operators: These operators are used to perform normal arithmetics/mathematical operations. There are 7 arithmetic operators:
Addition (+): Binary operation used to add two operands.
Subtraction (-): Binary operation used to subtract two operands.
Multiplication (*): Binary operation used to multiply two operands.
Division (/): Binary operation used to divide two operands.
Modulus (%): Binary operation used to find remainder of two operands.
Increment Operator (++): Unary operator used to increase the value of operand by one.
Decrement Operator (- -): Unary operator used to decrease the value of a operand by one
C
#!/bin/bash #reading data from the userread - p 'Enter a : ' a read - p 'Enter b : ' b add = $((a + b)) echo Addition of a and b are $add sub = $((a - b)) echo Subtraction of a and b are $sub mul = $((a * b)) echo Multiplication of a and b are $mul div = $((a / b)) echo division of a and b are $div mod = $((a % b)) echo Modulus of a and b are $mod ((++a)) echo Increment operator when applied on "a" results into a = $a ((--b)) echo Decrement operator when applied on "b" results into b = $b
Output:
2. Relational Operators: Relational operators are those operators which define the relation between two operands. They give either true or false depending upon the relation. They are of 6 types:
‘==’ Operator: Double equal to operator compares the two operands. Its returns true is they are equal otherwise returns false.
‘!=’ Operator: Not Equal to operator return true if the two operands are not equal otherwise it returns false.
‘<‘ Operator: Less than operator returns true if first operand is less than second operand otherwise returns false.
‘<=’ Operator: Less than or equal to operator returns true if first operand is less than or equal to second operand otherwise returns false
‘>’ Operator: Greater than operator return true if the first operand is greater than the second operand otherwise return false.
‘>=’ Operator: Greater than or equal to operator returns true if first operand is greater than or equal to second operand otherwise returns false
C
#!/bin/bash #reading data from the userread -p 'Enter a : ' aread -p 'Enter b : ' b if(( $a==$b ))then echo a is equal to b.else echo a is not equal to b.fi if(( $a!=$b ))then echo a is not equal to b.else echo a is equal to b.fi if(( $a<$b ))then echo a is less than b.else echo a is not less than b.fi if(( $a<=$b ))then echo a is less than or equal to b.else echo a is not less than or equal to b.fi if(( $a>$b ))then echo a is greater than b.else echo a is not greater than b.fi if(( $a>=$b ))then echo a is greater than or equal to b.else echo a is not greater than or equal to b.fi
Output:
3. Logical Operators : They are also known as boolean operators. These are used to perform logical operations. They are of 3 types:
Logical AND (&&): This is a binary operator, which returns true if both the operands are true otherwise returns false.
Logical OR (||): This is a binary operator, which returns true is either of the operand is true or both the operands are true and return false if none of then is false.
Not Equal to (!): This is a unary operator which returns true if the operand is false and returns false if the operand is true.
C
#!/bin/bash #reading data from the userread -p 'Enter a : ' aread -p 'Enter b : ' b if(($a == "true" & $b == "true" ))then echo Both are true.else echo Both are not true.fi if(($a == "true" || $b == "true" ))then echo Atleast one of them is true.else echo None of them is true.fi if(( ! $a == "true" ))then echo "a" was initially false.else echo "a" was initially true. fi
Output:
4. Bitwise Operators: A bitwise operator is an operator used to perform bitwise operations on bit patterns. They are of 6 types:
Bitwise And (&): Bitwise & operator performs binary AND operation bit by bit on the operands.
Bitwise OR (|): Bitwise | operator performs binary OR operation bit by bit on the operands.
Bitwise XOR (^): Bitwise ^ operator performs binary XOR operation bit by bit on the operands.
Bitwise complement (~): Bitwise ~ operator performs binary NOT operation bit by bit on the operand.
Left Shift (<<): This operator shifts the bits of the left operand to left by number of times specified by right operand.
Right Shift (>>): This operator shifts the bits of the left operand to right by number of times specified by right operand.
C
#!/bin/bash #reading data from the userread -p 'Enter a : ' aread -p 'Enter b : ' b bitwiseAND=$(( a&b ))echo Bitwise AND of a and b is $bitwiseAND bitwiseOR=$(( a|b ))echo Bitwise OR of a and b is $bitwiseOR bitwiseXOR=$(( a^b ))echo Bitwise XOR of a and b is $bitwiseXOR bitiwiseComplement=$(( ~a ))echo Bitwise Compliment of a is $bitiwiseComplement leftshift=$(( a<<1 ))echo Left Shift of a is $leftshift rightshift=$(( b>>1 ))echo Right Shift of b is $rightshift
Output:
5. File Test Operator: These operators are used to test a particular property of a file.
-b operator: This operator check whether a file is a block special file or not. It returns true if the file is a block special file otherwise false.
-c operator: This operator checks whether a file is a character special file or not. It returns true if it is a character special file otherwise false.
-d operator: This operator checks if the given directory exists or not. If it exists then operators returns true otherwise false.
-e operator: This operator checks whether the given file exists or not. If it exits this operator returns true otherwise false.
-r operator: This operator checks whether the given file has read access or not. If it has read access then it returns true otherwise false.
-w operator: This operator check whether the given file has write access or not. If it has write then it returns true otherwise false.
-x operator: This operator check whether the given file has execute access or not. If it has execute access then it returns true otherwise false.
-s operator: This operator checks the size of the given file. If the size of given file is greater than 0 then it returns true otherwise it is false.
C
#!/bin/bash #reading data from the userread -p 'Enter file name : ' FileName if [ -e $FileName ]then echo File Existelse echo File doesnot existfi if [ -s $FileName ]then echo The given file is not empty.else echo The given file is empty.fi if [ -r $FileName ]then echo The given file has read access.else echo The given file does not has read access.fi if [ -w $FileName ]then echo The given file has write access.else echo The given file does not has write access.fi if [ -x $FileName ]then echo The given file has execute access.else echo The given file does not has execute access.fi
Output:
ankitagarwal10
surinderdawra388
simmytarika5
gabaa406
surindertarika1234
Shell Script
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
'crontab' in Linux with Examples
Tail command in Linux with examples
UDP Server-Client implementation in C
Cat command in Linux with examples
touch command in Linux with Examples
scp command in Linux with Examples
echo command in Linux with Examples
ps command in Linux with Examples
Compiling with g++
|
[
{
"code": null,
"e": 25907,
"s": 25879,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 25960,
"s": 25907,
"text": "There are 5 basic operators in bash/shell scripting:"
},
{
"code": null,
"e": 25981,
"s": 25960,
"text": "Arithmetic Operators"
},
{
"code": null,
"e": 26002,
"s": 25981,
"text": "Relational Operators"
},
{
"code": null,
"e": 26020,
"s": 26002,
"text": "Boolean Operators"
},
{
"code": null,
"e": 26038,
"s": 26020,
"text": "Bitwise Operators"
},
{
"code": null,
"e": 26058,
"s": 26038,
"text": "File Test Operators"
},
{
"code": null,
"e": 26197,
"s": 26058,
"text": "1. Arithmetic Operators: These operators are used to perform normal arithmetics/mathematical operations. There are 7 arithmetic operators:"
},
{
"code": null,
"e": 26254,
"s": 26197,
"text": "Addition (+): Binary operation used to add two operands."
},
{
"code": null,
"e": 26319,
"s": 26254,
"text": "Subtraction (-): Binary operation used to subtract two operands."
},
{
"code": null,
"e": 26387,
"s": 26319,
"text": "Multiplication (*): Binary operation used to multiply two operands."
},
{
"code": null,
"e": 26447,
"s": 26387,
"text": "Division (/): Binary operation used to divide two operands."
},
{
"code": null,
"e": 26517,
"s": 26447,
"text": "Modulus (%): Binary operation used to find remainder of two operands."
},
{
"code": null,
"e": 26603,
"s": 26517,
"text": "Increment Operator (++): Unary operator used to increase the value of operand by one."
},
{
"code": null,
"e": 26691,
"s": 26603,
"text": "Decrement Operator (- -): Unary operator used to decrease the value of a operand by one"
},
{
"code": null,
"e": 26693,
"s": 26691,
"text": "C"
},
{
"code": "#!/bin/bash #reading data from the userread - p 'Enter a : ' a read - p 'Enter b : ' b add = $((a + b)) echo Addition of a and b are $add sub = $((a - b)) echo Subtraction of a and b are $sub mul = $((a * b)) echo Multiplication of a and b are $mul div = $((a / b)) echo division of a and b are $div mod = $((a % b)) echo Modulus of a and b are $mod ((++a)) echo Increment operator when applied on \"a\" results into a = $a ((--b)) echo Decrement operator when applied on \"b\" results into b = $b",
"e": 27371,
"s": 26693,
"text": null
},
{
"code": null,
"e": 27379,
"s": 27371,
"text": "Output:"
},
{
"code": null,
"e": 27574,
"s": 27379,
"text": "2. Relational Operators: Relational operators are those operators which define the relation between two operands. They give either true or false depending upon the relation. They are of 6 types:"
},
{
"code": null,
"e": 27701,
"s": 27574,
"text": "‘==’ Operator: Double equal to operator compares the two operands. Its returns true is they are equal otherwise returns false."
},
{
"code": null,
"e": 27812,
"s": 27701,
"text": "‘!=’ Operator: Not Equal to operator return true if the two operands are not equal otherwise it returns false."
},
{
"code": null,
"e": 27928,
"s": 27812,
"text": "‘<‘ Operator: Less than operator returns true if first operand is less than second operand otherwise returns false."
},
{
"code": null,
"e": 28068,
"s": 27928,
"text": "‘<=’ Operator: Less than or equal to operator returns true if first operand is less than or equal to second operand otherwise returns false"
},
{
"code": null,
"e": 28196,
"s": 28068,
"text": "‘>’ Operator: Greater than operator return true if the first operand is greater than the second operand otherwise return false."
},
{
"code": null,
"e": 28342,
"s": 28196,
"text": "‘>=’ Operator: Greater than or equal to operator returns true if first operand is greater than or equal to second operand otherwise returns false"
},
{
"code": null,
"e": 28344,
"s": 28342,
"text": "C"
},
{
"code": "#!/bin/bash #reading data from the userread -p 'Enter a : ' aread -p 'Enter b : ' b if(( $a==$b ))then echo a is equal to b.else echo a is not equal to b.fi if(( $a!=$b ))then echo a is not equal to b.else echo a is equal to b.fi if(( $a<$b ))then echo a is less than b.else echo a is not less than b.fi if(( $a<=$b ))then echo a is less than or equal to b.else echo a is not less than or equal to b.fi if(( $a>$b ))then echo a is greater than b.else echo a is not greater than b.fi if(( $a>=$b ))then echo a is greater than or equal to b.else echo a is not greater than or equal to b.fi",
"e": 28982,
"s": 28344,
"text": null
},
{
"code": null,
"e": 28990,
"s": 28982,
"text": "Output:"
},
{
"code": null,
"e": 29123,
"s": 28990,
"text": "3. Logical Operators : They are also known as boolean operators. These are used to perform logical operations. They are of 3 types: "
},
{
"code": null,
"e": 29242,
"s": 29123,
"text": "Logical AND (&&): This is a binary operator, which returns true if both the operands are true otherwise returns false."
},
{
"code": null,
"e": 29411,
"s": 29242,
"text": "Logical OR (||): This is a binary operator, which returns true is either of the operand is true or both the operands are true and return false if none of then is false."
},
{
"code": null,
"e": 29539,
"s": 29411,
"text": "Not Equal to (!): This is a unary operator which returns true if the operand is false and returns false if the operand is true."
},
{
"code": null,
"e": 29541,
"s": 29539,
"text": "C"
},
{
"code": "#!/bin/bash #reading data from the userread -p 'Enter a : ' aread -p 'Enter b : ' b if(($a == \"true\" & $b == \"true\" ))then echo Both are true.else echo Both are not true.fi if(($a == \"true\" || $b == \"true\" ))then echo Atleast one of them is true.else echo None of them is true.fi if(( ! $a == \"true\" ))then echo \"a\" was initially false.else echo \"a\" was initially true. fi",
"e": 29938,
"s": 29541,
"text": null
},
{
"code": null,
"e": 29946,
"s": 29938,
"text": "Output:"
},
{
"code": null,
"e": 30075,
"s": 29946,
"text": "4. Bitwise Operators: A bitwise operator is an operator used to perform bitwise operations on bit patterns. They are of 6 types:"
},
{
"code": null,
"e": 30169,
"s": 30075,
"text": "Bitwise And (&): Bitwise & operator performs binary AND operation bit by bit on the operands."
},
{
"code": null,
"e": 30261,
"s": 30169,
"text": "Bitwise OR (|): Bitwise | operator performs binary OR operation bit by bit on the operands."
},
{
"code": null,
"e": 30355,
"s": 30261,
"text": "Bitwise XOR (^): Bitwise ^ operator performs binary XOR operation bit by bit on the operands."
},
{
"code": null,
"e": 30455,
"s": 30355,
"text": "Bitwise complement (~): Bitwise ~ operator performs binary NOT operation bit by bit on the operand."
},
{
"code": null,
"e": 30577,
"s": 30455,
"text": "Left Shift (<<): This operator shifts the bits of the left operand to left by number of times specified by right operand."
},
{
"code": null,
"e": 30701,
"s": 30577,
"text": "Right Shift (>>): This operator shifts the bits of the left operand to right by number of times specified by right operand."
},
{
"code": null,
"e": 30703,
"s": 30701,
"text": "C"
},
{
"code": "#!/bin/bash #reading data from the userread -p 'Enter a : ' aread -p 'Enter b : ' b bitwiseAND=$(( a&b ))echo Bitwise AND of a and b is $bitwiseAND bitwiseOR=$(( a|b ))echo Bitwise OR of a and b is $bitwiseOR bitwiseXOR=$(( a^b ))echo Bitwise XOR of a and b is $bitwiseXOR bitiwiseComplement=$(( ~a ))echo Bitwise Compliment of a is $bitiwiseComplement leftshift=$(( a<<1 ))echo Left Shift of a is $leftshift rightshift=$(( b>>1 ))echo Right Shift of b is $rightshift",
"e": 31178,
"s": 30703,
"text": null
},
{
"code": null,
"e": 31186,
"s": 31178,
"text": "Output:"
},
{
"code": null,
"e": 31275,
"s": 31186,
"text": "5. File Test Operator: These operators are used to test a particular property of a file."
},
{
"code": null,
"e": 31424,
"s": 31275,
"text": "-b operator: This operator check whether a file is a block special file or not. It returns true if the file is a block special file otherwise false."
},
{
"code": null,
"e": 31576,
"s": 31424,
"text": "-c operator: This operator checks whether a file is a character special file or not. It returns true if it is a character special file otherwise false."
},
{
"code": null,
"e": 31706,
"s": 31576,
"text": "-d operator: This operator checks if the given directory exists or not. If it exists then operators returns true otherwise false."
},
{
"code": null,
"e": 31834,
"s": 31706,
"text": "-e operator: This operator checks whether the given file exists or not. If it exits this operator returns true otherwise false."
},
{
"code": null,
"e": 31975,
"s": 31834,
"text": "-r operator: This operator checks whether the given file has read access or not. If it has read access then it returns true otherwise false."
},
{
"code": null,
"e": 32110,
"s": 31975,
"text": "-w operator: This operator check whether the given file has write access or not. If it has write then it returns true otherwise false."
},
{
"code": null,
"e": 32256,
"s": 32110,
"text": "-x operator: This operator check whether the given file has execute access or not. If it has execute access then it returns true otherwise false."
},
{
"code": null,
"e": 32406,
"s": 32256,
"text": "-s operator: This operator checks the size of the given file. If the size of given file is greater than 0 then it returns true otherwise it is false."
},
{
"code": null,
"e": 32408,
"s": 32406,
"text": "C"
},
{
"code": "#!/bin/bash #reading data from the userread -p 'Enter file name : ' FileName if [ -e $FileName ]then echo File Existelse echo File doesnot existfi if [ -s $FileName ]then echo The given file is not empty.else echo The given file is empty.fi if [ -r $FileName ]then echo The given file has read access.else echo The given file does not has read access.fi if [ -w $FileName ]then echo The given file has write access.else echo The given file does not has write access.fi if [ -x $FileName ]then echo The given file has execute access.else echo The given file does not has execute access.fi",
"e": 33032,
"s": 32408,
"text": null
},
{
"code": null,
"e": 33040,
"s": 33032,
"text": "Output:"
},
{
"code": null,
"e": 33055,
"s": 33040,
"text": "ankitagarwal10"
},
{
"code": null,
"e": 33072,
"s": 33055,
"text": "surinderdawra388"
},
{
"code": null,
"e": 33085,
"s": 33072,
"text": "simmytarika5"
},
{
"code": null,
"e": 33094,
"s": 33085,
"text": "gabaa406"
},
{
"code": null,
"e": 33113,
"s": 33094,
"text": "surindertarika1234"
},
{
"code": null,
"e": 33126,
"s": 33113,
"text": "Shell Script"
},
{
"code": null,
"e": 33137,
"s": 33126,
"text": "Linux-Unix"
},
{
"code": null,
"e": 33156,
"s": 33137,
"text": "Technical Scripter"
},
{
"code": null,
"e": 33254,
"s": 33156,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33289,
"s": 33254,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 33322,
"s": 33289,
"text": "'crontab' in Linux with Examples"
},
{
"code": null,
"e": 33358,
"s": 33322,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 33396,
"s": 33358,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 33431,
"s": 33396,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 33468,
"s": 33431,
"text": "touch command in Linux with Examples"
},
{
"code": null,
"e": 33503,
"s": 33468,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 33539,
"s": 33503,
"text": "echo command in Linux with Examples"
},
{
"code": null,
"e": 33573,
"s": 33539,
"text": "ps command in Linux with Examples"
}
] |
Sum of Interval and Update with Number of Divisors - GeeksforGeeks
|
05 Apr, 2018
Given an array A of N integers. You have to answer two types of queries :1. Update [l, r] – for every i in range from l to r update Ai with D(Ai), where D(Ai) represents the number of divisors of Ai2. Query [l, r] – calculate the sum of all numbers ranging between l and r in array A.Input is given as two integers N and Q, representing number of integers in array and number of queries respectively. Next line contains an array of n integers followed by Q queries where ith query is represented as typei, li, ri.
Prerequisite : Binary Indexed Trees | Segment Trees
Examples :
Input : 7 4
6 4 1 10 3 2 4
2 1 7
2 4 5
1 3 5
2 4 4
Output : 30
13
4
Explanation : First query is to calculate the sum of numbers from A1 to A7 which is 6 + 4+ 1 + 10 + 3 + 2 + 4 = 30. Similarly, second query results into 13. For third query,which is update operation, hence A3 will remain 1, A4 will become 4 and A5 will become 2.Fourth query will result into A4 = 4.
Naive Approach :A simple solution is to run a loop from l to r and calculate sum of elements in given range. To update a value, precompute the values of number of divisors of every number and simply do arr[i] = divisors[arr[i]].
Efficient Approach :The idea is to reduce the time complexity for each query and update operation to O(logN). Use Binary Indexed Trees (BIT) or Segment Trees. Construct a BIT[] array and have two functions for query and update operation and precompute the number of divisors for each number. Now, for each update operation the key observation is that the numbers ‘1’ and ‘2’ will have ‘1’ and ‘2’ as their number of divisors respectively, so if it exists in the range of update query, they don’t need to be updated. We will use a set to store the index of only those numbers which are greater than 2 and use binary search to find the l index of the update query and increment the l index until every element is updated in range of that update query. If the arr[i] has only 2 divisors then after updating it, remove it from the set as it will always be 2 even after any next update query. For sum query operation, simply do query(r) – query(l – 1).
// CPP program to calculate sum // in an interval and update with// number of divisors#include <bits/stdc++.h>using namespace std; int divisors[100], BIT[100]; // structure for queries with members type, // leftIndex, rightIndex of the querystruct queries{ int type, l, r;}; // function to calculate the number // of divisors of each numbervoid calcDivisors(){ for (int i = 1; i < 100; i++) { for (int j = i; j < 100; j += i) { divisors[j]++; } }} // function for updating the valuevoid update(int x, int val, int n){ for (x; x <= n; x += x&-x) { BIT[x] += val; }} // function for calculating the required // sum between two indexesint sum(int x){ int s = 0; for (x; x > 0; x -= x&-x) { s += BIT[x]; } return s;} // function to return answer to queriesvoid answerQueries(int arr[], queries que[], int n, int q){ // Declaring a Set set<int> s; for (int i = 1; i < n; i++) { // inserting indexes of those numbers // which are greater than 2 if(arr[i] > 2) s.insert(i); update(i, arr[i], n); } for (int i = 0; i < q; i++) { // update query if (que[i].type == 1) { while (true) { // find the left index of query in // the set using binary search auto it = s.lower_bound(que[i].l); // if it crosses the right index of // query or end of set, then break if(it == s.end() || *it > que[i].r) break; que[i].l = *it; // update the value of arr[i] to // its number of divisors update(*it, divisors[arr[*it]] - arr[*it], n); arr[*it] = divisors[arr[*it]]; // if updated value becomes less than or // equal to 2 remove it from the set if(arr[*it] <= 2) s.erase(*it); // increment the index que[i].l++; } } // sum query else { cout << (sum(que[i].r) - sum(que[i].l - 1)) << endl; } }} // Driver Codeint main() { // precompute the number of divisors for each number calcDivisors(); int q = 4; // input array int arr[] = {0, 6, 4, 1, 10, 3, 2, 4}; int n = sizeof(arr) / sizeof(arr[0]); // declaring array of structure of type queries queries que[q + 1]; que[0].type = 2, que[0].l = 1, que[0].r = 7; que[1].type = 2, que[1].l = 4, que[1].r = 5; que[2].type = 1, que[2].l = 3, que[2].r = 5; que[3].type = 2, que[3].l = 4, que[3].r = 4; // answer the Queries answerQueries(arr, que, n, q); return 0;}
30
13
4
Time Complexity for answering Q queries will be O(Q * log(N)).
array-range-queries
Binary Indexed Tree
Segment-Tree
Technical Scripter
Tree
Tree
Binary Indexed Tree
Segment-Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tree Traversals (Inorder, Preorder and Postorder)
AVL Tree | Set 1 (Insertion)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
Binary Tree | Set 3 (Types of Binary Tree)
Inorder Tree Traversal without Recursion
Binary Tree | Set 2 (Properties)
Write a Program to Find the Maximum Depth or Height of a Tree
Decision Tree
A program to check if a binary tree is BST or not
|
[
{
"code": null,
"e": 25957,
"s": 25929,
"text": "\n05 Apr, 2018"
},
{
"code": null,
"e": 26471,
"s": 25957,
"text": "Given an array A of N integers. You have to answer two types of queries :1. Update [l, r] – for every i in range from l to r update Ai with D(Ai), where D(Ai) represents the number of divisors of Ai2. Query [l, r] – calculate the sum of all numbers ranging between l and r in array A.Input is given as two integers N and Q, representing number of integers in array and number of queries respectively. Next line contains an array of n integers followed by Q queries where ith query is represented as typei, li, ri."
},
{
"code": null,
"e": 26523,
"s": 26471,
"text": "Prerequisite : Binary Indexed Trees | Segment Trees"
},
{
"code": null,
"e": 26534,
"s": 26523,
"text": "Examples :"
},
{
"code": null,
"e": 26661,
"s": 26534,
"text": "Input : 7 4\n 6 4 1 10 3 2 4\n 2 1 7\n 2 4 5\n 1 3 5\n 2 4 4\nOutput : 30\n 13\n 4\n"
},
{
"code": null,
"e": 26961,
"s": 26661,
"text": "Explanation : First query is to calculate the sum of numbers from A1 to A7 which is 6 + 4+ 1 + 10 + 3 + 2 + 4 = 30. Similarly, second query results into 13. For third query,which is update operation, hence A3 will remain 1, A4 will become 4 and A5 will become 2.Fourth query will result into A4 = 4."
},
{
"code": null,
"e": 27190,
"s": 26961,
"text": "Naive Approach :A simple solution is to run a loop from l to r and calculate sum of elements in given range. To update a value, precompute the values of number of divisors of every number and simply do arr[i] = divisors[arr[i]]."
},
{
"code": null,
"e": 28138,
"s": 27190,
"text": "Efficient Approach :The idea is to reduce the time complexity for each query and update operation to O(logN). Use Binary Indexed Trees (BIT) or Segment Trees. Construct a BIT[] array and have two functions for query and update operation and precompute the number of divisors for each number. Now, for each update operation the key observation is that the numbers ‘1’ and ‘2’ will have ‘1’ and ‘2’ as their number of divisors respectively, so if it exists in the range of update query, they don’t need to be updated. We will use a set to store the index of only those numbers which are greater than 2 and use binary search to find the l index of the update query and increment the l index until every element is updated in range of that update query. If the arr[i] has only 2 divisors then after updating it, remove it from the set as it will always be 2 even after any next update query. For sum query operation, simply do query(r) – query(l – 1)."
},
{
"code": "// CPP program to calculate sum // in an interval and update with// number of divisors#include <bits/stdc++.h>using namespace std; int divisors[100], BIT[100]; // structure for queries with members type, // leftIndex, rightIndex of the querystruct queries{ int type, l, r;}; // function to calculate the number // of divisors of each numbervoid calcDivisors(){ for (int i = 1; i < 100; i++) { for (int j = i; j < 100; j += i) { divisors[j]++; } }} // function for updating the valuevoid update(int x, int val, int n){ for (x; x <= n; x += x&-x) { BIT[x] += val; }} // function for calculating the required // sum between two indexesint sum(int x){ int s = 0; for (x; x > 0; x -= x&-x) { s += BIT[x]; } return s;} // function to return answer to queriesvoid answerQueries(int arr[], queries que[], int n, int q){ // Declaring a Set set<int> s; for (int i = 1; i < n; i++) { // inserting indexes of those numbers // which are greater than 2 if(arr[i] > 2) s.insert(i); update(i, arr[i], n); } for (int i = 0; i < q; i++) { // update query if (que[i].type == 1) { while (true) { // find the left index of query in // the set using binary search auto it = s.lower_bound(que[i].l); // if it crosses the right index of // query or end of set, then break if(it == s.end() || *it > que[i].r) break; que[i].l = *it; // update the value of arr[i] to // its number of divisors update(*it, divisors[arr[*it]] - arr[*it], n); arr[*it] = divisors[arr[*it]]; // if updated value becomes less than or // equal to 2 remove it from the set if(arr[*it] <= 2) s.erase(*it); // increment the index que[i].l++; } } // sum query else { cout << (sum(que[i].r) - sum(que[i].l - 1)) << endl; } }} // Driver Codeint main() { // precompute the number of divisors for each number calcDivisors(); int q = 4; // input array int arr[] = {0, 6, 4, 1, 10, 3, 2, 4}; int n = sizeof(arr) / sizeof(arr[0]); // declaring array of structure of type queries queries que[q + 1]; que[0].type = 2, que[0].l = 1, que[0].r = 7; que[1].type = 2, que[1].l = 4, que[1].r = 5; que[2].type = 1, que[2].l = 3, que[2].r = 5; que[3].type = 2, que[3].l = 4, que[3].r = 4; // answer the Queries answerQueries(arr, que, n, q); return 0;}",
"e": 31007,
"s": 28138,
"text": null
},
{
"code": null,
"e": 31016,
"s": 31007,
"text": "30\n13\n4\n"
},
{
"code": null,
"e": 31079,
"s": 31016,
"text": "Time Complexity for answering Q queries will be O(Q * log(N))."
},
{
"code": null,
"e": 31099,
"s": 31079,
"text": "array-range-queries"
},
{
"code": null,
"e": 31119,
"s": 31099,
"text": "Binary Indexed Tree"
},
{
"code": null,
"e": 31132,
"s": 31119,
"text": "Segment-Tree"
},
{
"code": null,
"e": 31151,
"s": 31132,
"text": "Technical Scripter"
},
{
"code": null,
"e": 31156,
"s": 31151,
"text": "Tree"
},
{
"code": null,
"e": 31161,
"s": 31156,
"text": "Tree"
},
{
"code": null,
"e": 31181,
"s": 31161,
"text": "Binary Indexed Tree"
},
{
"code": null,
"e": 31194,
"s": 31181,
"text": "Segment-Tree"
},
{
"code": null,
"e": 31292,
"s": 31194,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31342,
"s": 31292,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 31371,
"s": 31342,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 31406,
"s": 31371,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 31440,
"s": 31406,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 31483,
"s": 31440,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
},
{
"code": null,
"e": 31524,
"s": 31483,
"text": "Inorder Tree Traversal without Recursion"
},
{
"code": null,
"e": 31557,
"s": 31524,
"text": "Binary Tree | Set 2 (Properties)"
},
{
"code": null,
"e": 31619,
"s": 31557,
"text": "Write a Program to Find the Maximum Depth or Height of a Tree"
},
{
"code": null,
"e": 31633,
"s": 31619,
"text": "Decision Tree"
}
] |
Calculate number of nodes between two vertices in an acyclic Graph by DFS method - GeeksforGeeks
|
22 Jun, 2021
Given a connected acyclic graph consisting of V vertices and E edges, a source vertex src, and a destination vertex dest, the task is to count the number of vertices between the given source and destination vertex in the graph.
Examples:
Input: V = 8, E = 7, src = 7, dest = 8, edges[][] ={{1 4}, {4, 5}, {4, 2}, {2, 6}, {6, 3}, {2, 7}, {3, 8}}Output: 3Explanation:The path between 7 and 8 is 7 -> 2 -> 6 -> 3 -> 8.So, the number of nodes between 7 and 8 is 3.
Input: V = 8, E = 7, src = 5, dest = 2, edges[][] ={{1 4}, {4, 5}, {4, 2}, {2, 6}, {6, 3}, {2, 7}, {3, 8}}Output: 1Explanation:The path between 5 and 2 is 5 -> 4 -> 2.So, the number of nodes between 5 and 2 is 1.
Approach: The problem can also be solved using the Disjoint Union method as stated in this article. Another approach to this problem is to solve using the Depth First Search method. Follow the steps below to solve this problem:
Initialize a visited array vis[] to mark which nodes are already visited. Mark all the nodes as 0, i.e., not visited.
Perform a DFS to find the number of nodes present in the path between src and dest.
The number of nodes between src and dest is equal to the difference between the length of the path between them and 2, i.e., (pathSrcToDest – 2).
Since the graph is acyclic and connected, there will always be a single path between src and dest.
Below is the implementation of the above algorithm.
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to return the count of nodes// in the path from source to destinationint dfs(int src, int dest, int* vis, vector<int>* adj){ // Mark the node visited vis[src] = 1; // If dest is reached if (src == dest) { return 1; } // Traverse all adjacent nodes for (int u : adj[src]) { // If not already visited if (!vis[u]) { int temp = dfs(u, dest, vis, adj); // If there is path, then // include the current node if (temp != 0) { return temp + 1; } } } // Return 0 if there is no path // between src and dest through // the current node return 0;} // Function to return the// count of nodes between two// given vertices of the acyclic Graphint countNodes(int V, int E, int src, int dest, int edges[][2]){ // Initialize an adjacency list vector<int> adj[V + 1]; // Populate the edges in the list for (int i = 0; i < E; i++) { adj[edges[i][0]].push_back(edges[i][1]); adj[edges[i][1]].push_back(edges[i][0]); } // Mark all the nodes as not visited int vis[V + 1] = { 0 }; // Count nodes in the path from src to dest int count = dfs(src, dest, vis, adj); // Return the nodes between src and dest return count - 2;} // Driver Codeint main(){ // Given number of vertices and edges int V = 8, E = 7; // Given source and destination vertices int src = 5, dest = 2; // Given edges int edges[][2] = { { 1, 4 }, { 4, 5 }, { 4, 2 }, { 2, 6 }, { 6, 3 }, { 2, 7 }, { 3, 8 } }; cout << countNodes(V, E, src, dest, edges); return 0;}
// Java program for the above approachimport java.util.Vector;class GFG{ // Function to return the count of nodes// in the path from source to destinationstatic int dfs(int src, int dest, int []vis, Vector<Integer> []adj){ // Mark the node visited vis[src] = 1; // If dest is reached if (src == dest) { return 1; } // Traverse all adjacent nodes for (int u : adj[src]) { // If not already visited if (vis[u] == 0) { int temp = dfs(u, dest, vis, adj); // If there is path, then // include the current node if (temp != 0) { return temp + 1; } } } // Return 0 if there is no path // between src and dest through // the current node return 0;} // Function to return the// count of nodes between two// given vertices of the acyclic Graphstatic int countNodes(int V, int E, int src, int dest, int edges[][]){ // Initialize an adjacency list Vector<Integer> []adj = new Vector[V + 1]; for (int i = 0; i < adj.length; i++) adj[i] = new Vector<Integer>(); // Populate the edges in the list for (int i = 0; i < E; i++) { adj[edges[i][0]].add(edges[i][1]); adj[edges[i][1]].add(edges[i][0]); } // Mark all the nodes as // not visited int vis[] = new int[V + 1]; // Count nodes in the path // from src to dest int count = dfs(src, dest, vis, adj); // Return the nodes // between src and dest return count - 2;} // Driver Codepublic static void main(String[] args){ // Given number of vertices and edges int V = 8, E = 7; // Given source and destination vertices int src = 5, dest = 2; // Given edges int edges[][] = {{1, 4}, {4, 5}, {4, 2}, {2, 6}, {6, 3}, {2, 7}, {3, 8}}; System.out.print(countNodes(V, E, src, dest, edges));}} // This code is contributed by shikhasingrajput
# Python3 program for the above approach # Function to return the count of nodes# in the path from source to destinationdef dfs(src, dest, vis, adj): # Mark the node visited vis[src] = 1 # If dest is reached if (src == dest): return 1 # Traverse all adjacent nodes for u in adj[src]: # If not already visited if not vis[u]: temp = dfs(u, dest, vis, adj) # If there is path, then # include the current node if (temp != 0): return temp + 1 # Return 0 if there is no path # between src and dest through # the current node return 0 # Function to return the# count of nodes between two# given vertices of the acyclic Graphdef countNodes(V, E, src, dest, edges): # Initialize an adjacency list adj = [[] for i in range(V + 1)] # Populate the edges in the list for i in range(E): adj[edges[i][0]].append(edges[i][1]) adj[edges[i][1]].append(edges[i][0]) # Mark all the nodes as not visited vis = [0] * (V + 1) # Count nodes in the path from src to dest count = dfs(src, dest, vis, adj) # Return the nodes between src and dest return count - 2 # Driver Codeif __name__ == '__main__': # Given number of vertices and edges V = 8 E = 7 # Given source and destination vertices src = 5 dest = 2 # Given edges edges = [ [ 1, 4 ], [ 4, 5 ], [ 4, 2 ], [ 2, 6 ], [ 6, 3 ], [ 2, 7 ], [ 3, 8 ] ] print(countNodes(V, E, src, dest, edges)) # This code is contributed by mohit kumar 29
// C# program for// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to return the count of nodes// in the path from source to destinationstatic int dfs(int src, int dest, int []vis, List<int> []adj){ // Mark the node visited vis[src] = 1; // If dest is reached if (src == dest) { return 1; } // Traverse all adjacent nodes foreach (int u in adj[src]) { // If not already visited if (vis[u] == 0) { int temp = dfs(u, dest, vis, adj); // If there is path, then // include the current node if (temp != 0) { return temp + 1; } } } // Return 0 if there is no path // between src and dest through // the current node return 0;} // Function to return the// count of nodes between two// given vertices of the acyclic Graphstatic int countNodes(int V, int E, int src, int dest, int [,]edges){ // Initialize an adjacency list List<int> []adj = new List<int>[V + 1]; for (int i = 0; i < adj.Length; i++) adj[i] = new List<int>(); // Populate the edges in the list for (int i = 0; i < E; i++) { adj[edges[i, 0]].Add(edges[i, 1]); adj[edges[i, 1]].Add(edges[i, 0]); } // Mark all the nodes as // not visited int []vis = new int[V + 1]; // Count nodes in the path // from src to dest int count = dfs(src, dest, vis, adj); // Return the nodes // between src and dest return count - 2;} // Driver Codepublic static void Main(String[] args){ // Given number of vertices and edges int V = 8, E = 7; // Given source and destination vertices int src = 5, dest = 2; // Given edges int [,]edges = {{1, 4}, {4, 5}, {4, 2}, {2, 6}, {6, 3}, {2, 7}, {3, 8}}; Console.Write(countNodes(V, E, src, dest, edges));}} // This code is contributed by 29AjayKumar
<script>// Javascript program for the above approach // Function to return the count of nodes// in the path from source to destinationfunction dfs(src,dest,vis,adj){ // Mark the node visited vis[src] = 1; // If dest is reached if (src == dest) { return 1; } // Traverse all adjacent nodes for (let u=0;u< adj[src].length;u++) { // If not already visited if (vis[adj[src][u]] == 0) { let temp = dfs(adj[src][u], dest, vis, adj); // If there is path, then // include the current node if (temp != 0) { return temp + 1; } } } // Return 0 if there is no path // between src and dest through // the current node return 0;} // Function to return the// count of nodes between two// given vertices of the acyclic Graphfunction countNodes(V,E,src,dest,edges){ // Initialize an adjacency list let adj = new Array(V + 1); for (let i = 0; i < adj.length; i++) adj[i] = []; // Populate the edges in the list for (let i = 0; i < E; i++) { adj[edges[i][0]].push(edges[i][1]); adj[edges[i][1]].push(edges[i][0]); } // Mark all the nodes as // not visited let vis = new Array(V + 1); for(let i=0;i<vis.length;i++) { vis[i]=0; } // Count nodes in the path // from src to dest let count = dfs(src, dest, vis, adj); // Return the nodes // between src and dest return count - 2;} // Driver Code// Given number of vertices and edgeslet V = 8, E = 7; // Given source and destination verticeslet src = 5, dest = 2; // Given edgeslet edges = [[1, 4], [4, 5],[4, 2], [2, 6],[6, 3], [2, 7],[3, 8]]; document.write(countNodes(V, E, src, dest, edges)); // This code is contributed by unknown2108</script>
1
Time Complexity: O(V+E)Auxiliary Space: O(V)
mohit kumar 29
shikhasingrajput
29AjayKumar
unknown2108
DFS
Graph Traversals
Graph
Recursion
Searching
Searching
Recursion
DFS
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Graph Coloring | Set 2 (Greedy Algorithm)
Best First Search (Informed Search)
Maximum Bipartite Matching
Graph Coloring | Set 1 (Introduction and Applications)
Longest Path in a Directed Acyclic Graph
Write a program to print all permutations of a given string
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Recursion
Program for Tower of Hanoi
Backtracking | Introduction
|
[
{
"code": null,
"e": 25164,
"s": 25136,
"text": "\n22 Jun, 2021"
},
{
"code": null,
"e": 25392,
"s": 25164,
"text": "Given a connected acyclic graph consisting of V vertices and E edges, a source vertex src, and a destination vertex dest, the task is to count the number of vertices between the given source and destination vertex in the graph."
},
{
"code": null,
"e": 25402,
"s": 25392,
"text": "Examples:"
},
{
"code": null,
"e": 25625,
"s": 25402,
"text": "Input: V = 8, E = 7, src = 7, dest = 8, edges[][] ={{1 4}, {4, 5}, {4, 2}, {2, 6}, {6, 3}, {2, 7}, {3, 8}}Output: 3Explanation:The path between 7 and 8 is 7 -> 2 -> 6 -> 3 -> 8.So, the number of nodes between 7 and 8 is 3."
},
{
"code": null,
"e": 25838,
"s": 25625,
"text": "Input: V = 8, E = 7, src = 5, dest = 2, edges[][] ={{1 4}, {4, 5}, {4, 2}, {2, 6}, {6, 3}, {2, 7}, {3, 8}}Output: 1Explanation:The path between 5 and 2 is 5 -> 4 -> 2.So, the number of nodes between 5 and 2 is 1."
},
{
"code": null,
"e": 26066,
"s": 25838,
"text": "Approach: The problem can also be solved using the Disjoint Union method as stated in this article. Another approach to this problem is to solve using the Depth First Search method. Follow the steps below to solve this problem:"
},
{
"code": null,
"e": 26184,
"s": 26066,
"text": "Initialize a visited array vis[] to mark which nodes are already visited. Mark all the nodes as 0, i.e., not visited."
},
{
"code": null,
"e": 26268,
"s": 26184,
"text": "Perform a DFS to find the number of nodes present in the path between src and dest."
},
{
"code": null,
"e": 26414,
"s": 26268,
"text": "The number of nodes between src and dest is equal to the difference between the length of the path between them and 2, i.e., (pathSrcToDest – 2)."
},
{
"code": null,
"e": 26514,
"s": 26414,
"text": "Since the graph is acyclic and connected, there will always be a single path between src and dest. "
},
{
"code": null,
"e": 26566,
"s": 26514,
"text": "Below is the implementation of the above algorithm."
},
{
"code": null,
"e": 26570,
"s": 26566,
"text": "C++"
},
{
"code": null,
"e": 26575,
"s": 26570,
"text": "Java"
},
{
"code": null,
"e": 26583,
"s": 26575,
"text": "Python3"
},
{
"code": null,
"e": 26586,
"s": 26583,
"text": "C#"
},
{
"code": null,
"e": 26597,
"s": 26586,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to return the count of nodes// in the path from source to destinationint dfs(int src, int dest, int* vis, vector<int>* adj){ // Mark the node visited vis[src] = 1; // If dest is reached if (src == dest) { return 1; } // Traverse all adjacent nodes for (int u : adj[src]) { // If not already visited if (!vis[u]) { int temp = dfs(u, dest, vis, adj); // If there is path, then // include the current node if (temp != 0) { return temp + 1; } } } // Return 0 if there is no path // between src and dest through // the current node return 0;} // Function to return the// count of nodes between two// given vertices of the acyclic Graphint countNodes(int V, int E, int src, int dest, int edges[][2]){ // Initialize an adjacency list vector<int> adj[V + 1]; // Populate the edges in the list for (int i = 0; i < E; i++) { adj[edges[i][0]].push_back(edges[i][1]); adj[edges[i][1]].push_back(edges[i][0]); } // Mark all the nodes as not visited int vis[V + 1] = { 0 }; // Count nodes in the path from src to dest int count = dfs(src, dest, vis, adj); // Return the nodes between src and dest return count - 2;} // Driver Codeint main(){ // Given number of vertices and edges int V = 8, E = 7; // Given source and destination vertices int src = 5, dest = 2; // Given edges int edges[][2] = { { 1, 4 }, { 4, 5 }, { 4, 2 }, { 2, 6 }, { 6, 3 }, { 2, 7 }, { 3, 8 } }; cout << countNodes(V, E, src, dest, edges); return 0;}",
"e": 28383,
"s": 26597,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.Vector;class GFG{ // Function to return the count of nodes// in the path from source to destinationstatic int dfs(int src, int dest, int []vis, Vector<Integer> []adj){ // Mark the node visited vis[src] = 1; // If dest is reached if (src == dest) { return 1; } // Traverse all adjacent nodes for (int u : adj[src]) { // If not already visited if (vis[u] == 0) { int temp = dfs(u, dest, vis, adj); // If there is path, then // include the current node if (temp != 0) { return temp + 1; } } } // Return 0 if there is no path // between src and dest through // the current node return 0;} // Function to return the// count of nodes between two// given vertices of the acyclic Graphstatic int countNodes(int V, int E, int src, int dest, int edges[][]){ // Initialize an adjacency list Vector<Integer> []adj = new Vector[V + 1]; for (int i = 0; i < adj.length; i++) adj[i] = new Vector<Integer>(); // Populate the edges in the list for (int i = 0; i < E; i++) { adj[edges[i][0]].add(edges[i][1]); adj[edges[i][1]].add(edges[i][0]); } // Mark all the nodes as // not visited int vis[] = new int[V + 1]; // Count nodes in the path // from src to dest int count = dfs(src, dest, vis, adj); // Return the nodes // between src and dest return count - 2;} // Driver Codepublic static void main(String[] args){ // Given number of vertices and edges int V = 8, E = 7; // Given source and destination vertices int src = 5, dest = 2; // Given edges int edges[][] = {{1, 4}, {4, 5}, {4, 2}, {2, 6}, {6, 3}, {2, 7}, {3, 8}}; System.out.print(countNodes(V, E, src, dest, edges));}} // This code is contributed by shikhasingrajput",
"e": 30365,
"s": 28383,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to return the count of nodes# in the path from source to destinationdef dfs(src, dest, vis, adj): # Mark the node visited vis[src] = 1 # If dest is reached if (src == dest): return 1 # Traverse all adjacent nodes for u in adj[src]: # If not already visited if not vis[u]: temp = dfs(u, dest, vis, adj) # If there is path, then # include the current node if (temp != 0): return temp + 1 # Return 0 if there is no path # between src and dest through # the current node return 0 # Function to return the# count of nodes between two# given vertices of the acyclic Graphdef countNodes(V, E, src, dest, edges): # Initialize an adjacency list adj = [[] for i in range(V + 1)] # Populate the edges in the list for i in range(E): adj[edges[i][0]].append(edges[i][1]) adj[edges[i][1]].append(edges[i][0]) # Mark all the nodes as not visited vis = [0] * (V + 1) # Count nodes in the path from src to dest count = dfs(src, dest, vis, adj) # Return the nodes between src and dest return count - 2 # Driver Codeif __name__ == '__main__': # Given number of vertices and edges V = 8 E = 7 # Given source and destination vertices src = 5 dest = 2 # Given edges edges = [ [ 1, 4 ], [ 4, 5 ], [ 4, 2 ], [ 2, 6 ], [ 6, 3 ], [ 2, 7 ], [ 3, 8 ] ] print(countNodes(V, E, src, dest, edges)) # This code is contributed by mohit kumar 29 ",
"e": 31975,
"s": 30365,
"text": null
},
{
"code": "// C# program for// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to return the count of nodes// in the path from source to destinationstatic int dfs(int src, int dest, int []vis, List<int> []adj){ // Mark the node visited vis[src] = 1; // If dest is reached if (src == dest) { return 1; } // Traverse all adjacent nodes foreach (int u in adj[src]) { // If not already visited if (vis[u] == 0) { int temp = dfs(u, dest, vis, adj); // If there is path, then // include the current node if (temp != 0) { return temp + 1; } } } // Return 0 if there is no path // between src and dest through // the current node return 0;} // Function to return the// count of nodes between two// given vertices of the acyclic Graphstatic int countNodes(int V, int E, int src, int dest, int [,]edges){ // Initialize an adjacency list List<int> []adj = new List<int>[V + 1]; for (int i = 0; i < adj.Length; i++) adj[i] = new List<int>(); // Populate the edges in the list for (int i = 0; i < E; i++) { adj[edges[i, 0]].Add(edges[i, 1]); adj[edges[i, 1]].Add(edges[i, 0]); } // Mark all the nodes as // not visited int []vis = new int[V + 1]; // Count nodes in the path // from src to dest int count = dfs(src, dest, vis, adj); // Return the nodes // between src and dest return count - 2;} // Driver Codepublic static void Main(String[] args){ // Given number of vertices and edges int V = 8, E = 7; // Given source and destination vertices int src = 5, dest = 2; // Given edges int [,]edges = {{1, 4}, {4, 5}, {4, 2}, {2, 6}, {6, 3}, {2, 7}, {3, 8}}; Console.Write(countNodes(V, E, src, dest, edges));}} // This code is contributed by 29AjayKumar",
"e": 33927,
"s": 31975,
"text": null
},
{
"code": "<script>// Javascript program for the above approach // Function to return the count of nodes// in the path from source to destinationfunction dfs(src,dest,vis,adj){ // Mark the node visited vis[src] = 1; // If dest is reached if (src == dest) { return 1; } // Traverse all adjacent nodes for (let u=0;u< adj[src].length;u++) { // If not already visited if (vis[adj[src][u]] == 0) { let temp = dfs(adj[src][u], dest, vis, adj); // If there is path, then // include the current node if (temp != 0) { return temp + 1; } } } // Return 0 if there is no path // between src and dest through // the current node return 0;} // Function to return the// count of nodes between two// given vertices of the acyclic Graphfunction countNodes(V,E,src,dest,edges){ // Initialize an adjacency list let adj = new Array(V + 1); for (let i = 0; i < adj.length; i++) adj[i] = []; // Populate the edges in the list for (let i = 0; i < E; i++) { adj[edges[i][0]].push(edges[i][1]); adj[edges[i][1]].push(edges[i][0]); } // Mark all the nodes as // not visited let vis = new Array(V + 1); for(let i=0;i<vis.length;i++) { vis[i]=0; } // Count nodes in the path // from src to dest let count = dfs(src, dest, vis, adj); // Return the nodes // between src and dest return count - 2;} // Driver Code// Given number of vertices and edgeslet V = 8, E = 7; // Given source and destination verticeslet src = 5, dest = 2; // Given edgeslet edges = [[1, 4], [4, 5],[4, 2], [2, 6],[6, 3], [2, 7],[3, 8]]; document.write(countNodes(V, E, src, dest, edges)); // This code is contributed by unknown2108</script>",
"e": 35711,
"s": 33927,
"text": null
},
{
"code": null,
"e": 35713,
"s": 35711,
"text": "1"
},
{
"code": null,
"e": 35760,
"s": 35715,
"text": "Time Complexity: O(V+E)Auxiliary Space: O(V)"
},
{
"code": null,
"e": 35775,
"s": 35760,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 35792,
"s": 35775,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 35804,
"s": 35792,
"text": "29AjayKumar"
},
{
"code": null,
"e": 35816,
"s": 35804,
"text": "unknown2108"
},
{
"code": null,
"e": 35820,
"s": 35816,
"text": "DFS"
},
{
"code": null,
"e": 35837,
"s": 35820,
"text": "Graph Traversals"
},
{
"code": null,
"e": 35843,
"s": 35837,
"text": "Graph"
},
{
"code": null,
"e": 35853,
"s": 35843,
"text": "Recursion"
},
{
"code": null,
"e": 35863,
"s": 35853,
"text": "Searching"
},
{
"code": null,
"e": 35873,
"s": 35863,
"text": "Searching"
},
{
"code": null,
"e": 35883,
"s": 35873,
"text": "Recursion"
},
{
"code": null,
"e": 35887,
"s": 35883,
"text": "DFS"
},
{
"code": null,
"e": 35893,
"s": 35887,
"text": "Graph"
},
{
"code": null,
"e": 35991,
"s": 35893,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36033,
"s": 35991,
"text": "Graph Coloring | Set 2 (Greedy Algorithm)"
},
{
"code": null,
"e": 36069,
"s": 36033,
"text": "Best First Search (Informed Search)"
},
{
"code": null,
"e": 36096,
"s": 36069,
"text": "Maximum Bipartite Matching"
},
{
"code": null,
"e": 36151,
"s": 36096,
"text": "Graph Coloring | Set 1 (Introduction and Applications)"
},
{
"code": null,
"e": 36192,
"s": 36151,
"text": "Longest Path in a Directed Acyclic Graph"
},
{
"code": null,
"e": 36252,
"s": 36192,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 36337,
"s": 36252,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 36347,
"s": 36337,
"text": "Recursion"
},
{
"code": null,
"e": 36374,
"s": 36347,
"text": "Program for Tower of Hanoi"
}
] |
tooltip("show") method in Bootstrap
|
Use the tooltip(“show”) method in Bootstrap to display the tooltip. As shown below that the tooltip is visible on button click:
$(document).ready(function(){
$(".btn-primary").click(function(){
$("[data-toggle='tooltip']").tooltip('show');
});
});
The tooltip would be visible on a link wherein I have set the data-toggle attribute and the link text as shown in the following code snippet −
<a href="#" data-toggle="tooltip" title="Tooltip is visible!">
On clicking the below button, the tooltip would be visible.
</a>
You can try to run the following code to implement the tooltip(“show”) method −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h3>Demo</h3>
<a href="#" data-toggle="tooltip" title="Tooltip is visible!">On clicking the below button, the tooltip would be visible.</a>
<div>
<button type="button" class="btn btn-primary">Click me</button>
</div>
</div>
<script>
$(document).ready(function(){
$(".btn-primary").click(function(){
$("[data-toggle='tooltip']").tooltip('show');
});
});
</script>
</body>
</html>
|
[
{
"code": null,
"e": 1190,
"s": 1062,
"text": "Use the tooltip(“show”) method in Bootstrap to display the tooltip. As shown below that the tooltip is visible on button click:"
},
{
"code": null,
"e": 1318,
"s": 1190,
"text": "$(document).ready(function(){\n $(\".btn-primary\").click(function(){\n $(\"[data-toggle='tooltip']\").tooltip('show');\n });\n});"
},
{
"code": null,
"e": 1461,
"s": 1318,
"text": "The tooltip would be visible on a link wherein I have set the data-toggle attribute and the link text as shown in the following code snippet −"
},
{
"code": null,
"e": 1591,
"s": 1461,
"text": "<a href=\"#\" data-toggle=\"tooltip\" title=\"Tooltip is visible!\">\n On clicking the below button, the tooltip would be visible.\n</a>"
},
{
"code": null,
"e": 1671,
"s": 1591,
"text": "You can try to run the following code to implement the tooltip(“show”) method −"
},
{
"code": null,
"e": 1681,
"s": 1671,
"text": "Live Demo"
},
{
"code": null,
"e": 2613,
"s": 1681,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"></script>\n </head>\n\n<body>\n <div class=\"container\">\n <h3>Demo</h3>\n <a href=\"#\" data-toggle=\"tooltip\" title=\"Tooltip is visible!\">On clicking the below button, the tooltip would be visible.</a>\n <div>\n <button type=\"button\" class=\"btn btn-primary\">Click me</button>\n </div> \n </div>\n\n<script>\n$(document).ready(function(){\n $(\".btn-primary\").click(function(){\n $(\"[data-toggle='tooltip']\").tooltip('show');\n });\n});\n</script>\n\n</body>\n</html>"
}
] |
How to query and calculate GA4 event data in BigQuery | by Johan van de Werken | Towards Data Science
|
The future of app and web analytics is here: Google announced a new way of measurement in Google Analytics. While still in beta, this is a small revolution for web and app analytics.
On top of this: there is a raw data BigQuery export available for all (even non 360) Google Analytics accounts. Let’s dive right in!
Note: do you enjoy this article? Then you’ll also like my new website GA4BigQuery.com: a digital guide with tips, ideas, example queries and tutorials on how to query Google Analytics data in BigQuery & rock your digital marketing analytics 🤘
You also might be interested in a digital course that I designed together with Mari and Simo Ahava for marketing professionals who want to dive into the world of queries, and for data professionals who need to skill up on GA4-specific knowledge:
www.teamsimmer.com
In this article I will focus on web data only. I will show you how to calculate new GA4 engagement metrics, but also how to replicate ‘classic’ Google Analytics dimensions and metrics that you won’t find in the GA4 user interface anymore. But beware...
This is not Universal Analytics. Try to look at the new measurement model as an opportunity to go beyond what Universal Analytics ever could, rather than just another way to populate GA’s ancient data model. (source)
If you are new to BigQuery, I recommend reading the first part of my previous article on how to query Google Analytics (Universal Analytics) data in BigQuery.
– What is going on?– Documentation– New engagement metrics– Google Analytics 4 BigQuery export schema– Nested fields– Get all unique events and parameters– Example queries: ‘standard’ dimensions & metrics– Example queries: calculated dimensions & metrics
Krista Seiden, former Analytics Advocate at Google, explains in a series of blogs why the new Google Analytics 4 property is a big step forward:
Currently, if you have both app and website data, you are collecting and analyzing that data separately, in Google Analytics for the web, and in Google Analytics for Firebase for apps. While the platforms differ, many of the KPIs and business needs when it comes to understanding data and reporting are the same, so it’s time to bring this data together in one Analytics property! (source)
This development has severe implications on the way data will be collected and analysed.
This new type of measurement uses the same data schema as Google Analytics for Firebase (GA4F) (...) The most important thing to know about this new data schema is that it moves away from the traditional Session + Pageview method that classic Google Analytics has used for 15+ years. Instead, it uses an Event + Parameter model. It’s different, but it opens up a whole new world of possibilities in terms of what you can track, and all of the additional details you can add to each event action via the associated parameters. (source)
Return to table of contents
If all this is new to you, please read all about GA4 properties before proceeding with the queries.
www.ga4bigquery.com
In the the Google Analytics 4 property we see some new metrics that were not available earlier:
The number of sessions that lasted longer than 10 seconds, or had a conversion event, or had 2 or more screen or page views. (source: definition in GA4 UI)
Here is some background by Krista Seiden:
The idea of an engaged session stems from wanting to remove bounces from the session count, therefore, an engaged session is only counted as such after the user has been on site for 10 seconds. If they leave before then, it will count as a bounce but not as an engaged session. (source)
And Florian Perl adds:
This is more or less opposite of Universal Analytics Bounces. An Engaged session is one with at least 2 pageviews, or a pageview + an interaction, or 1 pageview with 10-second duration. The 10-second timeout cannot be changed, for now. (source)
Number of engaged sessions per user, so if we see the same user ID coming back multiple times, this may be 3, 4, or 5 sessions per user, then averaged out over your total user count, giving you an average above 1, with the actual number dependent on how many new vs returning users (or deleted cookies) your content has. (source)
This one is perhaps my favorite new metric. Why? For years, I’ve been talking about why I hate the metrics ‘Bounce Rate’ and ‘Time on Page’ in Universal Google Analytics. There is good reason for this dislike: the metrics are flawed in how they are calculated due to how the use of the web has changed since the inception of these metrics more than 15 years ago. (...) In Google Analytics for Firebase, there is a metric called ‘Engagement time’, which I like much better because it is calculated as the actual time in foreground for the app which is much more reliable than ‘Time on Page’ in Universal Google Analytics.
For A+W, we wanted to bring a similar logic, but due to how browsers and tabs work, that is much harder. Our small team spent quite some time debating on the best way to calculate a metric that would be meaningful for analysis, and eventually came to ‘Engagement time’ for web which is meant to be synonymous with how it’s calculated in app, using some new handlers to closely follow the tab in foreground, screen sleep time, etc. Essentially, a much better calculation of time on page. (source)
The percentage of engaged sessions (Engaged Sessions divided by Sessions). (source: definition in GA4 UI)
These are not immediately useful if we mean to duplicate Universal Analytics reports in App+Web: Conversions are a count of events marked as Conversions, not deduplicated on session level (so it is not really a session-scope metric). What is more, right now there is no way to specify which conversion we want to view — they are all thrown into the same pot. The most likely use case is when we only track a single Conversion event — then the report will be more meaningful. (source)
Return to table of contents
As there is no sample data set for Google Analytics 4 properties (yet?), I will use an export data set (web only) from OrangeValley, the digital marketing agency I worked for at the time of writing. Apart from the standard events that are collected through ‘enhanced measurement’, it is possible you will see some custom event parameters in our data set, like ‘wordCount’ in event ‘page_view’. This does not impact our schema in any way.
Let’s take a look at the GA4 BigQuery export schema:
As you will notice the data set is heavily organised around event and user data, supplemented with some device, geo, app and traffic source data.
Depending on various definitions, you can expect some relatively small differences between the Google Analytics 4 user interface and the results of your BigQuery export data queries. Read about differences in user counts or dimension & metric definitions.
Return to table of contents
In the Universal Analytics export schema, every row in the data set represents a single session. As the GA4 properties are event based, every row in our data set represents an event. Every event in turn can contain multiple event parameters and corresponding values. To show you how this works in BigQuery, we query our nested sample set:
SELECT *FROM `ga4.analytics_1234567890.events_*`LIMIT 3
This gives us 3 rows, which represented as a flat table would look like this:
Remember, only row 2,9 and 15 in this example are real rows in our table. The other ‘rows’ are in fact nested fields, in most cases NULL values. Only the event.params columns are populated with values.
To deal with this fields and to be able to query our tables so they meet our needs, we need the UNNEST function.
The problem here is that is essentially an array (actually in BigQuery parlance it’s a “repeated record”, but you can think of it as an array). (...) This is where the UNNEST function comes in. It basically lets you take elements in an array and expand each one of these individual elements. You can then join your original row against each unnested element to add them to your table. (source)
I highly recommend reading this article which explains the UNNEST concept in detail with the Firebase Analytics sample data set as an example.
You only have to UNNEST records that contain ‘repeated fields’. In case of our Google Analytics 4 data set these could involve:
event_params
user_properties
items
Return to table of contents
As every data set can and will contain different events and event parameters with different data types, it is very helpful to query the actual tables to find out. Especially when you lack documentation about the way data is collected. To get all unique events and parameters you can use a query like this:
In case of our data set, this results in a list of all unique events and parameters with their corresponding data type. These repeated fields contain a lot of data, which we will use to calculate dimensions and metrics.
Return to table of contents
A lot of data can be derived straight from the tables without performing calculations on the data. With the help ofUNNEST and PARSE for dates or timestamps we can do the trick.
Look at the -- comments in the example query for names and definitions and copy the part you need from the SELECT clause. Make sure that you also add any additional conditions (i.e. WITH, FROM, WHERE, GROUP BY, HAVING and ORDER BY) that are necessary to calculate the results correctly.
—
user_iduser_pseudo_iduser_first_touch_timestampuser_string_valueuser_set_timestamp_microsuser_ltv_revenue currency
user_int_valueuser_float_valueuser_double_value
www.ga4bigquery.com
—
device.categorydevice.mobile_brand_namedevice.mobile_model_namedevice.mobile_marketing_namedevice.mobile_os_hardware_modeldevice.operating_systemdevice.operating_system_versiondevice.vendor_iddevice.advertising_iddevice.languagedevice.is_limited_ad_trackingdevice.time_zone_offset_secondsdevice.browserdevice.browser_versiondevice.web_info.browserdevice.web_info.browser_versiondevice.web_info.hostname
www.ga4bigquery.com
—
geo.continentgeo.sub_continentgeo.countrygeo.regiongeo.citygeo.metro
www.ga4bigquery.com
—
app_info.idapp_info.versionapp_info.install_storeapp_info.firebase_app_idapp_info.install_source
www.ga4bigquery.com
—
traffic_source.name (user)traffic_source.medium (user)traffic_source.source (user)
www.ga4bigquery.com
—
event_dateevent_timestampevent_nameevent_keyevent_previous_timestampevent_bundle_sequence_idevent_server_timestamp_offsetstream_idplatformevent_dimensions.hostname
event_int_valueevent_float_valueevent_double_valueevent_value_in_usd
www.ga4bigquery.com
Return to table of contents
ecommerce.transaction_id
ecommerce.total_item_quantityecommerce.purchase_revenue_in_usdecommerce.purchase_revenueecommerce.refund_value_in_usdecommerce.refund_valueecommerce.shipping_value_in_usdecommerce.shipping_valueecommerce.tax_value_in_usdecommerce.tax_valueecommerce.unique_items
www.ga4bigquery.com
Return to table of contents
items.item_iditems.item_nameitems.item_branditems.item_variantitems.item_categoryitems.item_category2items.item_category3items.item_category4items.item_category5items.couponitems.affiliationitems.location_iditems.item_list_iditems.item_list_nameitems.item_list_indexitems.promotion_iditems.promotion_nameitems.creative_nameitems.creative_slot
items.price_in_usditems.priceitems.quantityitems.item_revenue_in_usditems.item_revenueitems.item_refund_in_usd
www.ga4bigquery.com
Return to table of contents
Other dimensions & metrics you are used to in your Google Analytics analysing and reporting are a bit harder to access. You’ll have to calculate them, using your own queries.
As I’ve tried to sort out the most used dimensions and metrics already, I hope I can be of help with the following example queries. There are plenty other, probably even better ways to achieve these results, but here is my two cents.
These example queries (ordered by category) contain all following Google Analytics dimensions and metrics. If you only need one dimension or metric, look at the -- comments in the example query for names and definitions and copy the part you need from the SELECT clause. Make sure that you also add any additional conditions (i.e. WITH, FROM, WHERE, GROUP BY, HAVING and ORDER BY) that are necessary to calculate the results correctly.
—
User typeCount of sessions
UsersNew users% New sessionsNumber of sessions per userEvent count per user
www.ga4bigquery.com
—
SessionsEngaged sessionsEngagement rateEngagement timeBouncesBounce rateEvent count per session
www.ga4bigquery.com
—
The calculation for engaged sessions above is based on the event ‘user_engagement’. To be more specific: when parameter ‘session_engaged’ = ‘1’. The definition of engaged sessions, according to the GA4 user interface, is:
The number of sessions that lasted longer than 10 seconds, or had a conversion event, or had 2 or more screen or page views.
You can set a conversion event in the UI, but the definitions of session length or the amount of page views cannot be changed if you use the event ‘user_engagement’. But what if we want to customise the definition of an engaged session? You could use (a variation on) this advanced query.
—
DateYearISO yearMonth of yearMonth of the yearWeek of yearWeek of the yearISO week of the yearISO week of ISO yearDay of the monthDay of weekDay of week nameHourMinuteHour of dayDate hour and minute
www.ga4bigquery.com
BigQuery displays data usually in UTC. That leads to problems when using date formatting functions because dates and times can be off. Converting the datetimes prior formatting into the correct timezone solves those issues.(source & how to)
—
Default channel grouping (user or session)Source / medium (user or session)Campaign (user or session)Full referrer
www.ga4bigquery.com
—
HostnamePagePrevious page pathPage path level 1Page path level 2Page path level 3Page path level 4Page titleLanding pageSecond pageExit page
EntrancesPageviewsUnique pageviewsPages / sessionExits% Exit
www.ga4bigquery.com
—
As I’ve had no access to any ecommerce data set for GA4 so far, I’d suggest to take a look at the query examples for ecommerce transactions and products in the guide on querying GA4 data by Bounteous.
Return to table of contents
No rights reserved
by the author.
|
[
{
"code": null,
"e": 355,
"s": 172,
"text": "The future of app and web analytics is here: Google announced a new way of measurement in Google Analytics. While still in beta, this is a small revolution for web and app analytics."
},
{
"code": null,
"e": 488,
"s": 355,
"text": "On top of this: there is a raw data BigQuery export available for all (even non 360) Google Analytics accounts. Let’s dive right in!"
},
{
"code": null,
"e": 731,
"s": 488,
"text": "Note: do you enjoy this article? Then you’ll also like my new website GA4BigQuery.com: a digital guide with tips, ideas, example queries and tutorials on how to query Google Analytics data in BigQuery & rock your digital marketing analytics 🤘"
},
{
"code": null,
"e": 977,
"s": 731,
"text": "You also might be interested in a digital course that I designed together with Mari and Simo Ahava for marketing professionals who want to dive into the world of queries, and for data professionals who need to skill up on GA4-specific knowledge:"
},
{
"code": null,
"e": 996,
"s": 977,
"text": "www.teamsimmer.com"
},
{
"code": null,
"e": 1249,
"s": 996,
"text": "In this article I will focus on web data only. I will show you how to calculate new GA4 engagement metrics, but also how to replicate ‘classic’ Google Analytics dimensions and metrics that you won’t find in the GA4 user interface anymore. But beware..."
},
{
"code": null,
"e": 1466,
"s": 1249,
"text": "This is not Universal Analytics. Try to look at the new measurement model as an opportunity to go beyond what Universal Analytics ever could, rather than just another way to populate GA’s ancient data model. (source)"
},
{
"code": null,
"e": 1625,
"s": 1466,
"text": "If you are new to BigQuery, I recommend reading the first part of my previous article on how to query Google Analytics (Universal Analytics) data in BigQuery."
},
{
"code": null,
"e": 1880,
"s": 1625,
"text": "– What is going on?– Documentation– New engagement metrics– Google Analytics 4 BigQuery export schema– Nested fields– Get all unique events and parameters– Example queries: ‘standard’ dimensions & metrics– Example queries: calculated dimensions & metrics"
},
{
"code": null,
"e": 2025,
"s": 1880,
"text": "Krista Seiden, former Analytics Advocate at Google, explains in a series of blogs why the new Google Analytics 4 property is a big step forward:"
},
{
"code": null,
"e": 2415,
"s": 2025,
"text": "Currently, if you have both app and website data, you are collecting and analyzing that data separately, in Google Analytics for the web, and in Google Analytics for Firebase for apps. While the platforms differ, many of the KPIs and business needs when it comes to understanding data and reporting are the same, so it’s time to bring this data together in one Analytics property! (source)"
},
{
"code": null,
"e": 2504,
"s": 2415,
"text": "This development has severe implications on the way data will be collected and analysed."
},
{
"code": null,
"e": 3039,
"s": 2504,
"text": "This new type of measurement uses the same data schema as Google Analytics for Firebase (GA4F) (...) The most important thing to know about this new data schema is that it moves away from the traditional Session + Pageview method that classic Google Analytics has used for 15+ years. Instead, it uses an Event + Parameter model. It’s different, but it opens up a whole new world of possibilities in terms of what you can track, and all of the additional details you can add to each event action via the associated parameters. (source)"
},
{
"code": null,
"e": 3067,
"s": 3039,
"text": "Return to table of contents"
},
{
"code": null,
"e": 3167,
"s": 3067,
"text": "If all this is new to you, please read all about GA4 properties before proceeding with the queries."
},
{
"code": null,
"e": 3187,
"s": 3167,
"text": "www.ga4bigquery.com"
},
{
"code": null,
"e": 3283,
"s": 3187,
"text": "In the the Google Analytics 4 property we see some new metrics that were not available earlier:"
},
{
"code": null,
"e": 3439,
"s": 3283,
"text": "The number of sessions that lasted longer than 10 seconds, or had a conversion event, or had 2 or more screen or page views. (source: definition in GA4 UI)"
},
{
"code": null,
"e": 3481,
"s": 3439,
"text": "Here is some background by Krista Seiden:"
},
{
"code": null,
"e": 3768,
"s": 3481,
"text": "The idea of an engaged session stems from wanting to remove bounces from the session count, therefore, an engaged session is only counted as such after the user has been on site for 10 seconds. If they leave before then, it will count as a bounce but not as an engaged session. (source)"
},
{
"code": null,
"e": 3791,
"s": 3768,
"text": "And Florian Perl adds:"
},
{
"code": null,
"e": 4036,
"s": 3791,
"text": "This is more or less opposite of Universal Analytics Bounces. An Engaged session is one with at least 2 pageviews, or a pageview + an interaction, or 1 pageview with 10-second duration. The 10-second timeout cannot be changed, for now. (source)"
},
{
"code": null,
"e": 4366,
"s": 4036,
"text": "Number of engaged sessions per user, so if we see the same user ID coming back multiple times, this may be 3, 4, or 5 sessions per user, then averaged out over your total user count, giving you an average above 1, with the actual number dependent on how many new vs returning users (or deleted cookies) your content has. (source)"
},
{
"code": null,
"e": 4987,
"s": 4366,
"text": "This one is perhaps my favorite new metric. Why? For years, I’ve been talking about why I hate the metrics ‘Bounce Rate’ and ‘Time on Page’ in Universal Google Analytics. There is good reason for this dislike: the metrics are flawed in how they are calculated due to how the use of the web has changed since the inception of these metrics more than 15 years ago. (...) In Google Analytics for Firebase, there is a metric called ‘Engagement time’, which I like much better because it is calculated as the actual time in foreground for the app which is much more reliable than ‘Time on Page’ in Universal Google Analytics."
},
{
"code": null,
"e": 5483,
"s": 4987,
"text": "For A+W, we wanted to bring a similar logic, but due to how browsers and tabs work, that is much harder. Our small team spent quite some time debating on the best way to calculate a metric that would be meaningful for analysis, and eventually came to ‘Engagement time’ for web which is meant to be synonymous with how it’s calculated in app, using some new handlers to closely follow the tab in foreground, screen sleep time, etc. Essentially, a much better calculation of time on page. (source)"
},
{
"code": null,
"e": 5589,
"s": 5483,
"text": "The percentage of engaged sessions (Engaged Sessions divided by Sessions). (source: definition in GA4 UI)"
},
{
"code": null,
"e": 6073,
"s": 5589,
"text": "These are not immediately useful if we mean to duplicate Universal Analytics reports in App+Web: Conversions are a count of events marked as Conversions, not deduplicated on session level (so it is not really a session-scope metric). What is more, right now there is no way to specify which conversion we want to view — they are all thrown into the same pot. The most likely use case is when we only track a single Conversion event — then the report will be more meaningful. (source)"
},
{
"code": null,
"e": 6101,
"s": 6073,
"text": "Return to table of contents"
},
{
"code": null,
"e": 6539,
"s": 6101,
"text": "As there is no sample data set for Google Analytics 4 properties (yet?), I will use an export data set (web only) from OrangeValley, the digital marketing agency I worked for at the time of writing. Apart from the standard events that are collected through ‘enhanced measurement’, it is possible you will see some custom event parameters in our data set, like ‘wordCount’ in event ‘page_view’. This does not impact our schema in any way."
},
{
"code": null,
"e": 6592,
"s": 6539,
"text": "Let’s take a look at the GA4 BigQuery export schema:"
},
{
"code": null,
"e": 6738,
"s": 6592,
"text": "As you will notice the data set is heavily organised around event and user data, supplemented with some device, geo, app and traffic source data."
},
{
"code": null,
"e": 6994,
"s": 6738,
"text": "Depending on various definitions, you can expect some relatively small differences between the Google Analytics 4 user interface and the results of your BigQuery export data queries. Read about differences in user counts or dimension & metric definitions."
},
{
"code": null,
"e": 7022,
"s": 6994,
"text": "Return to table of contents"
},
{
"code": null,
"e": 7361,
"s": 7022,
"text": "In the Universal Analytics export schema, every row in the data set represents a single session. As the GA4 properties are event based, every row in our data set represents an event. Every event in turn can contain multiple event parameters and corresponding values. To show you how this works in BigQuery, we query our nested sample set:"
},
{
"code": null,
"e": 7420,
"s": 7361,
"text": "SELECT *FROM `ga4.analytics_1234567890.events_*`LIMIT 3"
},
{
"code": null,
"e": 7498,
"s": 7420,
"text": "This gives us 3 rows, which represented as a flat table would look like this:"
},
{
"code": null,
"e": 7700,
"s": 7498,
"text": "Remember, only row 2,9 and 15 in this example are real rows in our table. The other ‘rows’ are in fact nested fields, in most cases NULL values. Only the event.params columns are populated with values."
},
{
"code": null,
"e": 7813,
"s": 7700,
"text": "To deal with this fields and to be able to query our tables so they meet our needs, we need the UNNEST function."
},
{
"code": null,
"e": 8207,
"s": 7813,
"text": "The problem here is that is essentially an array (actually in BigQuery parlance it’s a “repeated record”, but you can think of it as an array). (...) This is where the UNNEST function comes in. It basically lets you take elements in an array and expand each one of these individual elements. You can then join your original row against each unnested element to add them to your table. (source)"
},
{
"code": null,
"e": 8350,
"s": 8207,
"text": "I highly recommend reading this article which explains the UNNEST concept in detail with the Firebase Analytics sample data set as an example."
},
{
"code": null,
"e": 8478,
"s": 8350,
"text": "You only have to UNNEST records that contain ‘repeated fields’. In case of our Google Analytics 4 data set these could involve:"
},
{
"code": null,
"e": 8491,
"s": 8478,
"text": "event_params"
},
{
"code": null,
"e": 8507,
"s": 8491,
"text": "user_properties"
},
{
"code": null,
"e": 8513,
"s": 8507,
"text": "items"
},
{
"code": null,
"e": 8541,
"s": 8513,
"text": "Return to table of contents"
},
{
"code": null,
"e": 8847,
"s": 8541,
"text": "As every data set can and will contain different events and event parameters with different data types, it is very helpful to query the actual tables to find out. Especially when you lack documentation about the way data is collected. To get all unique events and parameters you can use a query like this:"
},
{
"code": null,
"e": 9067,
"s": 8847,
"text": "In case of our data set, this results in a list of all unique events and parameters with their corresponding data type. These repeated fields contain a lot of data, which we will use to calculate dimensions and metrics."
},
{
"code": null,
"e": 9095,
"s": 9067,
"text": "Return to table of contents"
},
{
"code": null,
"e": 9272,
"s": 9095,
"text": "A lot of data can be derived straight from the tables without performing calculations on the data. With the help ofUNNEST and PARSE for dates or timestamps we can do the trick."
},
{
"code": null,
"e": 9559,
"s": 9272,
"text": "Look at the -- comments in the example query for names and definitions and copy the part you need from the SELECT clause. Make sure that you also add any additional conditions (i.e. WITH, FROM, WHERE, GROUP BY, HAVING and ORDER BY) that are necessary to calculate the results correctly."
},
{
"code": null,
"e": 9561,
"s": 9559,
"text": "—"
},
{
"code": null,
"e": 9676,
"s": 9561,
"text": "user_iduser_pseudo_iduser_first_touch_timestampuser_string_valueuser_set_timestamp_microsuser_ltv_revenue currency"
},
{
"code": null,
"e": 9724,
"s": 9676,
"text": "user_int_valueuser_float_valueuser_double_value"
},
{
"code": null,
"e": 9744,
"s": 9724,
"text": "www.ga4bigquery.com"
},
{
"code": null,
"e": 9746,
"s": 9744,
"text": "—"
},
{
"code": null,
"e": 10149,
"s": 9746,
"text": "device.categorydevice.mobile_brand_namedevice.mobile_model_namedevice.mobile_marketing_namedevice.mobile_os_hardware_modeldevice.operating_systemdevice.operating_system_versiondevice.vendor_iddevice.advertising_iddevice.languagedevice.is_limited_ad_trackingdevice.time_zone_offset_secondsdevice.browserdevice.browser_versiondevice.web_info.browserdevice.web_info.browser_versiondevice.web_info.hostname"
},
{
"code": null,
"e": 10169,
"s": 10149,
"text": "www.ga4bigquery.com"
},
{
"code": null,
"e": 10171,
"s": 10169,
"text": "—"
},
{
"code": null,
"e": 10240,
"s": 10171,
"text": "geo.continentgeo.sub_continentgeo.countrygeo.regiongeo.citygeo.metro"
},
{
"code": null,
"e": 10260,
"s": 10240,
"text": "www.ga4bigquery.com"
},
{
"code": null,
"e": 10262,
"s": 10260,
"text": "—"
},
{
"code": null,
"e": 10359,
"s": 10262,
"text": "app_info.idapp_info.versionapp_info.install_storeapp_info.firebase_app_idapp_info.install_source"
},
{
"code": null,
"e": 10379,
"s": 10359,
"text": "www.ga4bigquery.com"
},
{
"code": null,
"e": 10381,
"s": 10379,
"text": "—"
},
{
"code": null,
"e": 10464,
"s": 10381,
"text": "traffic_source.name (user)traffic_source.medium (user)traffic_source.source (user)"
},
{
"code": null,
"e": 10484,
"s": 10464,
"text": "www.ga4bigquery.com"
},
{
"code": null,
"e": 10486,
"s": 10484,
"text": "—"
},
{
"code": null,
"e": 10650,
"s": 10486,
"text": "event_dateevent_timestampevent_nameevent_keyevent_previous_timestampevent_bundle_sequence_idevent_server_timestamp_offsetstream_idplatformevent_dimensions.hostname"
},
{
"code": null,
"e": 10719,
"s": 10650,
"text": "event_int_valueevent_float_valueevent_double_valueevent_value_in_usd"
},
{
"code": null,
"e": 10739,
"s": 10719,
"text": "www.ga4bigquery.com"
},
{
"code": null,
"e": 10767,
"s": 10739,
"text": "Return to table of contents"
},
{
"code": null,
"e": 10792,
"s": 10767,
"text": "ecommerce.transaction_id"
},
{
"code": null,
"e": 11054,
"s": 10792,
"text": "ecommerce.total_item_quantityecommerce.purchase_revenue_in_usdecommerce.purchase_revenueecommerce.refund_value_in_usdecommerce.refund_valueecommerce.shipping_value_in_usdecommerce.shipping_valueecommerce.tax_value_in_usdecommerce.tax_valueecommerce.unique_items"
},
{
"code": null,
"e": 11074,
"s": 11054,
"text": "www.ga4bigquery.com"
},
{
"code": null,
"e": 11102,
"s": 11074,
"text": "Return to table of contents"
},
{
"code": null,
"e": 11445,
"s": 11102,
"text": "items.item_iditems.item_nameitems.item_branditems.item_variantitems.item_categoryitems.item_category2items.item_category3items.item_category4items.item_category5items.couponitems.affiliationitems.location_iditems.item_list_iditems.item_list_nameitems.item_list_indexitems.promotion_iditems.promotion_nameitems.creative_nameitems.creative_slot"
},
{
"code": null,
"e": 11556,
"s": 11445,
"text": "items.price_in_usditems.priceitems.quantityitems.item_revenue_in_usditems.item_revenueitems.item_refund_in_usd"
},
{
"code": null,
"e": 11576,
"s": 11556,
"text": "www.ga4bigquery.com"
},
{
"code": null,
"e": 11604,
"s": 11576,
"text": "Return to table of contents"
},
{
"code": null,
"e": 11779,
"s": 11604,
"text": "Other dimensions & metrics you are used to in your Google Analytics analysing and reporting are a bit harder to access. You’ll have to calculate them, using your own queries."
},
{
"code": null,
"e": 12013,
"s": 11779,
"text": "As I’ve tried to sort out the most used dimensions and metrics already, I hope I can be of help with the following example queries. There are plenty other, probably even better ways to achieve these results, but here is my two cents."
},
{
"code": null,
"e": 12449,
"s": 12013,
"text": "These example queries (ordered by category) contain all following Google Analytics dimensions and metrics. If you only need one dimension or metric, look at the -- comments in the example query for names and definitions and copy the part you need from the SELECT clause. Make sure that you also add any additional conditions (i.e. WITH, FROM, WHERE, GROUP BY, HAVING and ORDER BY) that are necessary to calculate the results correctly."
},
{
"code": null,
"e": 12451,
"s": 12449,
"text": "—"
},
{
"code": null,
"e": 12478,
"s": 12451,
"text": "User typeCount of sessions"
},
{
"code": null,
"e": 12554,
"s": 12478,
"text": "UsersNew users% New sessionsNumber of sessions per userEvent count per user"
},
{
"code": null,
"e": 12574,
"s": 12554,
"text": "www.ga4bigquery.com"
},
{
"code": null,
"e": 12576,
"s": 12574,
"text": "—"
},
{
"code": null,
"e": 12672,
"s": 12576,
"text": "SessionsEngaged sessionsEngagement rateEngagement timeBouncesBounce rateEvent count per session"
},
{
"code": null,
"e": 12692,
"s": 12672,
"text": "www.ga4bigquery.com"
},
{
"code": null,
"e": 12694,
"s": 12692,
"text": "—"
},
{
"code": null,
"e": 12916,
"s": 12694,
"text": "The calculation for engaged sessions above is based on the event ‘user_engagement’. To be more specific: when parameter ‘session_engaged’ = ‘1’. The definition of engaged sessions, according to the GA4 user interface, is:"
},
{
"code": null,
"e": 13041,
"s": 12916,
"text": "The number of sessions that lasted longer than 10 seconds, or had a conversion event, or had 2 or more screen or page views."
},
{
"code": null,
"e": 13330,
"s": 13041,
"text": "You can set a conversion event in the UI, but the definitions of session length or the amount of page views cannot be changed if you use the event ‘user_engagement’. But what if we want to customise the definition of an engaged session? You could use (a variation on) this advanced query."
},
{
"code": null,
"e": 13332,
"s": 13330,
"text": "—"
},
{
"code": null,
"e": 13531,
"s": 13332,
"text": "DateYearISO yearMonth of yearMonth of the yearWeek of yearWeek of the yearISO week of the yearISO week of ISO yearDay of the monthDay of weekDay of week nameHourMinuteHour of dayDate hour and minute"
},
{
"code": null,
"e": 13551,
"s": 13531,
"text": "www.ga4bigquery.com"
},
{
"code": null,
"e": 13792,
"s": 13551,
"text": "BigQuery displays data usually in UTC. That leads to problems when using date formatting functions because dates and times can be off. Converting the datetimes prior formatting into the correct timezone solves those issues.(source & how to)"
},
{
"code": null,
"e": 13794,
"s": 13792,
"text": "—"
},
{
"code": null,
"e": 13909,
"s": 13794,
"text": "Default channel grouping (user or session)Source / medium (user or session)Campaign (user or session)Full referrer"
},
{
"code": null,
"e": 13929,
"s": 13909,
"text": "www.ga4bigquery.com"
},
{
"code": null,
"e": 13931,
"s": 13929,
"text": "—"
},
{
"code": null,
"e": 14072,
"s": 13931,
"text": "HostnamePagePrevious page pathPage path level 1Page path level 2Page path level 3Page path level 4Page titleLanding pageSecond pageExit page"
},
{
"code": null,
"e": 14133,
"s": 14072,
"text": "EntrancesPageviewsUnique pageviewsPages / sessionExits% Exit"
},
{
"code": null,
"e": 14153,
"s": 14133,
"text": "www.ga4bigquery.com"
},
{
"code": null,
"e": 14155,
"s": 14153,
"text": "—"
},
{
"code": null,
"e": 14356,
"s": 14155,
"text": "As I’ve had no access to any ecommerce data set for GA4 so far, I’d suggest to take a look at the query examples for ecommerce transactions and products in the guide on querying GA4 data by Bounteous."
},
{
"code": null,
"e": 14384,
"s": 14356,
"text": "Return to table of contents"
},
{
"code": null,
"e": 14403,
"s": 14384,
"text": "No rights reserved"
}
] |
3 Python Tricks to Read, Create, and Run Multiple Models Automatically | by Khuyen Tran | Towards Data Science
|
When putting your code into production, you will most likely need to deal with organizing the files of your code. It can be really time-consuming to read, create, and run many files of data. This article will show you how to automatically
Loop through files in a directory
Create nested files if they do not exist
Run one file with different inputs using bash for loop
These tricks have saved me a lot of time while working on my data science projects. I hope you will find them useful as well!
If we have multiple data to read and process like this:
├── data│ ├── data1.csv│ ├── data2.csv│ └── data3.csv└── main.py
we can try to manually read one file at a time
import pandas as pd def process_data(df): passdf = pd.read_csv(data1.csv)process_data(df)df2 = pd.read_csv(data2.csv)process_data(df2)df3 = pd.read_csv(data3.csv)process_data(df3)
This works but not efficiently when we have more than 3 data. If the only thing we change in the script above is the data, why not use the a for loop to access each data instead?
The script below allows us to loop through files in a specified directory
data/data3.csvdata/data2.csvdata/data1.csv
Here are the explanations for the script above
for filename in os.listdir(directory) : loop through files in a specific directory
if filename.endswith(".csv") : access the files that end with ‘.csv’
file_directory = os.path.join(directory, filename) : join the parent directory (‘data’) and the files within the directory.
Now we can access all your files within the ‘data’ directory!
Sometimes we might want to create nested files to organize our code or model, which makes it easier in the future for us to find them. For example, we might use ‘model 1’ to specify a specific feature engineering.
While using model 1, we might want to use different types of machine learning models to train our data (‘model1/XGBoost’).
While using each machine learning model, we might even want to save different versions of the model because of the difference in hyperparameters used for the model.
Thus, our model directory can look as complicated as below
model├── model1│ ├── NaiveBayes│ └── XGBoost│ ├── version_1│ └── version_2└── model2 ├── NaiveBayes └── XGBoost ├── version_1 └── version_2
It might take a lot of time for us to manually create a nested file for every model we create. Is there a way that we can automate this process? Yes, with os.makedirs(datapath).
Run the file above and you should see the nested file ‘model/model2/XGBoost/version_2’ created automatically!
Now you can save your model or data to the new directory!
What if we want to run one file with different parameters? For example, we might want to use the same script to predict data using different models.
If one script takes a long time to run and we have multiple models to run, it will be time-consuming for us to wait for the script to finish running then run the next one. Is there a way that we can tell the computer to run model 1, 2, 3,.., 10 with one command line then go and do something else.
Yes, we can with for bash for loop. First, we use sys.argv to enable us to parse command-line arguments. You can also use tools such as hydra if you want to overwrite your config file on the command line.
>>> python train.py XGBoost 1Loading model from model/model1/XGBoost/version_1 for training
Sweet! We have just told our script to use the model XGBoost, version 1 to predict the data on the command line. Now we can use the bash for loop to loop through different versions of the model.
If you can do a for loop with Python, you can also do that on the terminal like below
$ for version in 2 3 4> do> python train.py XGBoost $version> done
Type Enter to separate the lines
Output:
Loading model from model/model1/XGBoost/version_1 for trainingLoading model from model/model1/XGBoost/version_2 for trainingLoading model from model/model1/XGBoost/version_3 for trainingLoading model from model/model1/XGBoost/version_4 for training
Now you can do other things while letting your script run using different models! How convenient is that!
Congratulations! You have just learned how to automatically read and create multiple files at once. You also learned how to run one file with different parameters. The time you spend manually reading, writing, and running files can now be saved for more important tasks.
If there are some parts in the articles that you are confused about, I created concrete examples in this repo.
I like to write about basic data science concepts and play with different algorithms and 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": 411,
"s": 172,
"text": "When putting your code into production, you will most likely need to deal with organizing the files of your code. It can be really time-consuming to read, create, and run many files of data. This article will show you how to automatically"
},
{
"code": null,
"e": 445,
"s": 411,
"text": "Loop through files in a directory"
},
{
"code": null,
"e": 486,
"s": 445,
"text": "Create nested files if they do not exist"
},
{
"code": null,
"e": 541,
"s": 486,
"text": "Run one file with different inputs using bash for loop"
},
{
"code": null,
"e": 667,
"s": 541,
"text": "These tricks have saved me a lot of time while working on my data science projects. I hope you will find them useful as well!"
},
{
"code": null,
"e": 723,
"s": 667,
"text": "If we have multiple data to read and process like this:"
},
{
"code": null,
"e": 794,
"s": 723,
"text": "├── data│ ├── data1.csv│ ├── data2.csv│ └── data3.csv└── main.py"
},
{
"code": null,
"e": 841,
"s": 794,
"text": "we can try to manually read one file at a time"
},
{
"code": null,
"e": 1023,
"s": 841,
"text": "import pandas as pd def process_data(df): passdf = pd.read_csv(data1.csv)process_data(df)df2 = pd.read_csv(data2.csv)process_data(df2)df3 = pd.read_csv(data3.csv)process_data(df3)"
},
{
"code": null,
"e": 1202,
"s": 1023,
"text": "This works but not efficiently when we have more than 3 data. If the only thing we change in the script above is the data, why not use the a for loop to access each data instead?"
},
{
"code": null,
"e": 1276,
"s": 1202,
"text": "The script below allows us to loop through files in a specified directory"
},
{
"code": null,
"e": 1319,
"s": 1276,
"text": "data/data3.csvdata/data2.csvdata/data1.csv"
},
{
"code": null,
"e": 1366,
"s": 1319,
"text": "Here are the explanations for the script above"
},
{
"code": null,
"e": 1449,
"s": 1366,
"text": "for filename in os.listdir(directory) : loop through files in a specific directory"
},
{
"code": null,
"e": 1518,
"s": 1449,
"text": "if filename.endswith(\".csv\") : access the files that end with ‘.csv’"
},
{
"code": null,
"e": 1642,
"s": 1518,
"text": "file_directory = os.path.join(directory, filename) : join the parent directory (‘data’) and the files within the directory."
},
{
"code": null,
"e": 1704,
"s": 1642,
"text": "Now we can access all your files within the ‘data’ directory!"
},
{
"code": null,
"e": 1918,
"s": 1704,
"text": "Sometimes we might want to create nested files to organize our code or model, which makes it easier in the future for us to find them. For example, we might use ‘model 1’ to specify a specific feature engineering."
},
{
"code": null,
"e": 2041,
"s": 1918,
"text": "While using model 1, we might want to use different types of machine learning models to train our data (‘model1/XGBoost’)."
},
{
"code": null,
"e": 2206,
"s": 2041,
"text": "While using each machine learning model, we might even want to save different versions of the model because of the difference in hyperparameters used for the model."
},
{
"code": null,
"e": 2265,
"s": 2206,
"text": "Thus, our model directory can look as complicated as below"
},
{
"code": null,
"e": 2441,
"s": 2265,
"text": "model├── model1│ ├── NaiveBayes│ └── XGBoost│ ├── version_1│ └── version_2└── model2 ├── NaiveBayes └── XGBoost ├── version_1 └── version_2"
},
{
"code": null,
"e": 2619,
"s": 2441,
"text": "It might take a lot of time for us to manually create a nested file for every model we create. Is there a way that we can automate this process? Yes, with os.makedirs(datapath)."
},
{
"code": null,
"e": 2729,
"s": 2619,
"text": "Run the file above and you should see the nested file ‘model/model2/XGBoost/version_2’ created automatically!"
},
{
"code": null,
"e": 2787,
"s": 2729,
"text": "Now you can save your model or data to the new directory!"
},
{
"code": null,
"e": 2936,
"s": 2787,
"text": "What if we want to run one file with different parameters? For example, we might want to use the same script to predict data using different models."
},
{
"code": null,
"e": 3234,
"s": 2936,
"text": "If one script takes a long time to run and we have multiple models to run, it will be time-consuming for us to wait for the script to finish running then run the next one. Is there a way that we can tell the computer to run model 1, 2, 3,.., 10 with one command line then go and do something else."
},
{
"code": null,
"e": 3439,
"s": 3234,
"text": "Yes, we can with for bash for loop. First, we use sys.argv to enable us to parse command-line arguments. You can also use tools such as hydra if you want to overwrite your config file on the command line."
},
{
"code": null,
"e": 3531,
"s": 3439,
"text": ">>> python train.py XGBoost 1Loading model from model/model1/XGBoost/version_1 for training"
},
{
"code": null,
"e": 3726,
"s": 3531,
"text": "Sweet! We have just told our script to use the model XGBoost, version 1 to predict the data on the command line. Now we can use the bash for loop to loop through different versions of the model."
},
{
"code": null,
"e": 3812,
"s": 3726,
"text": "If you can do a for loop with Python, you can also do that on the terminal like below"
},
{
"code": null,
"e": 3879,
"s": 3812,
"text": "$ for version in 2 3 4> do> python train.py XGBoost $version> done"
},
{
"code": null,
"e": 3912,
"s": 3879,
"text": "Type Enter to separate the lines"
},
{
"code": null,
"e": 3920,
"s": 3912,
"text": "Output:"
},
{
"code": null,
"e": 4169,
"s": 3920,
"text": "Loading model from model/model1/XGBoost/version_1 for trainingLoading model from model/model1/XGBoost/version_2 for trainingLoading model from model/model1/XGBoost/version_3 for trainingLoading model from model/model1/XGBoost/version_4 for training"
},
{
"code": null,
"e": 4275,
"s": 4169,
"text": "Now you can do other things while letting your script run using different models! How convenient is that!"
},
{
"code": null,
"e": 4546,
"s": 4275,
"text": "Congratulations! You have just learned how to automatically read and create multiple files at once. You also learned how to run one file with different parameters. The time you spend manually reading, writing, and running files can now be saved for more important tasks."
},
{
"code": null,
"e": 4657,
"s": 4546,
"text": "If there are some parts in the articles that you are confused about, I created concrete examples in this repo."
},
{
"code": null,
"e": 4817,
"s": 4657,
"text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter."
}
] |
Check if Email Address is Valid or not in Java - GeeksforGeeks
|
22 Oct, 2021
Given a string, find if the given string is a valid email or not.
Input : email = "review-team@geeksforgeeks.org"
Output : Yes
Input : email = "contribute@geeksforgeeks..org"
Output : No
Explanation : There is an extra dot(.) before org.
Prerequisite: Regular Expressions in Java
Regular Expressions or Regex is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are a few areas of strings where Regex is widely used to define the constraints. Regular Expressions are provided under java.util.regex package.
In order to check that an email address is valid or not, we use the below-given regular expression provided in the OWASP Validation Regex repository.
^[a-zA-Z0-9_+&*-] + (?:\\.[a-zA-Z0-9_+&*-]
+ )*@(?:[a-zA-Z0-9-]+\\.) + [a-zA-Z]{2, 7}$
Code –
Java
// Java program to check if an email address// is valid using Regex.import java.util.regex.Matcher;import java.util.regex.Pattern;import java.util.*; class Test{ public static boolean isValid(String email) { String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\."+ "[a-zA-Z0-9_+&*-]+)*@" + "(?:[a-zA-Z0-9-]+\\.)+[a-z" + "A-Z]{2,7}$"; Pattern pat = Pattern.compile(emailRegex); if (email == null) return false; return pat.matcher(email).matches(); } public static void main(String[] args) { ArrayList<String> address = new ArrayList<>(); address.add("review-team@geeksforgeeks.org"); address.add("writing.geeksforgeeks.org"); for(String i : address){ if (isValid(i)) System.out.println(i + " - Yes"); else System.out.println(i + " - No"); } }}
review-team@geeksforgeeks.org - Yes
writing.geeksforgeeks.org - No
This article is contributed by Pranav. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nishkarshgandhi
java-regular-expression
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Interfaces in Java
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
Overriding in Java
Stack Class in Java
Collections in Java
|
[
{
"code": null,
"e": 24403,
"s": 24375,
"text": "\n22 Oct, 2021"
},
{
"code": null,
"e": 24469,
"s": 24403,
"text": "Given a string, find if the given string is a valid email or not."
},
{
"code": null,
"e": 24642,
"s": 24469,
"text": "Input : email = \"review-team@geeksforgeeks.org\"\nOutput : Yes\n\nInput : email = \"contribute@geeksforgeeks..org\"\nOutput : No\nExplanation : There is an extra dot(.) before org."
},
{
"code": null,
"e": 24685,
"s": 24642,
"text": "Prerequisite: Regular Expressions in Java "
},
{
"code": null,
"e": 25006,
"s": 24685,
"text": "Regular Expressions or Regex is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are a few areas of strings where Regex is widely used to define the constraints. Regular Expressions are provided under java.util.regex package. "
},
{
"code": null,
"e": 25156,
"s": 25006,
"text": "In order to check that an email address is valid or not, we use the below-given regular expression provided in the OWASP Validation Regex repository."
},
{
"code": null,
"e": 25244,
"s": 25156,
"text": "^[a-zA-Z0-9_+&*-] + (?:\\\\.[a-zA-Z0-9_+&*-]\n+ )*@(?:[a-zA-Z0-9-]+\\\\.) + [a-zA-Z]{2, 7}$ "
},
{
"code": null,
"e": 25252,
"s": 25244,
"text": "Code – "
},
{
"code": null,
"e": 25257,
"s": 25252,
"text": "Java"
},
{
"code": "// Java program to check if an email address// is valid using Regex.import java.util.regex.Matcher;import java.util.regex.Pattern;import java.util.*; class Test{ public static boolean isValid(String email) { String emailRegex = \"^[a-zA-Z0-9_+&*-]+(?:\\\\.\"+ \"[a-zA-Z0-9_+&*-]+)*@\" + \"(?:[a-zA-Z0-9-]+\\\\.)+[a-z\" + \"A-Z]{2,7}$\"; Pattern pat = Pattern.compile(emailRegex); if (email == null) return false; return pat.matcher(email).matches(); } public static void main(String[] args) { ArrayList<String> address = new ArrayList<>(); address.add(\"review-team@geeksforgeeks.org\"); address.add(\"writing.geeksforgeeks.org\"); for(String i : address){ if (isValid(i)) System.out.println(i + \" - Yes\"); else System.out.println(i + \" - No\"); } }}",
"e": 26277,
"s": 25257,
"text": null
},
{
"code": null,
"e": 26344,
"s": 26277,
"text": "review-team@geeksforgeeks.org - Yes\nwriting.geeksforgeeks.org - No"
},
{
"code": null,
"e": 26760,
"s": 26344,
"text": "This article is contributed by Pranav. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 26776,
"s": 26760,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 26800,
"s": 26776,
"text": "java-regular-expression"
},
{
"code": null,
"e": 26805,
"s": 26800,
"text": "Java"
},
{
"code": null,
"e": 26810,
"s": 26805,
"text": "Java"
},
{
"code": null,
"e": 26908,
"s": 26810,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26917,
"s": 26908,
"text": "Comments"
},
{
"code": null,
"e": 26930,
"s": 26917,
"text": "Old Comments"
},
{
"code": null,
"e": 26960,
"s": 26930,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 26979,
"s": 26960,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27011,
"s": 26979,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 27062,
"s": 27011,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 27080,
"s": 27062,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 27111,
"s": 27080,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 27143,
"s": 27111,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 27162,
"s": 27143,
"text": "Overriding in Java"
},
{
"code": null,
"e": 27182,
"s": 27162,
"text": "Stack Class in Java"
}
] |
Traversing a map (or unordered_map) in C++ STL - GeeksforGeeks
|
08 Jul, 2021
We can traverse map and unordered_map using following different ways.
Using a range based for loop
map
unordered_map
// CPP program to traverse a map using range// based for loop#include <bits/stdc++.h>using namespace std; int main(){ int arr[] = { 1, 1, 2, 1, 1, 3, 4, 3 }; int n = sizeof(arr) / sizeof(arr[0]); map<int, int> m; for (int i = 0; i < n; i++) m[arr[i]]++; cout << "Element Frequency" << endl; for (auto i : m) cout << i.first << " " << i.second << endl; return 0;}
// CPP program to traverse a unordered_map using// range based for loop#include <bits/stdc++.h>using namespace std; int main(){ int arr[] = { 1, 1, 2, 1, 1, 3, 4, 3 }; int n = sizeof(arr) / sizeof(arr[0]); unordered_map<int, int> m; for (int i = 0; i < n; i++) m[arr[i]]++; cout << "Element Frequency" << endl; for (auto i : m) cout << i.first << " " << i.second << endl; return 0;}
Element Frequency
1 4
2 1
3 2
4 1
Output [NOTE: For unordered_map output rows can be in any order]
Traversing using begin() and end()
map
unordered_map
// CPP program to traverse a map using iterators#include <bits/stdc++.h>using namespace std; int main(){ int arr[] = { 1, 1, 2, 1, 1, 3, 4, 3 }; int n = sizeof(arr) / sizeof(arr[0]); map<int, int> m; for (int i = 0; i < n; i++) m[arr[i]]++; cout << " Element Frequency" << endl; for (auto i = m.begin(); i != m.end(); i++) cout << i->first << " " << i->second << endl; return 0;}
// CPP program to traverse a unordered_map// using iterators#include <bits/stdc++.h>using namespace std; int main(){ int arr[] = { 1, 1, 2, 1, 1, 3, 4, 3 }; int n = sizeof(arr) / sizeof(arr[0]); unordered_map<int, int> m; for (int i = 0; i < n; i++) m[arr[i]]++; cout << " Element Frequency" << endl; for (auto i = m.begin(); i != m.end(); i++) cout << i->first << " " << i->second << endl; return 0;}
Element Frequency
1 4
2 1
3 2
4 1
Output [NOTE: For unordered_map output rows can be in any order]
Iterating over a map by using STL Iterator:
By creating an iterator of std::map and initializing it to the starting of map and visiting upto the end of map we can successfully iterate over all the elements of map.
So, let’s see the below program to know how to do it.
C++
#include <iostream>#include <map>#include <string>#include <iterator>#include <algorithm> int main(){ // Map created std::map<std::string, int> ExampleMap; // elements are inserted into map ExampleMap.insert(std::pair<std::string, int>("Sunday", 1)); ExampleMap.insert(std::pair<std::string, int>("Monday", 2)); ExampleMap.insert(std::pair<std::string, int>("Tuesday", 3)); ExampleMap.insert(std::pair<std::string, int>("Wednesday", 4)); ExampleMap.insert(std::pair<std::string, int>("Thursday", 5)); ExampleMap.insert(std::pair<std::string, int>("Friday", 6)); ExampleMap.insert(std::pair<std::string, int>("Saturday", 7)); // map iterator created // iterator pointing to start of map std::map<std::string, int>::iterator it = ExampleMap.begin(); // Iterating over the map using Iterator till map end. while (it != ExampleMap.end()) { // Accessing the key std::string word = it->first; // Accessing the value int count = it->second; std::cout << word << " :: " << count << std::endl; // iterator incremented to point next item it++; } return 0;}
Friday :: 6
Monday :: 2
Saturday :: 7
Sunday :: 1
Thursday :: 5
Tuesday :: 3
Wednesday :: 4
Iterating over a map by using std::for_each and lambda function:
By using std::for and lambda function we can can successfully iterate over all the elements of map.
Where lambda function will be used as call back function and will receive each map entry.
So, let’s see the below program to know how to do it.
C++
#include <iostream>#include <map>#include <string>#include <iterator>#include <algorithm> int main(){ // Map created std::map<std::string, int> ExampleMap; // elements are inserted into map ExampleMap.insert(std::pair<std::string, int>("Sunday", 1)); ExampleMap.insert(std::pair<std::string, int>("Monday", 2)); ExampleMap.insert(std::pair<std::string, int>("Tuesday", 3)); ExampleMap.insert(std::pair<std::string, int>("Wednesday", 4)); ExampleMap.insert(std::pair<std::string, int>("Thursday", 5)); ExampleMap.insert(std::pair<std::string, int>("Friday", 6)); ExampleMap.insert(std::pair<std::string, int>("Saturday", 7)); // map iterator created // iterator pointing to start of map std::map<std::string, int>::iterator it = ExampleMap.begin(); // Iterating over the map till map end. std::for_each(ExampleMap.begin(), ExampleMap.end(), [](std::pair<std::string, int> key_value) { // Accessing the key std::string word = key_value.first; // Accessing the value int count = key_value.second; std::cout<<word<<" :: "<<count<<std::endl; }); return 0;}
Friday :: 6
Monday :: 2
Saturday :: 7
Sunday :: 1
Thursday :: 5
Tuesday :: 3
Wednesday :: 4
This article is contributed by Kartik. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Satyabrata_Jena
cpp-unordered_map
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
Virtual Function in C++
C++ Classes and Objects
Bitwise Operators in C/C++
Constructors in C++
Templates in C++ with Examples
Operator Overloading in C++
Socket Programming in C/C++
Polymorphism in C++
Object Oriented Programming in C++
|
[
{
"code": null,
"e": 25924,
"s": 25896,
"text": "\n08 Jul, 2021"
},
{
"code": null,
"e": 25995,
"s": 25924,
"text": "We can traverse map and unordered_map using following different ways. "
},
{
"code": null,
"e": 26024,
"s": 25995,
"text": "Using a range based for loop"
},
{
"code": null,
"e": 26030,
"s": 26026,
"text": "map"
},
{
"code": null,
"e": 26044,
"s": 26030,
"text": "unordered_map"
},
{
"code": "// CPP program to traverse a map using range// based for loop#include <bits/stdc++.h>using namespace std; int main(){ int arr[] = { 1, 1, 2, 1, 1, 3, 4, 3 }; int n = sizeof(arr) / sizeof(arr[0]); map<int, int> m; for (int i = 0; i < n; i++) m[arr[i]]++; cout << \"Element Frequency\" << endl; for (auto i : m) cout << i.first << \" \" << i.second << endl; return 0;}",
"e": 26460,
"s": 26044,
"text": null
},
{
"code": "// CPP program to traverse a unordered_map using// range based for loop#include <bits/stdc++.h>using namespace std; int main(){ int arr[] = { 1, 1, 2, 1, 1, 3, 4, 3 }; int n = sizeof(arr) / sizeof(arr[0]); unordered_map<int, int> m; for (int i = 0; i < n; i++) m[arr[i]]++; cout << \"Element Frequency\" << endl; for (auto i : m) cout << i.first << \" \" << i.second << endl; return 0;}",
"e": 26896,
"s": 26460,
"text": null
},
{
"code": null,
"e": 26940,
"s": 26896,
"text": "Element Frequency\n1 4\n2 1\n3 2\n4 1\n"
},
{
"code": null,
"e": 27006,
"s": 26940,
"text": "Output [NOTE: For unordered_map output rows can be in any order] "
},
{
"code": null,
"e": 27041,
"s": 27006,
"text": "Traversing using begin() and end()"
},
{
"code": null,
"e": 27047,
"s": 27043,
"text": "map"
},
{
"code": null,
"e": 27061,
"s": 27047,
"text": "unordered_map"
},
{
"code": "// CPP program to traverse a map using iterators#include <bits/stdc++.h>using namespace std; int main(){ int arr[] = { 1, 1, 2, 1, 1, 3, 4, 3 }; int n = sizeof(arr) / sizeof(arr[0]); map<int, int> m; for (int i = 0; i < n; i++) m[arr[i]]++; cout << \" Element Frequency\" << endl; for (auto i = m.begin(); i != m.end(); i++) cout << i->first << \" \" << i->second << endl; return 0;}",
"e": 27496,
"s": 27061,
"text": null
},
{
"code": "// CPP program to traverse a unordered_map// using iterators#include <bits/stdc++.h>using namespace std; int main(){ int arr[] = { 1, 1, 2, 1, 1, 3, 4, 3 }; int n = sizeof(arr) / sizeof(arr[0]); unordered_map<int, int> m; for (int i = 0; i < n; i++) m[arr[i]]++; cout << \" Element Frequency\" << endl; for (auto i = m.begin(); i != m.end(); i++) cout << i->first << \" \" << i->second << endl; return 0;}",
"e": 27954,
"s": 27496,
"text": null
},
{
"code": null,
"e": 28010,
"s": 27954,
"text": " Element Frequency\n1 4\n2 1\n3 2\n4 1\n"
},
{
"code": null,
"e": 28077,
"s": 28010,
"text": "Output [NOTE: For unordered_map output rows can be in any order] "
},
{
"code": null,
"e": 28121,
"s": 28077,
"text": "Iterating over a map by using STL Iterator:"
},
{
"code": null,
"e": 28291,
"s": 28121,
"text": "By creating an iterator of std::map and initializing it to the starting of map and visiting upto the end of map we can successfully iterate over all the elements of map."
},
{
"code": null,
"e": 28345,
"s": 28291,
"text": "So, let’s see the below program to know how to do it."
},
{
"code": null,
"e": 28349,
"s": 28345,
"text": "C++"
},
{
"code": "#include <iostream>#include <map>#include <string>#include <iterator>#include <algorithm> int main(){ // Map created std::map<std::string, int> ExampleMap; // elements are inserted into map ExampleMap.insert(std::pair<std::string, int>(\"Sunday\", 1)); ExampleMap.insert(std::pair<std::string, int>(\"Monday\", 2)); ExampleMap.insert(std::pair<std::string, int>(\"Tuesday\", 3)); ExampleMap.insert(std::pair<std::string, int>(\"Wednesday\", 4)); ExampleMap.insert(std::pair<std::string, int>(\"Thursday\", 5)); ExampleMap.insert(std::pair<std::string, int>(\"Friday\", 6)); ExampleMap.insert(std::pair<std::string, int>(\"Saturday\", 7)); // map iterator created // iterator pointing to start of map std::map<std::string, int>::iterator it = ExampleMap.begin(); // Iterating over the map using Iterator till map end. while (it != ExampleMap.end()) { // Accessing the key std::string word = it->first; // Accessing the value int count = it->second; std::cout << word << \" :: \" << count << std::endl; // iterator incremented to point next item it++; } return 0;}",
"e": 29514,
"s": 28349,
"text": null
},
{
"code": null,
"e": 29607,
"s": 29514,
"text": "Friday :: 6\nMonday :: 2\nSaturday :: 7\nSunday :: 1\nThursday :: 5\nTuesday :: 3\nWednesday :: 4\n"
},
{
"code": null,
"e": 29674,
"s": 29609,
"text": "Iterating over a map by using std::for_each and lambda function:"
},
{
"code": null,
"e": 29774,
"s": 29674,
"text": "By using std::for and lambda function we can can successfully iterate over all the elements of map."
},
{
"code": null,
"e": 29864,
"s": 29774,
"text": "Where lambda function will be used as call back function and will receive each map entry."
},
{
"code": null,
"e": 29918,
"s": 29864,
"text": "So, let’s see the below program to know how to do it."
},
{
"code": null,
"e": 29922,
"s": 29918,
"text": "C++"
},
{
"code": "#include <iostream>#include <map>#include <string>#include <iterator>#include <algorithm> int main(){ // Map created std::map<std::string, int> ExampleMap; // elements are inserted into map ExampleMap.insert(std::pair<std::string, int>(\"Sunday\", 1)); ExampleMap.insert(std::pair<std::string, int>(\"Monday\", 2)); ExampleMap.insert(std::pair<std::string, int>(\"Tuesday\", 3)); ExampleMap.insert(std::pair<std::string, int>(\"Wednesday\", 4)); ExampleMap.insert(std::pair<std::string, int>(\"Thursday\", 5)); ExampleMap.insert(std::pair<std::string, int>(\"Friday\", 6)); ExampleMap.insert(std::pair<std::string, int>(\"Saturday\", 7)); // map iterator created // iterator pointing to start of map std::map<std::string, int>::iterator it = ExampleMap.begin(); // Iterating over the map till map end. std::for_each(ExampleMap.begin(), ExampleMap.end(), [](std::pair<std::string, int> key_value) { // Accessing the key std::string word = key_value.first; // Accessing the value int count = key_value.second; std::cout<<word<<\" :: \"<<count<<std::endl; }); return 0;}",
"e": 31173,
"s": 29922,
"text": null
},
{
"code": null,
"e": 31266,
"s": 31173,
"text": "Friday :: 6\nMonday :: 2\nSaturday :: 7\nSunday :: 1\nThursday :: 5\nTuesday :: 3\nWednesday :: 4\n"
},
{
"code": null,
"e": 31681,
"s": 31266,
"text": "This article is contributed by Kartik. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 31697,
"s": 31681,
"text": "Satyabrata_Jena"
},
{
"code": null,
"e": 31715,
"s": 31697,
"text": "cpp-unordered_map"
},
{
"code": null,
"e": 31719,
"s": 31715,
"text": "STL"
},
{
"code": null,
"e": 31723,
"s": 31719,
"text": "C++"
},
{
"code": null,
"e": 31727,
"s": 31723,
"text": "STL"
},
{
"code": null,
"e": 31731,
"s": 31727,
"text": "CPP"
},
{
"code": null,
"e": 31829,
"s": 31731,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31848,
"s": 31829,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 31872,
"s": 31848,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 31896,
"s": 31872,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 31923,
"s": 31896,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 31943,
"s": 31923,
"text": "Constructors in C++"
},
{
"code": null,
"e": 31974,
"s": 31943,
"text": "Templates in C++ with Examples"
},
{
"code": null,
"e": 32002,
"s": 31974,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 32030,
"s": 32002,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 32050,
"s": 32030,
"text": "Polymorphism in C++"
}
] |
sigwaitinfo() - Unix, Linux System Call
|
Unix - Home
Unix - Getting Started
Unix - File Management
Unix - Directories
Unix - File Permission
Unix - Environment
Unix - Basic Utilities
Unix - Pipes & Filters
Unix - Processes
Unix - Communication
Unix - The vi Editor
Unix - What is Shell?
Unix - Using Variables
Unix - Special Variables
Unix - Using Arrays
Unix - Basic Operators
Unix - Decision Making
Unix - Shell Loops
Unix - Loop Control
Unix - Shell Substitutions
Unix - Quoting Mechanisms
Unix - IO Redirections
Unix - Shell Functions
Unix - Manpage Help
Unix - Regular Expressions
Unix - File System Basics
Unix - User Administration
Unix - System Performance
Unix - System Logging
Unix - Signals and Traps
Unix - Useful Commands
Unix - Quick Guide
Unix - Builtin Functions
Unix - System Calls
Unix - Commands List
Unix Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
#include <signal.h>
int sigwaitinfo(const sigset_t *set, siginfo_t *info);
int sigtimedwait(const sigset_t *set, siginfo_t *info,
const struct timespec *timeout);
int sigwaitinfo(const sigset_t *set, siginfo_t *info);
int sigtimedwait(const sigset_t *set, siginfo_t *info,
const struct timespec *timeout);
sigwaitinfo() removes the delivered signal from the calling process’s list of pending
signals and returns the signal number as its function result.
If the
info argument is not NULL,
then it returns a structure of type
siginfo_t (see
sigaction(2))
containing information about the signal.
Signals returned via
sigwaitinfo() are delivered in the usual order; see
signal(7)
for further details.
sigtimedwait() operates in exactly the same way as
sigwaitinfo() except that it has an additional argument,
timeout, which enables an upper bound to be placed on the time for which
the process is suspended.
This argument is of the following type:
struct timespec {
long tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
}
If both fields of this structure are specified as 0, a poll is performed:
sigtimedwait() returns immediately, either with information about a signal that
was pending for the caller, or with an error
if none of the signals in
set was pending.
POSIX leaves the meaning of a NULL value for the
timeout argument of
sigtimedwait() unspecified, permitting the possibility that this has the same meaning
as a call to
sigwaitinfo(), and indeed this is what is done on Linux.
kill (2)
kill (2)
sigaction (2)
sigaction (2)
signal (2)
signal (2)
sigpending (2)
sigpending (2)
sigprocmask (2)
sigprocmask (2)
sigqueue (2)
sigqueue (2)
Advertisements
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1466,
"s": 1454,
"text": "Unix - Home"
},
{
"code": null,
"e": 1489,
"s": 1466,
"text": "Unix - Getting Started"
},
{
"code": null,
"e": 1512,
"s": 1489,
"text": "Unix - File Management"
},
{
"code": null,
"e": 1531,
"s": 1512,
"text": "Unix - Directories"
},
{
"code": null,
"e": 1554,
"s": 1531,
"text": "Unix - File Permission"
},
{
"code": null,
"e": 1573,
"s": 1554,
"text": "Unix - Environment"
},
{
"code": null,
"e": 1596,
"s": 1573,
"text": "Unix - Basic Utilities"
},
{
"code": null,
"e": 1619,
"s": 1596,
"text": "Unix - Pipes & Filters"
},
{
"code": null,
"e": 1636,
"s": 1619,
"text": "Unix - Processes"
},
{
"code": null,
"e": 1657,
"s": 1636,
"text": "Unix - Communication"
},
{
"code": null,
"e": 1678,
"s": 1657,
"text": "Unix - The vi Editor"
},
{
"code": null,
"e": 1700,
"s": 1678,
"text": "Unix - What is Shell?"
},
{
"code": null,
"e": 1723,
"s": 1700,
"text": "Unix - Using Variables"
},
{
"code": null,
"e": 1748,
"s": 1723,
"text": "Unix - Special Variables"
},
{
"code": null,
"e": 1768,
"s": 1748,
"text": "Unix - Using Arrays"
},
{
"code": null,
"e": 1791,
"s": 1768,
"text": "Unix - Basic Operators"
},
{
"code": null,
"e": 1814,
"s": 1791,
"text": "Unix - Decision Making"
},
{
"code": null,
"e": 1833,
"s": 1814,
"text": "Unix - Shell Loops"
},
{
"code": null,
"e": 1853,
"s": 1833,
"text": "Unix - Loop Control"
},
{
"code": null,
"e": 1880,
"s": 1853,
"text": "Unix - Shell Substitutions"
},
{
"code": null,
"e": 1906,
"s": 1880,
"text": "Unix - Quoting Mechanisms"
},
{
"code": null,
"e": 1929,
"s": 1906,
"text": "Unix - IO Redirections"
},
{
"code": null,
"e": 1952,
"s": 1929,
"text": "Unix - Shell Functions"
},
{
"code": null,
"e": 1972,
"s": 1952,
"text": "Unix - Manpage Help"
},
{
"code": null,
"e": 1999,
"s": 1972,
"text": "Unix - Regular Expressions"
},
{
"code": null,
"e": 2025,
"s": 1999,
"text": "Unix - File System Basics"
},
{
"code": null,
"e": 2052,
"s": 2025,
"text": "Unix - User Administration"
},
{
"code": null,
"e": 2078,
"s": 2052,
"text": "Unix - System Performance"
},
{
"code": null,
"e": 2100,
"s": 2078,
"text": "Unix - System Logging"
},
{
"code": null,
"e": 2125,
"s": 2100,
"text": "Unix - Signals and Traps"
},
{
"code": null,
"e": 2148,
"s": 2125,
"text": "Unix - Useful Commands"
},
{
"code": null,
"e": 2167,
"s": 2148,
"text": "Unix - Quick Guide"
},
{
"code": null,
"e": 2192,
"s": 2167,
"text": "Unix - Builtin Functions"
},
{
"code": null,
"e": 2212,
"s": 2192,
"text": "Unix - System Calls"
},
{
"code": null,
"e": 2233,
"s": 2212,
"text": "Unix - Commands List"
},
{
"code": null,
"e": 2255,
"s": 2233,
"text": "Unix Useful Resources"
},
{
"code": null,
"e": 2273,
"s": 2255,
"text": "Computer Glossary"
},
{
"code": null,
"e": 2284,
"s": 2273,
"text": "Who is Who"
},
{
"code": null,
"e": 2319,
"s": 2284,
"text": "Copyright © 2014 by tutorialspoint"
},
{
"code": null,
"e": 2507,
"s": 2319,
"text": "#include <signal.h> \n\nint sigwaitinfo(const sigset_t *set, siginfo_t *info); \n\nint sigtimedwait(const sigset_t *set, siginfo_t *info, \n const struct timespec *timeout); \n"
},
{
"code": null,
"e": 2565,
"s": 2507,
"text": "\nint sigwaitinfo(const sigset_t *set, siginfo_t *info); \n"
},
{
"code": null,
"e": 2675,
"s": 2565,
"text": "\nint sigtimedwait(const sigset_t *set, siginfo_t *info, \n const struct timespec *timeout); \n"
},
{
"code": null,
"e": 2965,
"s": 2675,
"text": "\nsigwaitinfo() removes the delivered signal from the calling process’s list of pending\nsignals and returns the signal number as its function result.\nIf the\ninfo argument is not NULL,\nthen it returns a structure of type\nsiginfo_t (see\nsigaction(2))\ncontaining information about the signal.\n"
},
{
"code": null,
"e": 3071,
"s": 2965,
"text": "\nSignals returned via\nsigwaitinfo() are delivered in the usual order; see\nsignal(7)\nfor further details.\n"
},
{
"code": null,
"e": 3320,
"s": 3071,
"text": "\nsigtimedwait() operates in exactly the same way as\nsigwaitinfo() except that it has an additional argument,\ntimeout, which enables an upper bound to be placed on the time for which\nthe process is suspended.\nThis argument is of the following type:\n"
},
{
"code": null,
"e": 3432,
"s": 3323,
"text": "struct timespec {\n long tv_sec; /* seconds */\n long tv_nsec; /* nanoseconds */\n}\n"
},
{
"code": null,
"e": 3676,
"s": 3432,
"text": "\nIf both fields of this structure are specified as 0, a poll is performed:\nsigtimedwait() returns immediately, either with information about a signal that\nwas pending for the caller, or with an error\nif none of the signals in\nset was pending.\n"
},
{
"code": null,
"e": 3903,
"s": 3676,
"text": "\nPOSIX leaves the meaning of a NULL value for the\ntimeout argument of\nsigtimedwait() unspecified, permitting the possibility that this has the same meaning\nas a call to\nsigwaitinfo(), and indeed this is what is done on Linux.\n"
},
{
"code": null,
"e": 3912,
"s": 3903,
"text": "kill (2)"
},
{
"code": null,
"e": 3921,
"s": 3912,
"text": "kill (2)"
},
{
"code": null,
"e": 3935,
"s": 3921,
"text": "sigaction (2)"
},
{
"code": null,
"e": 3949,
"s": 3935,
"text": "sigaction (2)"
},
{
"code": null,
"e": 3960,
"s": 3949,
"text": "signal (2)"
},
{
"code": null,
"e": 3971,
"s": 3960,
"text": "signal (2)"
},
{
"code": null,
"e": 3986,
"s": 3971,
"text": "sigpending (2)"
},
{
"code": null,
"e": 4001,
"s": 3986,
"text": "sigpending (2)"
},
{
"code": null,
"e": 4017,
"s": 4001,
"text": "sigprocmask (2)"
},
{
"code": null,
"e": 4033,
"s": 4017,
"text": "sigprocmask (2)"
},
{
"code": null,
"e": 4046,
"s": 4033,
"text": "sigqueue (2)"
},
{
"code": null,
"e": 4059,
"s": 4046,
"text": "sigqueue (2)"
},
{
"code": null,
"e": 4076,
"s": 4059,
"text": "\nAdvertisements\n"
},
{
"code": null,
"e": 4111,
"s": 4076,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 4139,
"s": 4111,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4173,
"s": 4139,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4190,
"s": 4173,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4223,
"s": 4190,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4234,
"s": 4223,
"text": " Pradeep D"
},
{
"code": null,
"e": 4269,
"s": 4234,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4285,
"s": 4269,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 4318,
"s": 4285,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4330,
"s": 4318,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 4362,
"s": 4330,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4370,
"s": 4362,
"text": " Uplatz"
},
{
"code": null,
"e": 4377,
"s": 4370,
"text": " Print"
},
{
"code": null,
"e": 4388,
"s": 4377,
"text": " Add Notes"
}
] |
Make your Own Book and Movie Recommender System using Surprise | by Maha Amami | Towards Data Science
|
I spent my Ph.D. years building recommender systems and benchmarking them all from scratch and it is only when I finished it that I heard about the sikit library Surprise.
It was a Surprise that I wished to know before. It would be spare me time and effort in implementing many recommender system baselines.
So I want to share information about this library here and give some code on how to use it as it may help one of the readers. Let’s dive in!
Surprise (stands for Simple Python RecommendatIon System Engine) is a Python library for building and analyzing recommender systems that deal with explicit rating data. It provides various ready-to-use prediction algorithms such as baseline algorithms, neighborhood methods, matrix factorization-based ( SVD, PMF, SVD++, NMF), and many others. Also, various similarity measures (cosine, MSD, Pearson...) are built-in. Source: http://surpriselib.com/
I will use Surprise on two different datasets:
To build a movie recommender system.To build a book recommender system.
To build a movie recommender system.
To build a book recommender system.
In both, I will use collaborative filtering techniques and content-based techniques to filter items, and no worries I will explain the differences between them.
pip install surprise
I use here the MovieLens dataset. It contains 25 million users ratings. the data are in the ./data/raw folder. We could load directly the .csv file with a built-in Surprise function, but it’s more convenient to load it through a Pandas data frame for later flexibility purposes.
I use only a subset of this dataset for complexity matters but you can use it all. Then, I upload the ratings to a Surprise Dataset object which contains the following fields in this order:
userIdmovieIdThe corresponding rating (usually on a scale such as 1–5)
userId
movieId
The corresponding rating (usually on a scale such as 1–5)
Collaborative filtering methods rely on the preferences of the user as well as those of other users in the system. The idea is that if two users are like-minded (agreed in the past on some preferences of items), relevant items to one user are recommended to the other user and vice versa. They derive recommendations only from the user-item rating matrix. Source: my PhD thesis report
Surprise implements a handful of algorithms that are collaborative such as SVD, NMF, etc.
0it [00:00, ?it/s]RMSE: 0.9265RMSE: 1.0959Computing the msd similarity matrix...Done computing similarity matrix.1it [00:12, 12.72s/it]RMSE: 0.9919RMSE: 0.9299RMSE: 1.1025Computing the msd similarity matrix...Done computing similarity matrix.2it [00:26, 13.54s/it]RMSE: 0.9915RMSE: 0.9270RMSE: 1.0996Computing the msd similarity matrix...Done computing similarity matrix.3it [00:42, 14.14s/it]RMSE: 0.9905
Content-based filtering methods analyze a set of features of items relevant to the user and learn a user profile based on these features. The filtering process basically consists in matching up the features of the user profile against the features of an item content (i.e., item profile). Source: my PhD thesis report
So, here I will rely directly on items attributes i.e. the movie title. First, I have to describe a user profile with an attributes vector. Then I will use these vectors to generate recommendations based on similarity measures.
Most of the content-based filtering methods are based on heuristic models which represent users and items as vectors of TF-IDF (or BM25) in a Vector Space Model.
I used TF-IDF in this code which considers terms that occur frequently in one document (TF =term-frequency), but rarely in the rest of the corpus (IDF = inverse-document-frequency).
Since items and user profiles are represented as vectors of TF-IDF, items arerecommended in decreasing order of similarity with the user (the user profiles are represented in the same form of the items). The most common measure is the cosine similarity which I m gonna use below to calculate the similarity between both profiles.
Suppose a user wants the 10 most ‘similar’ movies from the movie ‘Scientology and the Prison of Belief (2015)’.
Recommending 10 products similar to Going Clear: Scientology and the Prison of Belief (2015)...------- Recommended: Soulless 2 (2015) (score:0.09111541613391295) Recommended: Víkend (2015) (score:0.09111541613391295) Recommended: No Longer Heroine (2015) (score:0.06179864475000222) Recommended: In the Shadow of Women (2015) (score:0.06179864475000222) Recommended: Marco Polo: One Hundred Eyes (2015) (score:0.05026525144746273) Recommended: Ugly American, The (1963) (score:0.0) Recommended: Snitch Cartel, The (El cartel de los sapos) (2011) (score:0.0) Recommended: Drone (2014) (score:0.0) Recommended: Kenny Rogers as The Gambler (1980) (score:0.0) Recommended: Le Rossignol (2005) (score:0.0)
This is gonna be a similar code to the above but by applying it to a different dataset.
I used the goodbooks-10k dataset available on Kaggle. It contains ratings and books csv files. The first one contains rating data for 10,000 books rated by over 53,000 users. The second file contains the metadata of the 10,000 books (title, author, ISBN, etc.).
I shared the book and movie recommender systems via Github.
That’s it! You can apply this recommender system code template to any data you want. I will also share in the next few days about contextual recommender systems and how to implement one.
So, stay tuned!
|
[
{
"code": null,
"e": 343,
"s": 171,
"text": "I spent my Ph.D. years building recommender systems and benchmarking them all from scratch and it is only when I finished it that I heard about the sikit library Surprise."
},
{
"code": null,
"e": 479,
"s": 343,
"text": "It was a Surprise that I wished to know before. It would be spare me time and effort in implementing many recommender system baselines."
},
{
"code": null,
"e": 620,
"s": 479,
"text": "So I want to share information about this library here and give some code on how to use it as it may help one of the readers. Let’s dive in!"
},
{
"code": null,
"e": 1070,
"s": 620,
"text": "Surprise (stands for Simple Python RecommendatIon System Engine) is a Python library for building and analyzing recommender systems that deal with explicit rating data. It provides various ready-to-use prediction algorithms such as baseline algorithms, neighborhood methods, matrix factorization-based ( SVD, PMF, SVD++, NMF), and many others. Also, various similarity measures (cosine, MSD, Pearson...) are built-in. Source: http://surpriselib.com/"
},
{
"code": null,
"e": 1117,
"s": 1070,
"text": "I will use Surprise on two different datasets:"
},
{
"code": null,
"e": 1189,
"s": 1117,
"text": "To build a movie recommender system.To build a book recommender system."
},
{
"code": null,
"e": 1226,
"s": 1189,
"text": "To build a movie recommender system."
},
{
"code": null,
"e": 1262,
"s": 1226,
"text": "To build a book recommender system."
},
{
"code": null,
"e": 1423,
"s": 1262,
"text": "In both, I will use collaborative filtering techniques and content-based techniques to filter items, and no worries I will explain the differences between them."
},
{
"code": null,
"e": 1444,
"s": 1423,
"text": "pip install surprise"
},
{
"code": null,
"e": 1723,
"s": 1444,
"text": "I use here the MovieLens dataset. It contains 25 million users ratings. the data are in the ./data/raw folder. We could load directly the .csv file with a built-in Surprise function, but it’s more convenient to load it through a Pandas data frame for later flexibility purposes."
},
{
"code": null,
"e": 1913,
"s": 1723,
"text": "I use only a subset of this dataset for complexity matters but you can use it all. Then, I upload the ratings to a Surprise Dataset object which contains the following fields in this order:"
},
{
"code": null,
"e": 1984,
"s": 1913,
"text": "userIdmovieIdThe corresponding rating (usually on a scale such as 1–5)"
},
{
"code": null,
"e": 1991,
"s": 1984,
"text": "userId"
},
{
"code": null,
"e": 1999,
"s": 1991,
"text": "movieId"
},
{
"code": null,
"e": 2057,
"s": 1999,
"text": "The corresponding rating (usually on a scale such as 1–5)"
},
{
"code": null,
"e": 2442,
"s": 2057,
"text": "Collaborative filtering methods rely on the preferences of the user as well as those of other users in the system. The idea is that if two users are like-minded (agreed in the past on some preferences of items), relevant items to one user are recommended to the other user and vice versa. They derive recommendations only from the user-item rating matrix. Source: my PhD thesis report"
},
{
"code": null,
"e": 2532,
"s": 2442,
"text": "Surprise implements a handful of algorithms that are collaborative such as SVD, NMF, etc."
},
{
"code": null,
"e": 2938,
"s": 2532,
"text": "0it [00:00, ?it/s]RMSE: 0.9265RMSE: 1.0959Computing the msd similarity matrix...Done computing similarity matrix.1it [00:12, 12.72s/it]RMSE: 0.9919RMSE: 0.9299RMSE: 1.1025Computing the msd similarity matrix...Done computing similarity matrix.2it [00:26, 13.54s/it]RMSE: 0.9915RMSE: 0.9270RMSE: 1.0996Computing the msd similarity matrix...Done computing similarity matrix.3it [00:42, 14.14s/it]RMSE: 0.9905"
},
{
"code": null,
"e": 3256,
"s": 2938,
"text": "Content-based filtering methods analyze a set of features of items relevant to the user and learn a user profile based on these features. The filtering process basically consists in matching up the features of the user profile against the features of an item content (i.e., item profile). Source: my PhD thesis report"
},
{
"code": null,
"e": 3484,
"s": 3256,
"text": "So, here I will rely directly on items attributes i.e. the movie title. First, I have to describe a user profile with an attributes vector. Then I will use these vectors to generate recommendations based on similarity measures."
},
{
"code": null,
"e": 3646,
"s": 3484,
"text": "Most of the content-based filtering methods are based on heuristic models which represent users and items as vectors of TF-IDF (or BM25) in a Vector Space Model."
},
{
"code": null,
"e": 3828,
"s": 3646,
"text": "I used TF-IDF in this code which considers terms that occur frequently in one document (TF =term-frequency), but rarely in the rest of the corpus (IDF = inverse-document-frequency)."
},
{
"code": null,
"e": 4158,
"s": 3828,
"text": "Since items and user profiles are represented as vectors of TF-IDF, items arerecommended in decreasing order of similarity with the user (the user profiles are represented in the same form of the items). The most common measure is the cosine similarity which I m gonna use below to calculate the similarity between both profiles."
},
{
"code": null,
"e": 4270,
"s": 4158,
"text": "Suppose a user wants the 10 most ‘similar’ movies from the movie ‘Scientology and the Prison of Belief (2015)’."
},
{
"code": null,
"e": 4972,
"s": 4270,
"text": "Recommending 10 products similar to Going Clear: Scientology and the Prison of Belief (2015)...-------\tRecommended: Soulless 2 (2015) (score:0.09111541613391295)\tRecommended: Víkend (2015) (score:0.09111541613391295)\tRecommended: No Longer Heroine (2015) (score:0.06179864475000222)\tRecommended: In the Shadow of Women (2015) (score:0.06179864475000222)\tRecommended: Marco Polo: One Hundred Eyes (2015) (score:0.05026525144746273)\tRecommended: Ugly American, The (1963) (score:0.0)\tRecommended: Snitch Cartel, The (El cartel de los sapos) (2011) (score:0.0)\tRecommended: Drone (2014) (score:0.0)\tRecommended: Kenny Rogers as The Gambler (1980) (score:0.0)\tRecommended: Le Rossignol (2005) (score:0.0)"
},
{
"code": null,
"e": 5060,
"s": 4972,
"text": "This is gonna be a similar code to the above but by applying it to a different dataset."
},
{
"code": null,
"e": 5322,
"s": 5060,
"text": "I used the goodbooks-10k dataset available on Kaggle. It contains ratings and books csv files. The first one contains rating data for 10,000 books rated by over 53,000 users. The second file contains the metadata of the 10,000 books (title, author, ISBN, etc.)."
},
{
"code": null,
"e": 5382,
"s": 5322,
"text": "I shared the book and movie recommender systems via Github."
},
{
"code": null,
"e": 5569,
"s": 5382,
"text": "That’s it! You can apply this recommender system code template to any data you want. I will also share in the next few days about contextual recommender systems and how to implement one."
}
] |
bzip2 command in Linux with Examples - GeeksforGeeks
|
22 Aug, 2019
bzip2 command in Linux is used to compress and decompress the files i.e. it helps in binding the files into a single file which takes less storage space as the original file use to take. It has a slower decompression time and higher memory use. It uses Burrows-Wheeler block sorting text compression algorithm, and Huffman Coding. Each file is replaced by a compressed version of itself, with the name original name of the file followed by extension bz2.
Syntax:
bzip2 [OPTIONS] filenames ...
Options:
-z : This option forces compression. It is an opposite command of decompression i.e. -d Option.$ bzip2 -z input.txtExample:Note: This option deletes the original file also.
$ bzip2 -z input.txt
Example:
Note: This option deletes the original file also.
-k: This option does compression but does not deletes the original file.$ bzip2 -k input.txtExample:
$ bzip2 -k input.txt
Example:
-d : This option is used for decompression of compressed files.$ bzip2 -d input.txt.bz2Example:
$ bzip2 -d input.txt.bz2
Example:
-t : This option does the integrity check of the file and does not decompresses the file. It gives us the idea that the file is corrupt or not.$ bzip2 -t input.txt.bz2Example:
$ bzip2 -t input.txt.bz2
Example:
-v : Verbose mode show the compression ratio for each file processed. It also increases the verbosity level, spewing out lots of information which is primarily of interest for diagnostic purposes.$ bzip2 -v input.txtExample:
$ bzip2 -v input.txt
Example:
-h –help : To display the help message and exit.
-L –license -V –version : It is used to display the software version, license terms, and conditions.
-q –quiet : It will suppress non-essential warning messages. Messages pertaining to I/O errors and other critical events will not be suppressed.
-f –force : It will force overwrite of output files.
Akanksha_Rai
linux-command
Linux-file-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
nohup Command in Linux with Examples
scp command in Linux with Examples
Thread functions in C/C++
mv command in Linux with examples
SED command in Linux | Set 2
chown command in Linux with Examples
Docker - COPY Instruction
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
nslookup command in Linux with Examples
|
[
{
"code": null,
"e": 24431,
"s": 24403,
"text": "\n22 Aug, 2019"
},
{
"code": null,
"e": 24886,
"s": 24431,
"text": "bzip2 command in Linux is used to compress and decompress the files i.e. it helps in binding the files into a single file which takes less storage space as the original file use to take. It has a slower decompression time and higher memory use. It uses Burrows-Wheeler block sorting text compression algorithm, and Huffman Coding. Each file is replaced by a compressed version of itself, with the name original name of the file followed by extension bz2."
},
{
"code": null,
"e": 24894,
"s": 24886,
"text": "Syntax:"
},
{
"code": null,
"e": 24924,
"s": 24894,
"text": "bzip2 [OPTIONS] filenames ..."
},
{
"code": null,
"e": 24933,
"s": 24924,
"text": "Options:"
},
{
"code": null,
"e": 25106,
"s": 24933,
"text": "-z : This option forces compression. It is an opposite command of decompression i.e. -d Option.$ bzip2 -z input.txtExample:Note: This option deletes the original file also."
},
{
"code": null,
"e": 25127,
"s": 25106,
"text": "$ bzip2 -z input.txt"
},
{
"code": null,
"e": 25136,
"s": 25127,
"text": "Example:"
},
{
"code": null,
"e": 25186,
"s": 25136,
"text": "Note: This option deletes the original file also."
},
{
"code": null,
"e": 25287,
"s": 25186,
"text": "-k: This option does compression but does not deletes the original file.$ bzip2 -k input.txtExample:"
},
{
"code": null,
"e": 25308,
"s": 25287,
"text": "$ bzip2 -k input.txt"
},
{
"code": null,
"e": 25317,
"s": 25308,
"text": "Example:"
},
{
"code": null,
"e": 25413,
"s": 25317,
"text": "-d : This option is used for decompression of compressed files.$ bzip2 -d input.txt.bz2Example:"
},
{
"code": null,
"e": 25438,
"s": 25413,
"text": "$ bzip2 -d input.txt.bz2"
},
{
"code": null,
"e": 25447,
"s": 25438,
"text": "Example:"
},
{
"code": null,
"e": 25623,
"s": 25447,
"text": "-t : This option does the integrity check of the file and does not decompresses the file. It gives us the idea that the file is corrupt or not.$ bzip2 -t input.txt.bz2Example:"
},
{
"code": null,
"e": 25648,
"s": 25623,
"text": "$ bzip2 -t input.txt.bz2"
},
{
"code": null,
"e": 25657,
"s": 25648,
"text": "Example:"
},
{
"code": null,
"e": 25882,
"s": 25657,
"text": "-v : Verbose mode show the compression ratio for each file processed. It also increases the verbosity level, spewing out lots of information which is primarily of interest for diagnostic purposes.$ bzip2 -v input.txtExample:"
},
{
"code": null,
"e": 25903,
"s": 25882,
"text": "$ bzip2 -v input.txt"
},
{
"code": null,
"e": 25912,
"s": 25903,
"text": "Example:"
},
{
"code": null,
"e": 25961,
"s": 25912,
"text": "-h –help : To display the help message and exit."
},
{
"code": null,
"e": 26062,
"s": 25961,
"text": "-L –license -V –version : It is used to display the software version, license terms, and conditions."
},
{
"code": null,
"e": 26207,
"s": 26062,
"text": "-q –quiet : It will suppress non-essential warning messages. Messages pertaining to I/O errors and other critical events will not be suppressed."
},
{
"code": null,
"e": 26260,
"s": 26207,
"text": "-f –force : It will force overwrite of output files."
},
{
"code": null,
"e": 26273,
"s": 26260,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 26287,
"s": 26273,
"text": "linux-command"
},
{
"code": null,
"e": 26307,
"s": 26287,
"text": "Linux-file-commands"
},
{
"code": null,
"e": 26314,
"s": 26307,
"text": "Picked"
},
{
"code": null,
"e": 26325,
"s": 26314,
"text": "Linux-Unix"
},
{
"code": null,
"e": 26423,
"s": 26325,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26460,
"s": 26423,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 26495,
"s": 26460,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 26521,
"s": 26495,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 26555,
"s": 26521,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 26584,
"s": 26555,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 26621,
"s": 26584,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 26647,
"s": 26621,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 26687,
"s": 26647,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 26722,
"s": 26687,
"text": "Basic Operators in Shell Scripting"
}
] |
Longest Span in two Binary Arrays | Practice | GeeksforGeeks
|
Given two binary arrays arr1[] and arr2[] of same size N. Find length of the longest common span [i, j] where j>=i such that arr1[i] + arr1[i+1] + .... + arr1[j] = arr2[i] + arr2[i+1] + .... + arr2[j].
Example 1:
Input:
N = 6
Arr1[] = {0, 1, 0, 0, 0, 0}
Arr2[] = {1, 0, 1, 0, 0, 1}
Output: 4
Explanation: The longest span with same
sum is from index 1 to 4 following zero
based indexing.
Your Task:
You don't need to read input or print anything. Complete the function longestCommonSum() which takes two arrays arr1, arr2 and integer n as input parameters and returns the length of the longest common span.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)
Constraints:
1 <= N <= 105
0 <= Arr1[i], Arr2[i] <= 1
0
premranjan88046
This comment was deleted.
+1
sivasret2 weeks ago
Arr1[] = {0, 1, 0, 0, 0, 0}
Arr2[] = {1, 0, 1, 0, 0, 1}
How the longest span for above two arrays is 4 . It should be 2 right ?
0
anirbanhaldar6002 weeks ago
Easy Solution C++ → Time : O(n) , Space : O(1)#
>> First find difference (arr1 - arr2) between two arrays (the new array will have -1 or 0 or 1).
>> Now solve the problem as, “Subarray sum 0”
>> Remember to store the indices as they will help to calculate subarray size.
int longestCommonSum(bool arr1[], bool arr2[], int n) {
int a[n];
for(int i = 0; i < n; i++) a[i] = (int) arr1[i] - (int) arr2[i];
unordered_map<int, int> m;
int dist = 0 + !a[0];
m.insert({a[0], 0});
for(int i = 1; i < n; i++){
a[i] += a[i-1];
if(a[i] == 0){
if(dist < i+1) dist = i+1;
}
else if(m.find(a[i]) != m.end()){
int x = m.find(a[i]) -> second;
if(dist < i-x) dist = i - x;
}
else m.insert({a[i], i});
}
return dist;
}
#Space complexity : As they have given Boolean array instead of binary array, so I am forced to take an integer array to store “-1”, So space complexity for this particular problem is O(n) otherwise if they have given proper integer array, then the algorithm could be implemented inplace and the space would be O(1).
0
harshpandeyalfa23 weeks ago
C++
(0.7sec)
int longestCommonSum(bool arr1[], bool arr2[], int n) { int arr[n]; for(int i=0;i<n;i++) arr[i]=arr1[i]-arr2[i]; int ps=0; int res=0; unordered_map<int,int> s; for(int i=0;i<n;i++) { ps+=arr[i]; if(ps==0) res=i+1; else if(s.find(ps)==s.end()) s.insert({ps,i}); else if(s.find(ps)!=s.end()) res=max(res,i-s[ps]); } return res; }
0
shreyansh28124 months ago
Is it not efficient if we use map to solve this problem?
I have done it like this...
int longestCommonSum(bool arr1[], bool arr2[], int n) { unordered_map<int,int> m; int sum = 0; int result = 0; for(int i = 0; i < n; i++) { int diff = arr1[i]-arr2[i]; sum += diff; if(sum == 0) { result = max(result,i+1); } if(m.find(sum) != m.end()) { result = max(result, i - m[sum]); }
else { m[sum] = i; } } return result; }
+1
badgujarsachin834 months ago
int longestCommonSum(bool arr1[], bool arr2[], int n) {
// code here
int v[n];
for(int i=0;i<n;i++){
v[i]=arr1[i]-arr2[i];
}
int maxi=0,sum=0;
unordered_map<int,int> mp;
for(int i=0;i<n;i++){
sum+=v[i];
if(sum==0){
maxi=i+1;
}
if(mp.find(sum)!=mp.end()){
maxi=max(maxi,i-mp[sum]);
}else{
mp[sum]=i;
}
}
return maxi;
}
0
abhishekpanwar6976 months ago
first find the difference of both arrays than find the longest subarray with sum 0 or equal number of zeros and one's
int longestCommonSum(bool a[], bool b[], int n) { int v[n]; for(int i=0;i<n;i++) { v[i]=a[i]-b[i]; } int maxi=0,sum=0; unordered_map<int,int>mp; for(int i=0;i<n;i++) { sum+=v[i]; if(sum==0) maxi=i+1; if(mp.find(sum)!=mp.end()) maxi=max(maxi,i-mp[sum]); else mp[sum]=i; } return maxi; }
0
prashantsketch7 months ago
class Solution:
def longestCommonSum(self, arr1, arr2, n):
# code here
max_len=0
sum1=0
sum2=0
diff={}
for i in range(n):
sum1+=arr1[i]
sum2+=arr2[i]
current_diff=sum1-sum2
if current_diff==0:
max_len=i+1
elif current_diff not in diff:
diff[current_diff]=i
else:
length=i-diff[current_diff]
max_len=max(max_len,length)
return max_len
0
akjha4987 months ago
O(N),O(N)
int longestCommonSum(bool arr1[], bool arr2[], int n) { // code here int temp[n]; for(int i=0;i<n;i++){ temp[i]=arr1[i]-arr2[i]; } int pre_sum=0,res=0; unordered_map<int,int> m; for(int i=0;i<n;i++){ pre_sum+=temp[i]; if(pre_sum==0){ res=i+1; } if(m.find(pre_sum)==m.end()){ m[pre_sum]=i; } if(m.find(pre_sum)!=m.end()){ res=max(res,i-m[pre_sum]); } } return res; }
0
Manasvin_Sharma1 year ago
Manasvin_Sharma
C++ 0.01 Solution
#include<bits stdc++.h="">using namespace std;
int main(){ios_base::sync_with_stdio(false); cin.tie(NULL);
int queries;cin>>queries;while(queries--){int n;cin>>n;
int arr1[n],arr2[n],temp[n],sum=0,count=0,temp_count;
for(int i=0;i<n;i++) cin="">>arr1[i];
for(int i=0;i<n;i++) cin="">>arr2[i];
for(int i=0;i<n;i++) temp[i]="arr1[i]-arr2[i];" for(int="" size="1;size<=n;size++)" {="" temp_count="0;sum=0;" for(int="" i="0;i<size;i++)" {="" sum+="temp[i];" temp_count++;="" }="" if(sum="=0)" count="max(count,temp_count);" for(int="" i="size;i<n;i++)" {="" sum="sum+temp[i]-temp[i-size];" if(sum="=0)" count="max(count,temp_count);" }="" }="" cout<<count<<"\n";="" }="" return="" 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": 429,
"s": 226,
"text": "Given two binary arrays arr1[] and arr2[] of same size N. Find length of the longest common span [i, j] where j>=i such that arr1[i] + arr1[i+1] + .... + arr1[j] = arr2[i] + arr2[i+1] + .... + arr2[j]. "
},
{
"code": null,
"e": 442,
"s": 431,
"text": "Example 1:"
},
{
"code": null,
"e": 619,
"s": 442,
"text": "Input:\nN = 6\nArr1[] = {0, 1, 0, 0, 0, 0}\nArr2[] = {1, 0, 1, 0, 0, 1}\nOutput: 4\nExplanation: The longest span with same\nsum is from index 1 to 4 following zero \nbased indexing.\n"
},
{
"code": null,
"e": 840,
"s": 621,
"text": "Your Task:\nYou don't need to read input or print anything. Complete the function longestCommonSum() which takes two arrays arr1, arr2 and integer n as input parameters and returns the length of the longest common span."
},
{
"code": null,
"e": 904,
"s": 842,
"text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)"
},
{
"code": null,
"e": 960,
"s": 906,
"text": "Constraints:\n1 <= N <= 105\n0 <= Arr1[i], Arr2[i] <= 1"
},
{
"code": null,
"e": 962,
"s": 960,
"text": "0"
},
{
"code": null,
"e": 978,
"s": 962,
"text": "premranjan88046"
},
{
"code": null,
"e": 1004,
"s": 978,
"text": "This comment was deleted."
},
{
"code": null,
"e": 1007,
"s": 1004,
"text": "+1"
},
{
"code": null,
"e": 1027,
"s": 1007,
"text": "sivasret2 weeks ago"
},
{
"code": null,
"e": 1083,
"s": 1027,
"text": "Arr1[] = {0, 1, 0, 0, 0, 0}\nArr2[] = {1, 0, 1, 0, 0, 1}"
},
{
"code": null,
"e": 1157,
"s": 1085,
"text": "How the longest span for above two arrays is 4 . It should be 2 right ?"
},
{
"code": null,
"e": 1159,
"s": 1157,
"text": "0"
},
{
"code": null,
"e": 1187,
"s": 1159,
"text": "anirbanhaldar6002 weeks ago"
},
{
"code": null,
"e": 1235,
"s": 1187,
"text": "Easy Solution C++ → Time : O(n) , Space : O(1)#"
},
{
"code": null,
"e": 1333,
"s": 1235,
"text": ">> First find difference (arr1 - arr2) between two arrays (the new array will have -1 or 0 or 1)."
},
{
"code": null,
"e": 1379,
"s": 1333,
"text": ">> Now solve the problem as, “Subarray sum 0”"
},
{
"code": null,
"e": 1458,
"s": 1379,
"text": ">> Remember to store the indices as they will help to calculate subarray size."
},
{
"code": null,
"e": 2003,
"s": 1458,
"text": "int longestCommonSum(bool arr1[], bool arr2[], int n) {\n int a[n];\n for(int i = 0; i < n; i++) a[i] = (int) arr1[i] - (int) arr2[i];\n unordered_map<int, int> m;\n int dist = 0 + !a[0];\n m.insert({a[0], 0});\n for(int i = 1; i < n; i++){\n a[i] += a[i-1];\n if(a[i] == 0){\n if(dist < i+1) dist = i+1;\n }\n else if(m.find(a[i]) != m.end()){\n int x = m.find(a[i]) -> second;\n if(dist < i-x) dist = i - x;\n }\n else m.insert({a[i], i});\n }\n return dist;\n}"
},
{
"code": null,
"e": 2320,
"s": 2003,
"text": "#Space complexity : As they have given Boolean array instead of binary array, so I am forced to take an integer array to store “-1”, So space complexity for this particular problem is O(n) otherwise if they have given proper integer array, then the algorithm could be implemented inplace and the space would be O(1)."
},
{
"code": null,
"e": 2322,
"s": 2320,
"text": "0"
},
{
"code": null,
"e": 2350,
"s": 2322,
"text": "harshpandeyalfa23 weeks ago"
},
{
"code": null,
"e": 2354,
"s": 2350,
"text": "C++"
},
{
"code": null,
"e": 2363,
"s": 2354,
"text": "(0.7sec)"
},
{
"code": null,
"e": 2836,
"s": 2363,
"text": "int longestCommonSum(bool arr1[], bool arr2[], int n) { int arr[n]; for(int i=0;i<n;i++) arr[i]=arr1[i]-arr2[i]; int ps=0; int res=0; unordered_map<int,int> s; for(int i=0;i<n;i++) { ps+=arr[i]; if(ps==0) res=i+1; else if(s.find(ps)==s.end()) s.insert({ps,i}); else if(s.find(ps)!=s.end()) res=max(res,i-s[ps]); } return res; }"
},
{
"code": null,
"e": 2838,
"s": 2836,
"text": "0"
},
{
"code": null,
"e": 2864,
"s": 2838,
"text": "shreyansh28124 months ago"
},
{
"code": null,
"e": 2921,
"s": 2864,
"text": "Is it not efficient if we use map to solve this problem?"
},
{
"code": null,
"e": 2951,
"s": 2923,
"text": "I have done it like this..."
},
{
"code": null,
"e": 3417,
"s": 2953,
"text": " int longestCommonSum(bool arr1[], bool arr2[], int n) { unordered_map<int,int> m; int sum = 0; int result = 0; for(int i = 0; i < n; i++) { int diff = arr1[i]-arr2[i]; sum += diff; if(sum == 0) { result = max(result,i+1); } if(m.find(sum) != m.end()) { result = max(result, i - m[sum]); }"
},
{
"code": null,
"e": 3523,
"s": 3417,
"text": " else { m[sum] = i; } } return result; }"
},
{
"code": null,
"e": 3532,
"s": 3529,
"text": "+1"
},
{
"code": null,
"e": 3561,
"s": 3532,
"text": "badgujarsachin834 months ago"
},
{
"code": null,
"e": 4165,
"s": 3561,
"text": " int longestCommonSum(bool arr1[], bool arr2[], int n) {\n // code here \n int v[n];\n for(int i=0;i<n;i++){\n v[i]=arr1[i]-arr2[i];\n }\n int maxi=0,sum=0;\n unordered_map<int,int> mp;\n for(int i=0;i<n;i++){\n sum+=v[i];\n if(sum==0){\n maxi=i+1;\n }\n if(mp.find(sum)!=mp.end()){\n maxi=max(maxi,i-mp[sum]);\n }else{\n mp[sum]=i;\n }\n }\n return maxi;\n }"
},
{
"code": null,
"e": 4167,
"s": 4165,
"text": "0"
},
{
"code": null,
"e": 4197,
"s": 4167,
"text": "abhishekpanwar6976 months ago"
},
{
"code": null,
"e": 4315,
"s": 4197,
"text": "first find the difference of both arrays than find the longest subarray with sum 0 or equal number of zeros and one's"
},
{
"code": null,
"e": 4745,
"s": 4317,
"text": "int longestCommonSum(bool a[], bool b[], int n) { int v[n]; for(int i=0;i<n;i++) { v[i]=a[i]-b[i]; } int maxi=0,sum=0; unordered_map<int,int>mp; for(int i=0;i<n;i++) { sum+=v[i]; if(sum==0) maxi=i+1; if(mp.find(sum)!=mp.end()) maxi=max(maxi,i-mp[sum]); else mp[sum]=i; } return maxi; }"
},
{
"code": null,
"e": 4747,
"s": 4745,
"text": "0"
},
{
"code": null,
"e": 4774,
"s": 4747,
"text": "prashantsketch7 months ago"
},
{
"code": null,
"e": 5201,
"s": 4774,
"text": "class Solution:\n\tdef longestCommonSum(self, arr1, arr2, n): \n\t\t# code here \n\t\tmax_len=0\n\t\tsum1=0\n\t\tsum2=0\n\t\tdiff={}\n\t\tfor i in range(n):\n\t\t sum1+=arr1[i]\n\t\t sum2+=arr2[i]\n\t\t current_diff=sum1-sum2\n\t\t if current_diff==0:\n\t\t max_len=i+1\n\t\t elif current_diff not in diff:\n\t\t diff[current_diff]=i\n\t\t else:\n\t\t length=i-diff[current_diff]\n\t\t max_len=max(max_len,length)\n\t\treturn max_len"
},
{
"code": null,
"e": 5203,
"s": 5201,
"text": "0"
},
{
"code": null,
"e": 5224,
"s": 5203,
"text": "akjha4987 months ago"
},
{
"code": null,
"e": 5234,
"s": 5224,
"text": "O(N),O(N)"
},
{
"code": null,
"e": 5858,
"s": 5234,
"text": "int longestCommonSum(bool arr1[], bool arr2[], int n) { // code here int temp[n]; for(int i=0;i<n;i++){ temp[i]=arr1[i]-arr2[i]; } int pre_sum=0,res=0; unordered_map<int,int> m; for(int i=0;i<n;i++){ pre_sum+=temp[i]; if(pre_sum==0){ res=i+1; } if(m.find(pre_sum)==m.end()){ m[pre_sum]=i; } if(m.find(pre_sum)!=m.end()){ res=max(res,i-m[pre_sum]); } } return res; }"
},
{
"code": null,
"e": 5860,
"s": 5858,
"text": "0"
},
{
"code": null,
"e": 5886,
"s": 5860,
"text": "Manasvin_Sharma1 year ago"
},
{
"code": null,
"e": 5902,
"s": 5886,
"text": "Manasvin_Sharma"
},
{
"code": null,
"e": 5920,
"s": 5902,
"text": "C++ 0.01 Solution"
},
{
"code": null,
"e": 5967,
"s": 5920,
"text": "#include<bits stdc++.h=\"\">using namespace std;"
},
{
"code": null,
"e": 6030,
"s": 5967,
"text": "int main(){ios_base::sync_with_stdio(false); cin.tie(NULL);"
},
{
"code": null,
"e": 6086,
"s": 6030,
"text": "int queries;cin>>queries;while(queries--){int n;cin>>n;"
},
{
"code": null,
"e": 6140,
"s": 6086,
"text": "int arr1[n],arr2[n],temp[n],sum=0,count=0,temp_count;"
},
{
"code": null,
"e": 6178,
"s": 6140,
"text": "for(int i=0;i<n;i++) cin=\"\">>arr1[i];"
},
{
"code": null,
"e": 6216,
"s": 6178,
"text": "for(int i=0;i<n;i++) cin=\"\">>arr2[i];"
},
{
"code": null,
"e": 6621,
"s": 6216,
"text": "for(int i=0;i<n;i++) temp[i]=\"arr1[i]-arr2[i];\" for(int=\"\" size=\"1;size<=n;size++)\" {=\"\" temp_count=\"0;sum=0;\" for(int=\"\" i=\"0;i<size;i++)\" {=\"\" sum+=\"temp[i];\" temp_count++;=\"\" }=\"\" if(sum=\"=0)\" count=\"max(count,temp_count);\" for(int=\"\" i=\"size;i<n;i++)\" {=\"\" sum=\"sum+temp[i]-temp[i-size];\" if(sum=\"=0)\" count=\"max(count,temp_count);\" }=\"\" }=\"\" cout<<count<<\"\\n\";=\"\" }=\"\" return=\"\" 0;=\"\" }=\"\">"
},
{
"code": null,
"e": 6767,
"s": 6621,
"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": 6803,
"s": 6767,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6813,
"s": 6803,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6823,
"s": 6813,
"text": "\nContest\n"
},
{
"code": null,
"e": 6886,
"s": 6823,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7034,
"s": 6886,
"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": 7242,
"s": 7034,
"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": 7348,
"s": 7242,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Remove k corner elements to maximize remaining sum - GeeksforGeeks
|
31 Aug, 2021
Given an array, the task is to remove total k elements from corners to maximize the sum of remaining elements. For example, if we k = 5 and if we remove 2 elements from the left corner, then we need to remove 3 elements from the right corner.Examples:
Input : arr = [11, 49, 100, 20, 86, 29, 72], k = 4 Output : 206 Explanation :: We remove 29 and 72 from right corner. We also remove 11 and 49 from left corner to get the maximum sum as 206 for remaining elements.
Input : arr[] = [1, 2, 3, 4, 5, 6, 1], k = 3 Output : 18 Explanation :: We remove two elements from left corner (1 and 2) and one element from right corner (1).
Naive Approach : 1) Initialize result as negative infinity. 2) Compute total sum. 3) Run a loop for x = 1 to k .....Remove ‘x’ elements from left side and k – i elements from right side. .....If the remaining elements have sum more than the result, update the result.
Time Complexity: O(n * k)Efficient Approach (Using Window Sliding Technique) 1) Find the sum of first n-k elements and initialize this as a current sum and also initialize this as result. 2) Run a loop for i = n-k to n-1 ....curr_sum = curr_sum – arr[i – n + k] + arr[i] ....res = max(res, curr_sum)In step 2, we mainly run sliding window. We remove an element from left side and add an element from right side.
Below is the c++ implementation of the above problem statement.
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std;int calculate(int arr[], int n, int k){ // Calculate the sum of all elements // excluding the last k elements.. int curr_sum = 0; for (int i = 0; i < n - k; i++) curr_sum += arr[i]; // now here its time to use sliding window // concept, remove the first element from // the current window and add the new element // in it in order to get the sum of all n-k size // of elements in arr. // Calculate the minimum sum of elements of // size n-k and stored it into the result int res = curr_sum; for (int i = n - k; i < n; i++) { curr_sum = curr_sum - arr[i - n + k] + arr[i]; res = max(res, curr_sum); } // Now return result (sum of remaining n-k elements) return res;} // main functionint main(){ int arr[] = { 11, 49, 100, 20, 86, 29, 72 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 4; cout << "Maximum sum of remaining elements " << calculate(arr, n, k) << "\n"; return 0;}
// Java program for the// above approachimport java.util.*;class GFG{ static int calculate(int[] arr, int n, int k){ // Calculate the total // sum of all elements // present in the array.. int total_sum = 0; for (int i = 0; i < n; i++) total_sum += arr[i]; // Now calculate the sum // of all elements excluding // the last k elements.. int curr_sum = 0; for (int i = 0; i < n - k; i++) curr_sum += arr[i]; // Now here its time to use // sliding window concept, // remove the first element // from the current window // and add the new element // in it in order to get // the sum of all n-k size // of elements in arr. // Calculate the minimum // sum of elements of // size n-k and stored it // into the result int res = curr_sum; for (int i = n - k; i < n; i++) { curr_sum = curr_sum - arr[i - n + k] + arr[i]; res = Math.max(res, curr_sum); } // Now return result (sum of // remaining n-k elements) return res;} // Driver codepublic static void main(String[] args){ int[] arr = {11, 49, 100, 20, 86, 29, 72}; int n = arr.length; int k = 4; System.out.print("Maximum sum of remaining " + "elements " + calculate(arr, n, k) + "\n");}} // This code is contributed by Chitranayal
def calculate(arr, n, k): # calculate the total sum of all elements # present in the array.. total_sum = 0 for i in arr: total_sum += i # now calculate the sum of all elements # excluding the last k elements.. curr_sum = 0 for i in range(n - k): curr_sum += arr[i] # now here its time to use sliding window # concept, remove the first element from # the current window and add the new element # in it in order to get the sum of all n-k size # of elements in arr. # Calculate the minimum sum of elements of # size n-k and stored it into the result res = curr_sum for i in range(n - k, n): curr_sum = curr_sum - arr[i - n + k] + arr[i] res = max(res, curr_sum) # Now return result (sum of remaining n-k elements) return res # main functionif __name__ == '__main__': arr=[11, 49, 100, 20, 86, 29, 72] n = len(arr) k = 4 print("Maximum sum of remaining elements ",calculate(arr, n, k)) # This code is contributed by mohit kumar 29
using System;using System.Collections;using System.Collections.Generic; class GFG{ static int calculate(int []arr, int n, int k){ // Calculate the total sum of all elements // present in the array.. int total_sum = 0; for(int i = 0; i < n; i++) total_sum += arr[i]; // Now calculate the sum of all elements // excluding the last k elements.. int curr_sum = 0; for(int i = 0; i < n - k; i++) curr_sum += arr[i]; // Now here its time to use sliding window // concept, remove the first element from // the current window and add the new element // in it in order to get the sum of all n-k size // of elements in arr. // Calculate the minimum sum of elements of // size n-k and stored it into the result int res = curr_sum; for(int i = n - k; i < n; i++) { curr_sum = curr_sum - arr[i - n + k] + arr[i]; res = Math.Max(res, curr_sum); } // Now return result (sum of // remaining n-k elements) return res;} // Driver codepublic static void Main(string[] args){ int []arr = { 11, 49, 100, 20, 86, 29, 72 }; int n = arr.Length; int k = 4; Console.Write("Maximum sum of remaining " + "elements " + calculate(arr, n, k) + "\n");}} // This code is contributed by rutvik_56
<script> function calculate(arr, n, k){ // calculate the total sum of all elements // present in the array.. let total_sum = 0; for (let i = 0; i < n; i++) total_sum += arr[i]; // now calculate the sum of all elements // excluding the last k elements.. let curr_sum = 0; for (let i = 0; i < n - k; i++) curr_sum += arr[i]; // now here its time to use sliding window // concept, remove the first element from // the current window and add the new element // in it in order to get the sum of all n-k size // of elements in arr. // Calculate the minimum sum of elements of // size n-k and stored it into the result let res = curr_sum; for (let i = n - k; i < n; i++) { curr_sum = curr_sum - arr[i - n + k] + arr[i]; res = Math.max(res, curr_sum); } // Now return result (sum of remaining n-k elements) return res;} // main functionlet arr = [11, 49, 100, 20, 86, 29, 72];let n = arr.length;let k = 4;document.write("Maximum sum of remaining elements " + calculate(arr, n, k) + "<br>"); // This code is contributed by gfgking</script>
Maximum sum of remaining elements 206
Time Complexity: O(k) Auxiliary Space : O(1)
mohit kumar 29
rutvik_56
ukasp
sasikiranbh
gfgking
zack_aayush
karanudayandas
sliding-window
Arrays
sliding-window
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Python | Using 2D arrays/lists the right way
Linked List vs Array
Maximum and minimum of an array using minimum number of comparisons
Given an array of size n and a number k, find all elements that appear more than n/k times
|
[
{
"code": null,
"e": 24812,
"s": 24784,
"text": "\n31 Aug, 2021"
},
{
"code": null,
"e": 25065,
"s": 24812,
"text": "Given an array, the task is to remove total k elements from corners to maximize the sum of remaining elements. For example, if we k = 5 and if we remove 2 elements from the left corner, then we need to remove 3 elements from the right corner.Examples: "
},
{
"code": null,
"e": 25279,
"s": 25065,
"text": "Input : arr = [11, 49, 100, 20, 86, 29, 72], k = 4 Output : 206 Explanation :: We remove 29 and 72 from right corner. We also remove 11 and 49 from left corner to get the maximum sum as 206 for remaining elements."
},
{
"code": null,
"e": 25441,
"s": 25279,
"text": "Input : arr[] = [1, 2, 3, 4, 5, 6, 1], k = 3 Output : 18 Explanation :: We remove two elements from left corner (1 and 2) and one element from right corner (1). "
},
{
"code": null,
"e": 25709,
"s": 25441,
"text": "Naive Approach : 1) Initialize result as negative infinity. 2) Compute total sum. 3) Run a loop for x = 1 to k .....Remove ‘x’ elements from left side and k – i elements from right side. .....If the remaining elements have sum more than the result, update the result."
},
{
"code": null,
"e": 26121,
"s": 25709,
"text": "Time Complexity: O(n * k)Efficient Approach (Using Window Sliding Technique) 1) Find the sum of first n-k elements and initialize this as a current sum and also initialize this as result. 2) Run a loop for i = n-k to n-1 ....curr_sum = curr_sum – arr[i – n + k] + arr[i] ....res = max(res, curr_sum)In step 2, we mainly run sliding window. We remove an element from left side and add an element from right side."
},
{
"code": null,
"e": 26185,
"s": 26121,
"text": "Below is the c++ implementation of the above problem statement."
},
{
"code": null,
"e": 26189,
"s": 26185,
"text": "C++"
},
{
"code": null,
"e": 26194,
"s": 26189,
"text": "Java"
},
{
"code": null,
"e": 26202,
"s": 26194,
"text": "Python3"
},
{
"code": null,
"e": 26205,
"s": 26202,
"text": "C#"
},
{
"code": null,
"e": 26216,
"s": 26205,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std;int calculate(int arr[], int n, int k){ // Calculate the sum of all elements // excluding the last k elements.. int curr_sum = 0; for (int i = 0; i < n - k; i++) curr_sum += arr[i]; // now here its time to use sliding window // concept, remove the first element from // the current window and add the new element // in it in order to get the sum of all n-k size // of elements in arr. // Calculate the minimum sum of elements of // size n-k and stored it into the result int res = curr_sum; for (int i = n - k; i < n; i++) { curr_sum = curr_sum - arr[i - n + k] + arr[i]; res = max(res, curr_sum); } // Now return result (sum of remaining n-k elements) return res;} // main functionint main(){ int arr[] = { 11, 49, 100, 20, 86, 29, 72 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 4; cout << \"Maximum sum of remaining elements \" << calculate(arr, n, k) << \"\\n\"; return 0;}",
"e": 27231,
"s": 26216,
"text": null
},
{
"code": "// Java program for the// above approachimport java.util.*;class GFG{ static int calculate(int[] arr, int n, int k){ // Calculate the total // sum of all elements // present in the array.. int total_sum = 0; for (int i = 0; i < n; i++) total_sum += arr[i]; // Now calculate the sum // of all elements excluding // the last k elements.. int curr_sum = 0; for (int i = 0; i < n - k; i++) curr_sum += arr[i]; // Now here its time to use // sliding window concept, // remove the first element // from the current window // and add the new element // in it in order to get // the sum of all n-k size // of elements in arr. // Calculate the minimum // sum of elements of // size n-k and stored it // into the result int res = curr_sum; for (int i = n - k; i < n; i++) { curr_sum = curr_sum - arr[i - n + k] + arr[i]; res = Math.max(res, curr_sum); } // Now return result (sum of // remaining n-k elements) return res;} // Driver codepublic static void main(String[] args){ int[] arr = {11, 49, 100, 20, 86, 29, 72}; int n = arr.length; int k = 4; System.out.print(\"Maximum sum of remaining \" + \"elements \" + calculate(arr, n, k) + \"\\n\");}} // This code is contributed by Chitranayal",
"e": 28564,
"s": 27231,
"text": null
},
{
"code": "def calculate(arr, n, k): # calculate the total sum of all elements # present in the array.. total_sum = 0 for i in arr: total_sum += i # now calculate the sum of all elements # excluding the last k elements.. curr_sum = 0 for i in range(n - k): curr_sum += arr[i] # now here its time to use sliding window # concept, remove the first element from # the current window and add the new element # in it in order to get the sum of all n-k size # of elements in arr. # Calculate the minimum sum of elements of # size n-k and stored it into the result res = curr_sum for i in range(n - k, n): curr_sum = curr_sum - arr[i - n + k] + arr[i] res = max(res, curr_sum) # Now return result (sum of remaining n-k elements) return res # main functionif __name__ == '__main__': arr=[11, 49, 100, 20, 86, 29, 72] n = len(arr) k = 4 print(\"Maximum sum of remaining elements \",calculate(arr, n, k)) # This code is contributed by mohit kumar 29 ",
"e": 29599,
"s": 28564,
"text": null
},
{
"code": "using System;using System.Collections;using System.Collections.Generic; class GFG{ static int calculate(int []arr, int n, int k){ // Calculate the total sum of all elements // present in the array.. int total_sum = 0; for(int i = 0; i < n; i++) total_sum += arr[i]; // Now calculate the sum of all elements // excluding the last k elements.. int curr_sum = 0; for(int i = 0; i < n - k; i++) curr_sum += arr[i]; // Now here its time to use sliding window // concept, remove the first element from // the current window and add the new element // in it in order to get the sum of all n-k size // of elements in arr. // Calculate the minimum sum of elements of // size n-k and stored it into the result int res = curr_sum; for(int i = n - k; i < n; i++) { curr_sum = curr_sum - arr[i - n + k] + arr[i]; res = Math.Max(res, curr_sum); } // Now return result (sum of // remaining n-k elements) return res;} // Driver codepublic static void Main(string[] args){ int []arr = { 11, 49, 100, 20, 86, 29, 72 }; int n = arr.Length; int k = 4; Console.Write(\"Maximum sum of remaining \" + \"elements \" + calculate(arr, n, k) + \"\\n\");}} // This code is contributed by rutvik_56",
"e": 30937,
"s": 29599,
"text": null
},
{
"code": "<script> function calculate(arr, n, k){ // calculate the total sum of all elements // present in the array.. let total_sum = 0; for (let i = 0; i < n; i++) total_sum += arr[i]; // now calculate the sum of all elements // excluding the last k elements.. let curr_sum = 0; for (let i = 0; i < n - k; i++) curr_sum += arr[i]; // now here its time to use sliding window // concept, remove the first element from // the current window and add the new element // in it in order to get the sum of all n-k size // of elements in arr. // Calculate the minimum sum of elements of // size n-k and stored it into the result let res = curr_sum; for (let i = n - k; i < n; i++) { curr_sum = curr_sum - arr[i - n + k] + arr[i]; res = Math.max(res, curr_sum); } // Now return result (sum of remaining n-k elements) return res;} // main functionlet arr = [11, 49, 100, 20, 86, 29, 72];let n = arr.length;let k = 4;document.write(\"Maximum sum of remaining elements \" + calculate(arr, n, k) + \"<br>\"); // This code is contributed by gfgking</script>",
"e": 32060,
"s": 30937,
"text": null
},
{
"code": null,
"e": 32098,
"s": 32060,
"text": "Maximum sum of remaining elements 206"
},
{
"code": null,
"e": 32145,
"s": 32100,
"text": "Time Complexity: O(k) Auxiliary Space : O(1)"
},
{
"code": null,
"e": 32160,
"s": 32145,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 32170,
"s": 32160,
"text": "rutvik_56"
},
{
"code": null,
"e": 32176,
"s": 32170,
"text": "ukasp"
},
{
"code": null,
"e": 32188,
"s": 32176,
"text": "sasikiranbh"
},
{
"code": null,
"e": 32196,
"s": 32188,
"text": "gfgking"
},
{
"code": null,
"e": 32208,
"s": 32196,
"text": "zack_aayush"
},
{
"code": null,
"e": 32223,
"s": 32208,
"text": "karanudayandas"
},
{
"code": null,
"e": 32238,
"s": 32223,
"text": "sliding-window"
},
{
"code": null,
"e": 32245,
"s": 32238,
"text": "Arrays"
},
{
"code": null,
"e": 32260,
"s": 32245,
"text": "sliding-window"
},
{
"code": null,
"e": 32267,
"s": 32260,
"text": "Arrays"
},
{
"code": null,
"e": 32365,
"s": 32267,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32374,
"s": 32365,
"text": "Comments"
},
{
"code": null,
"e": 32387,
"s": 32374,
"text": "Old Comments"
},
{
"code": null,
"e": 32435,
"s": 32387,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 32479,
"s": 32435,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 32502,
"s": 32479,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 32534,
"s": 32502,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 32548,
"s": 32534,
"text": "Linear Search"
},
{
"code": null,
"e": 32633,
"s": 32548,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 32678,
"s": 32633,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 32699,
"s": 32678,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 32767,
"s": 32699,
"text": "Maximum and minimum of an array using minimum number of comparisons"
}
] |
MongoDB aggregate to convert multiple documents into single document with an array?
|
For aggregate in MongoDB, use aggregate(). Let us create a collection with documents −
> db.demo248.insertOne({"id":101,"Name":"Chris","Age":21,"CountryName":"US"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e46b6651627c0c63e7dba6d")
}
> db.demo248.insertOne({"id":101,"Name":"Bob","Age":22,"CountryName":"UK"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e46b6741627c0c63e7dba6e")
}
> db.demo248.insertOne({"id":102,"Name":"Mike","Age":20,"CountryName":"AUS"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e46b6811627c0c63e7dba6f")
}
Display all documents from a collection with the help of find() method −
> db.demo248.find();
This will produce the following output −
{ "_id" : ObjectId("5e46b6651627c0c63e7dba6d"), "id" : 101, "Name" : "Chris", "Age" : 21, "CountryName" : "US" }
{ "_id" : ObjectId("5e46b6741627c0c63e7dba6e"), "id" : 101, "Name" : "Bob", "Age" : 22, "CountryName" : "UK" }
{ "_id" : ObjectId("5e46b6811627c0c63e7dba6f"), "id" : 102, "Name" : "Mike", "Age" : 20, "CountryName" : "AUS" }
Following is the query to convert multiple documents into single document with an array −
> db.demo248.aggregate([
... {
... $group : {
... _id : "$id",
... details : {
... $push : {
... id:"$id",
... Name:"$Name",
... Age:"$Age",
... CountryName:"$CountryName"
... }
... }
... }
... }
...])
This will produce the following output −
{ "_id" : 102, "details" : [ { "id" : 102, "Name" : "Mike", "Age" : 20, "CountryName" : "AUS" } ] }
{ "_id" : 101, "details" : [ { "id" : 101, "Name" : "Chris", "Age" : 21, "CountryName" : "US" }, { "id" : 101, "Name" : "Bob", "Age" : 22, "CountryName" : "UK" } ] }
|
[
{
"code": null,
"e": 1149,
"s": 1062,
"text": "For aggregate in MongoDB, use aggregate(). Let us create a collection with documents −"
},
{
"code": null,
"e": 1639,
"s": 1149,
"text": "> db.demo248.insertOne({\"id\":101,\"Name\":\"Chris\",\"Age\":21,\"CountryName\":\"US\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e46b6651627c0c63e7dba6d\")\n}\n> db.demo248.insertOne({\"id\":101,\"Name\":\"Bob\",\"Age\":22,\"CountryName\":\"UK\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e46b6741627c0c63e7dba6e\")\n}\n> db.demo248.insertOne({\"id\":102,\"Name\":\"Mike\",\"Age\":20,\"CountryName\":\"AUS\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e46b6811627c0c63e7dba6f\")\n}"
},
{
"code": null,
"e": 1712,
"s": 1639,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1733,
"s": 1712,
"text": "> db.demo248.find();"
},
{
"code": null,
"e": 1774,
"s": 1733,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2111,
"s": 1774,
"text": "{ \"_id\" : ObjectId(\"5e46b6651627c0c63e7dba6d\"), \"id\" : 101, \"Name\" : \"Chris\", \"Age\" : 21, \"CountryName\" : \"US\" }\n{ \"_id\" : ObjectId(\"5e46b6741627c0c63e7dba6e\"), \"id\" : 101, \"Name\" : \"Bob\", \"Age\" : 22, \"CountryName\" : \"UK\" }\n{ \"_id\" : ObjectId(\"5e46b6811627c0c63e7dba6f\"), \"id\" : 102, \"Name\" : \"Mike\", \"Age\" : 20, \"CountryName\" : \"AUS\" }"
},
{
"code": null,
"e": 2201,
"s": 2111,
"text": "Following is the query to convert multiple documents into single document with an array −"
},
{
"code": null,
"e": 2519,
"s": 2201,
"text": "> db.demo248.aggregate([\n... {\n... $group : {\n... _id : \"$id\",\n... details : {\n... $push : {\n... id:\"$id\",\n... Name:\"$Name\",\n... Age:\"$Age\",\n... CountryName:\"$CountryName\"\n... }\n... }\n... }\n... }\n...])"
},
{
"code": null,
"e": 2560,
"s": 2519,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2826,
"s": 2560,
"text": "{ \"_id\" : 102, \"details\" : [ { \"id\" : 102, \"Name\" : \"Mike\", \"Age\" : 20, \"CountryName\" : \"AUS\" } ] }\n{ \"_id\" : 101, \"details\" : [ { \"id\" : 101, \"Name\" : \"Chris\", \"Age\" : 21, \"CountryName\" : \"US\" }, { \"id\" : 101, \"Name\" : \"Bob\", \"Age\" : 22, \"CountryName\" : \"UK\" } ] }"
}
] |
How to enable soft delete for Azure Storage blobs using Azure CLI in Powershell?
|
From the Azure portal, we need to access the Data Protection property of the Azure Storage account.
To enable soft delete using Az CLI, you first need to install the storage-preview extension with the below command.
az extension add -n storage-preview
Once the extension is installed, you need to make sure that you are connected to the Azure Account (if not then use “az login”) command and the proper azure subscription (using “az account set”).
To enable soft delete with Azure CLI use the below command.
az storage fs service-properties update
We can use this command with Key, connection string, or SAS token. Here, we will use the connection string. To retrieve the connection string, use the below command.
$rg = 'az204'
$strgaccount = 'az204storage05june'
$connectionstring = az storage account show-connection-string -g $rg -
n $strgaccount -otsv
To enable the soft delete with 10 days of the retention period, use the below command.
az storage fs service-properties update `
--delete-retention `
--delete-retention-period 10 `
--account-name $strgaccount `
--connection-string $connectionstring
You can also use the storage account key instead of the connection string as shown below.
az storage fs service-properties update `
--delete-retention `
--delete-retention-period 10 `
--account-name $strgaccount `
--account-key $storageaccountkey
|
[
{
"code": null,
"e": 1162,
"s": 1062,
"text": "From the Azure portal, we need to access the Data Protection property of the Azure Storage account."
},
{
"code": null,
"e": 1278,
"s": 1162,
"text": "To enable soft delete using Az CLI, you first need to install the storage-preview extension with the below command."
},
{
"code": null,
"e": 1314,
"s": 1278,
"text": "az extension add -n storage-preview"
},
{
"code": null,
"e": 1510,
"s": 1314,
"text": "Once the extension is installed, you need to make sure that you are connected to the Azure Account (if not then use “az login”) command and the proper azure subscription (using “az account set”)."
},
{
"code": null,
"e": 1570,
"s": 1510,
"text": "To enable soft delete with Azure CLI use the below command."
},
{
"code": null,
"e": 1610,
"s": 1570,
"text": "az storage fs service-properties update"
},
{
"code": null,
"e": 1776,
"s": 1610,
"text": "We can use this command with Key, connection string, or SAS token. Here, we will use the connection string. To retrieve the connection string, use the below command."
},
{
"code": null,
"e": 1918,
"s": 1776,
"text": "$rg = 'az204'\n$strgaccount = 'az204storage05june'\n$connectionstring = az storage account show-connection-string -g $rg -\nn $strgaccount -otsv"
},
{
"code": null,
"e": 2005,
"s": 1918,
"text": "To enable the soft delete with 10 days of the retention period, use the below command."
},
{
"code": null,
"e": 2179,
"s": 2005,
"text": "az storage fs service-properties update `\n --delete-retention `\n --delete-retention-period 10 `\n --account-name $strgaccount `\n --connection-string $connectionstring"
},
{
"code": null,
"e": 2269,
"s": 2179,
"text": "You can also use the storage account key instead of the connection string as shown below."
},
{
"code": null,
"e": 2438,
"s": 2269,
"text": "az storage fs service-properties update `\n --delete-retention `\n --delete-retention-period 10 `\n --account-name $strgaccount `\n --account-key $storageaccountkey"
}
] |
Count factorial numbers in a given range in C++
|
We are given the range starting from an integer value holded by a variable let’s say start till the variable end and the task is to count the total number of factorial numbers available in the given range.
Factorial of a number is calculated by multiplying the digits in a number while decrementing thevalue of digit by 1. It is denoted by the symbol ‘!’ i.e. 0!, 1!, 2!, 3!, 5!,....,etc. Factorial of 0! and 1! is always 1.
I.e. factorial of 2 = 2 * (2-1) = 2 * 1 = 2
factorial of 3 = 3 * (3-1) * (2-1) = 3 * 2 * 1 = 6
Input − start = 5, end = 600
Output − Count of factorial numbers are 3
Explanation − Since, there are 3 numbers available that have factorial numbers in the range 5-600.
Input − start = 1, end = 100
Output − Count of factorial numbers are 5
Explanation − Since, there are 5 numbers available that have factorial numbers in the range 5-600.
Input the range and store in the variables start and end
Input the range and store in the variables start and end
Take another variable, ‘fact’ to store the factorial values and initialise it with 1 and a temporary variable, ‘i’ to increase the numbers count.
Take another variable, ‘fact’ to store the factorial values and initialise it with 1 and a temporary variable, ‘i’ to increase the numbers count.
Start the loop, while fact is less than start and keep multiplying the fact with i to calculate the factorial and also, keep incrementing the value of i
Start the loop, while fact is less than start and keep multiplying the fact with i to calculate the factorial and also, keep incrementing the value of i
Start another loop, while fact is less than equals to end variable and keep incrementing the value of a variable r and keep setting fact to fact *i and keep incrementing value of i
Start another loop, while fact is less than equals to end variable and keep incrementing the value of a variable r and keep setting fact to fact *i and keep incrementing value of i
Now, return the value of r that is holding the total count of total number of factorial numbers
Now, return the value of r that is holding the total count of total number of factorial numbers
Print the result.
Print the result.
Live Demo
#include <iostream>
using namespace std;
// To count the number of factorials
int factorials(int start, int end){
// Starting from 1 and find the first factorial number
// 'fact' greater than or equal to 'start'
int fact = 1, i = 1;
while (fact < start){
fact = fact*i;
i++;
}
// r to count factorial numbers in range start to end
int r = 0;
while (fact <= end){
r++;
fact = fact*i;
i++;
}
// Return the count of factorials in range
return r;
}
int main(){
int start = 5, end = 600;
cout << "Count of factorial numbers are " << factorials(start, end);
return 0;
}
If we run the above code it will generate the following output −
Count of factorial numbers are 3
|
[
{
"code": null,
"e": 1268,
"s": 1062,
"text": "We are given the range starting from an integer value holded by a variable let’s say start till the variable end and the task is to count the total number of factorial numbers available in the given range."
},
{
"code": null,
"e": 1487,
"s": 1268,
"text": "Factorial of a number is calculated by multiplying the digits in a number while decrementing thevalue of digit by 1. It is denoted by the symbol ‘!’ i.e. 0!, 1!, 2!, 3!, 5!,....,etc. Factorial of 0! and 1! is always 1."
},
{
"code": null,
"e": 1588,
"s": 1487,
"text": "I.e. factorial of 2 = 2 * (2-1) = 2 * 1 = 2\n factorial of 3 = 3 * (3-1) * (2-1) = 3 * 2 * 1 = 6"
},
{
"code": null,
"e": 1659,
"s": 1588,
"text": "Input − start = 5, end = 600\nOutput − Count of factorial numbers are 3"
},
{
"code": null,
"e": 1758,
"s": 1659,
"text": "Explanation − Since, there are 3 numbers available that have factorial numbers in the range 5-600."
},
{
"code": null,
"e": 1829,
"s": 1758,
"text": "Input − start = 1, end = 100\nOutput − Count of factorial numbers are 5"
},
{
"code": null,
"e": 1928,
"s": 1829,
"text": "Explanation − Since, there are 5 numbers available that have factorial numbers in the range 5-600."
},
{
"code": null,
"e": 1985,
"s": 1928,
"text": "Input the range and store in the variables start and end"
},
{
"code": null,
"e": 2042,
"s": 1985,
"text": "Input the range and store in the variables start and end"
},
{
"code": null,
"e": 2188,
"s": 2042,
"text": "Take another variable, ‘fact’ to store the factorial values and initialise it with 1 and a temporary variable, ‘i’ to increase the numbers count."
},
{
"code": null,
"e": 2334,
"s": 2188,
"text": "Take another variable, ‘fact’ to store the factorial values and initialise it with 1 and a temporary variable, ‘i’ to increase the numbers count."
},
{
"code": null,
"e": 2487,
"s": 2334,
"text": "Start the loop, while fact is less than start and keep multiplying the fact with i to calculate the factorial and also, keep incrementing the value of i"
},
{
"code": null,
"e": 2640,
"s": 2487,
"text": "Start the loop, while fact is less than start and keep multiplying the fact with i to calculate the factorial and also, keep incrementing the value of i"
},
{
"code": null,
"e": 2821,
"s": 2640,
"text": "Start another loop, while fact is less than equals to end variable and keep incrementing the value of a variable r and keep setting fact to fact *i and keep incrementing value of i"
},
{
"code": null,
"e": 3002,
"s": 2821,
"text": "Start another loop, while fact is less than equals to end variable and keep incrementing the value of a variable r and keep setting fact to fact *i and keep incrementing value of i"
},
{
"code": null,
"e": 3098,
"s": 3002,
"text": "Now, return the value of r that is holding the total count of total number of factorial numbers"
},
{
"code": null,
"e": 3194,
"s": 3098,
"text": "Now, return the value of r that is holding the total count of total number of factorial numbers"
},
{
"code": null,
"e": 3212,
"s": 3194,
"text": "Print the result."
},
{
"code": null,
"e": 3230,
"s": 3212,
"text": "Print the result."
},
{
"code": null,
"e": 3241,
"s": 3230,
"text": " Live Demo"
},
{
"code": null,
"e": 3877,
"s": 3241,
"text": "#include <iostream>\nusing namespace std;\n// To count the number of factorials\nint factorials(int start, int end){\n // Starting from 1 and find the first factorial number\n // 'fact' greater than or equal to 'start'\n int fact = 1, i = 1;\n while (fact < start){\n fact = fact*i;\n i++;\n }\n // r to count factorial numbers in range start to end\n int r = 0;\n while (fact <= end){\n r++;\n fact = fact*i;\n i++;\n }\n // Return the count of factorials in range\n return r;\n}\nint main(){\n int start = 5, end = 600;\n cout << \"Count of factorial numbers are \" << factorials(start, end);\n return 0;\n}"
},
{
"code": null,
"e": 3942,
"s": 3877,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 3975,
"s": 3942,
"text": "Count of factorial numbers are 3"
}
] |
Node.js new Agent() Method - GeeksforGeeks
|
26 Aug, 2020
The Node.js HTTP API is low-level so that it could support the HTTP applications. In order to access and use the HTTP server and client, we need to call them (by ‘require(‘http’)‘). HTTP message headers are represented as JSON Format.
The new Agent({}) (Added in v0.3.4) method is an inbuilt application programming interface (API) of the ‘http’ module in which default globalAgent is used by http.request() which should create a custom http.Agent instance.
Syntax:
new Agent({options})
Parameters: This function accepts a single object parameter as mentioned above and described below:
options <Object> It is the configurable options that could be set on the agent.
keepAlive <boolean>: The Default value set is false. It still Keeps the sockets around whether there are outstanding requests or not, so it could be used for future requests without re-establishing the connection (TCP). The keep-alive header connection is sent while using an agent, and a ‘close’ connection is used to close the connection.
keepAliveMsecs <number>: The Default value set is false. It denotes the initial delay for TCP Keep-Alive packets and if the keepAlive option is false or undefined, gets ignored.
maxSockets <number>: The Default value set is Infinity. It allows the maximum number of sockets per host and until the maximum is reached, each request uses a new socket.
maxTotalSockets <number>: The Default value set is Infinity. It allows the maximum number of sockets for all hosts in total and until the maximum is reached, each request uses a new socket.
maxFreeSockets <number>: The Default value set is 256. In order to leave open in a free state, it uses the maximum number of sockets and it is relevant only if keepAlive is set to true.
scheduling <string>: The Default scheduling is FIFO. It is a strategy of picking the next free socket to schedule and use. It is of two type ‘FIFO‘ or ‘LIFO‘. ‘LIFO‘ (Last In First Out) selects the socket which is most recently used, while ‘FIFO’ (First In First Out) selects the socket which is least recently used.
timeout <number>: It counts the socket timeout in milliseconds and sets the timeout when the socket is created.
The below examples illustrate the use of new Agent({}) method in Node.js.
Example 1: Filename: index.js
// Node.js program to demonstrate the // new agent({}) method // Importing http moduleconst http = require('http');var agent = new http.Agent({}); // Creating new agentconst aliveAgent = new http.Agent({ keepAlive: true, maxSockets: 0, maxSockets: 5, }); // Creating new agentvar agent = new http.Agent({}); // Creating new connectionvar createConnection = aliveAgent.createConnection; // Creating new connectionvar createConnection = agent.createConnection;console.log('Connection successfully created...'); // Printing the connectionconsole.log(createConnection);console.log('Connection successfully created...'); // Printing the connectionconsole.log('Connection: ', createConnection);
Run index.js file using the following command:
node index.js
Output:
Connection successfully created...
[Function: connect]
Connection successfully created...
Connection: [Function: connect]
Another Module agentkeepalive fits better compatible with Http, which makes it easier to handle requests. In order to use the ‘agentkeepalive’ module, we need to install the NPM (Node Package Manager) and the following (on cmd).
// Creates package.json file
>> npm init
// Installs express module
>> npm install agentkeepalive --save OR
>> npm i agentkeepalive -s
Import agentkeepalive module: Import agentkeepalive module and store returned instance into a variable.
const Agent = require('agentkeepalive');
Example 2: Filename: index.js
// Node.js program to demonstrate the // new agent({}) method // Importing http moduleconst http = require('http');// Importing agentkeepalive moduleconst Agent = require('agentkeepalive');// Creating new agentconst keepAliveAgent = new Agent({}); // Options objectconst options = { host: 'geeksforgeeks.org', port: 80, path: '/', method: 'GET', agent: keepAliveAgent,}; // Requesting via http server moduleconst req = http.request(options, (res) => { // console.log(require('util').inspect(res, depth=0)); // Printing statuscode console.log("StatusCode: ", res.statusCode); // Printing headers console.log("Headers: ", res.headers);}); // Printing agent optionsconsole.log("Agent Options: ", req.agent.options);// console.log(req.agent.sockets);req.end();
Run index.js file using the following command:
node index.js
Output:
>> Agent Options: { keepAlive: true,
freeSocketTimeout: 15000,
timeout: 30000,
socketActiveTTL: 0,
path: null}
>> StatusCode: 301
>> Headers: { date: ‘Wed, 19 Aug 2020 11:19:23 GMT’,
server: ‘Apache’,
location: ‘https://www.geeksforgeeks.org/’,
‘content-length’: ‘238’,
‘keep-alive’: ‘timeout=5, max=100’,
connection: ‘Keep-Alive’,
‘content-type’: ‘text/html; charset=iso-8859-1’}
Reference: https://nodejs.org/api/http.html#http_new_agent_options
Node.js-Methods
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Express.js express.Router() Function
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
How to update NPM ?
Difference between promise and async await in Node.js
Express.js express.Router() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 36891,
"s": 36863,
"text": "\n26 Aug, 2020"
},
{
"code": null,
"e": 37126,
"s": 36891,
"text": "The Node.js HTTP API is low-level so that it could support the HTTP applications. In order to access and use the HTTP server and client, we need to call them (by ‘require(‘http’)‘). HTTP message headers are represented as JSON Format."
},
{
"code": null,
"e": 37349,
"s": 37126,
"text": "The new Agent({}) (Added in v0.3.4) method is an inbuilt application programming interface (API) of the ‘http’ module in which default globalAgent is used by http.request() which should create a custom http.Agent instance."
},
{
"code": null,
"e": 37357,
"s": 37349,
"text": "Syntax:"
},
{
"code": null,
"e": 37378,
"s": 37357,
"text": "new Agent({options})"
},
{
"code": null,
"e": 37478,
"s": 37378,
"text": "Parameters: This function accepts a single object parameter as mentioned above and described below:"
},
{
"code": null,
"e": 37558,
"s": 37478,
"text": "options <Object> It is the configurable options that could be set on the agent."
},
{
"code": null,
"e": 37899,
"s": 37558,
"text": "keepAlive <boolean>: The Default value set is false. It still Keeps the sockets around whether there are outstanding requests or not, so it could be used for future requests without re-establishing the connection (TCP). The keep-alive header connection is sent while using an agent, and a ‘close’ connection is used to close the connection."
},
{
"code": null,
"e": 38077,
"s": 37899,
"text": "keepAliveMsecs <number>: The Default value set is false. It denotes the initial delay for TCP Keep-Alive packets and if the keepAlive option is false or undefined, gets ignored."
},
{
"code": null,
"e": 38248,
"s": 38077,
"text": "maxSockets <number>: The Default value set is Infinity. It allows the maximum number of sockets per host and until the maximum is reached, each request uses a new socket."
},
{
"code": null,
"e": 38438,
"s": 38248,
"text": "maxTotalSockets <number>: The Default value set is Infinity. It allows the maximum number of sockets for all hosts in total and until the maximum is reached, each request uses a new socket."
},
{
"code": null,
"e": 38624,
"s": 38438,
"text": "maxFreeSockets <number>: The Default value set is 256. In order to leave open in a free state, it uses the maximum number of sockets and it is relevant only if keepAlive is set to true."
},
{
"code": null,
"e": 38941,
"s": 38624,
"text": "scheduling <string>: The Default scheduling is FIFO. It is a strategy of picking the next free socket to schedule and use. It is of two type ‘FIFO‘ or ‘LIFO‘. ‘LIFO‘ (Last In First Out) selects the socket which is most recently used, while ‘FIFO’ (First In First Out) selects the socket which is least recently used."
},
{
"code": null,
"e": 39053,
"s": 38941,
"text": "timeout <number>: It counts the socket timeout in milliseconds and sets the timeout when the socket is created."
},
{
"code": null,
"e": 39127,
"s": 39053,
"text": "The below examples illustrate the use of new Agent({}) method in Node.js."
},
{
"code": null,
"e": 39157,
"s": 39127,
"text": "Example 1: Filename: index.js"
},
{
"code": "// Node.js program to demonstrate the // new agent({}) method // Importing http moduleconst http = require('http');var agent = new http.Agent({}); // Creating new agentconst aliveAgent = new http.Agent({ keepAlive: true, maxSockets: 0, maxSockets: 5, }); // Creating new agentvar agent = new http.Agent({}); // Creating new connectionvar createConnection = aliveAgent.createConnection; // Creating new connectionvar createConnection = agent.createConnection;console.log('Connection successfully created...'); // Printing the connectionconsole.log(createConnection);console.log('Connection successfully created...'); // Printing the connectionconsole.log('Connection: ', createConnection);",
"e": 39855,
"s": 39157,
"text": null
},
{
"code": null,
"e": 39902,
"s": 39855,
"text": "Run index.js file using the following command:"
},
{
"code": null,
"e": 39916,
"s": 39902,
"text": "node index.js"
},
{
"code": null,
"e": 39924,
"s": 39916,
"text": "Output:"
},
{
"code": null,
"e": 39959,
"s": 39924,
"text": "Connection successfully created..."
},
{
"code": null,
"e": 39979,
"s": 39959,
"text": "[Function: connect]"
},
{
"code": null,
"e": 40014,
"s": 39979,
"text": "Connection successfully created..."
},
{
"code": null,
"e": 40047,
"s": 40014,
"text": "Connection: [Function: connect]"
},
{
"code": null,
"e": 40276,
"s": 40047,
"text": "Another Module agentkeepalive fits better compatible with Http, which makes it easier to handle requests. In order to use the ‘agentkeepalive’ module, we need to install the NPM (Node Package Manager) and the following (on cmd)."
},
{
"code": null,
"e": 40416,
"s": 40276,
"text": "// Creates package.json file\n>> npm init \n\n// Installs express module\n>> npm install agentkeepalive --save OR\n>> npm i agentkeepalive -s "
},
{
"code": null,
"e": 40520,
"s": 40416,
"text": "Import agentkeepalive module: Import agentkeepalive module and store returned instance into a variable."
},
{
"code": null,
"e": 40562,
"s": 40520,
"text": "const Agent = require('agentkeepalive');\n"
},
{
"code": null,
"e": 40592,
"s": 40562,
"text": "Example 2: Filename: index.js"
},
{
"code": "// Node.js program to demonstrate the // new agent({}) method // Importing http moduleconst http = require('http');// Importing agentkeepalive moduleconst Agent = require('agentkeepalive');// Creating new agentconst keepAliveAgent = new Agent({}); // Options objectconst options = { host: 'geeksforgeeks.org', port: 80, path: '/', method: 'GET', agent: keepAliveAgent,}; // Requesting via http server moduleconst req = http.request(options, (res) => { // console.log(require('util').inspect(res, depth=0)); // Printing statuscode console.log(\"StatusCode: \", res.statusCode); // Printing headers console.log(\"Headers: \", res.headers);}); // Printing agent optionsconsole.log(\"Agent Options: \", req.agent.options);// console.log(req.agent.sockets);req.end();",
"e": 41364,
"s": 40592,
"text": null
},
{
"code": null,
"e": 41411,
"s": 41364,
"text": "Run index.js file using the following command:"
},
{
"code": null,
"e": 41425,
"s": 41411,
"text": "node index.js"
},
{
"code": null,
"e": 41433,
"s": 41425,
"text": "Output:"
},
{
"code": null,
"e": 41470,
"s": 41433,
"text": ">> Agent Options: { keepAlive: true,"
},
{
"code": null,
"e": 41497,
"s": 41470,
"text": " freeSocketTimeout: 15000,"
},
{
"code": null,
"e": 41514,
"s": 41497,
"text": " timeout: 30000,"
},
{
"code": null,
"e": 41535,
"s": 41514,
"text": " socketActiveTTL: 0,"
},
{
"code": null,
"e": 41548,
"s": 41535,
"text": " path: null}"
},
{
"code": null,
"e": 41568,
"s": 41548,
"text": ">> StatusCode: 301"
},
{
"code": null,
"e": 41622,
"s": 41568,
"text": ">> Headers: { date: ‘Wed, 19 Aug 2020 11:19:23 GMT’,"
},
{
"code": null,
"e": 41641,
"s": 41622,
"text": " server: ‘Apache’,"
},
{
"code": null,
"e": 41686,
"s": 41641,
"text": " location: ‘https://www.geeksforgeeks.org/’,"
},
{
"code": null,
"e": 41712,
"s": 41686,
"text": " ‘content-length’: ‘238’,"
},
{
"code": null,
"e": 41749,
"s": 41712,
"text": " ‘keep-alive’: ‘timeout=5, max=100’,"
},
{
"code": null,
"e": 41776,
"s": 41749,
"text": " connection: ‘Keep-Alive’,"
},
{
"code": null,
"e": 41826,
"s": 41776,
"text": " ‘content-type’: ‘text/html; charset=iso-8859-1’}"
},
{
"code": null,
"e": 41893,
"s": 41826,
"text": "Reference: https://nodejs.org/api/http.html#http_new_agent_options"
},
{
"code": null,
"e": 41909,
"s": 41893,
"text": "Node.js-Methods"
},
{
"code": null,
"e": 41917,
"s": 41909,
"text": "Node.js"
},
{
"code": null,
"e": 41934,
"s": 41917,
"text": "Web Technologies"
},
{
"code": null,
"e": 42032,
"s": 41934,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42041,
"s": 42032,
"text": "Comments"
},
{
"code": null,
"e": 42054,
"s": 42041,
"text": "Old Comments"
},
{
"code": null,
"e": 42091,
"s": 42054,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 42139,
"s": 42091,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 42172,
"s": 42139,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 42192,
"s": 42172,
"text": "How to update NPM ?"
},
{
"code": null,
"e": 42246,
"s": 42192,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 42283,
"s": 42246,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 42345,
"s": 42283,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 42388,
"s": 42345,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 42449,
"s": 42388,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
Toolz module in Python - GeeksforGeeks
|
26 Mar, 2020
Toolz package provides a set of utility functions for iterators, functions, and dictionaries. These functions extend the standard libraries itertools and functools and borrow heavily from the standard libraries of contemporary functional languages. This package consists of following modules –
dicttoolz
functoolz
itertoolz
recipes
sandbox
Functions –
assoc(d, key, value[, factory]) – Returns a new dict with new key value pair. It does not modify the initial dictionary.import toolz d = toolz.dicttoolz.assoc({'Geeks':0}, 'forGeeks', 1)print(d)Output –{'Geeks': 0, 'forGeeks': 1}
import toolz d = toolz.dicttoolz.assoc({'Geeks':0}, 'forGeeks', 1)print(d)
Output –
{'Geeks': 0, 'forGeeks': 1}
assoc_in(d, keys, value[, factory]) – Returns a new dict with new, potentially nested, key value pairimport toolz d = toolz.dicttoolz.assoc_in({'Geeks':0}, 'forGeeks', 1)print(d)Output –{‘Geeks’: 0, ‘f’: {‘o’: {‘r’: {‘G’: {‘e’: {‘e’: {‘k’: {‘s’: 1}}}}}}}}
import toolz d = toolz.dicttoolz.assoc_in({'Geeks':0}, 'forGeeks', 1)print(d)
Output –
{‘Geeks’: 0, ‘f’: {‘o’: {‘r’: {‘G’: {‘e’: {‘e’: {‘k’: {‘s’: 1}}}}}}}}
dissoc(d, *keys) – Returns a new dict with the given key(s) removed. It does not modify the initial dictionary.import toolz d = toolz.dicttoolz.dissoc({'g':0, 'e':1, 'k':2, 's':3}, 'k', 'e')print(d)Output –{'g': 0, 's': 3}
import toolz d = toolz.dicttoolz.dissoc({'g':0, 'e':1, 'k':2, 's':3}, 'k', 'e')print(d)
Output –
{'g': 0, 's': 3}
get_in(keys, ds[, default, no_default]) – Returns ds[I0][I1]...[IX] where [I0, I1, ..., IX] are keys and ds is a nested dictionary. If ds[I0][I1]...[IX] cannot be found, it returns “default”.import toolz nested_dict ={'d1':{'k1':'v1', 'k2':'v2'}, 'd2':{'k3':{'d2A':{'k4':'v4'}}}} d = toolz.dicttoolz.get_in(['d1'], nested_dict)print(d) d = toolz.dicttoolz.get_in(['d2', 'k3', 'd2A'], nested_dict)print(d)Output –{'k1': 'v1', 'k2': 'v2'}
{'k4': 'v4'}
import toolz nested_dict ={'d1':{'k1':'v1', 'k2':'v2'}, 'd2':{'k3':{'d2A':{'k4':'v4'}}}} d = toolz.dicttoolz.get_in(['d1'], nested_dict)print(d) d = toolz.dicttoolz.get_in(['d2', 'k3', 'd2A'], nested_dict)print(d)
Output –
{'k1': 'v1', 'k2': 'v2'}
{'k4': 'v4'}
itemfilter(predicate, d[, factory]) – It filters items in dictionary by item.import toolz def func(item): key, val = item return key == ord(val)-65 d = {0:'A', 1:'B', 3:'C', 5:'F'}print(toolz.dicttoolz.itemfilter(func, d))Output –{0: 'A', 1: 'B', 5: 'F'}
import toolz def func(item): key, val = item return key == ord(val)-65 d = {0:'A', 1:'B', 3:'C', 5:'F'}print(toolz.dicttoolz.itemfilter(func, d))
Output –
{0: 'A', 1: 'B', 5: 'F'}
itemmap(func, d[, factory]) – Applies function to items of dictionary.import toolz d = {0:'A', 1:'B', 3:'C', 5:'F'}print(toolz.dicttoolz.itemmap(reversed, d))Output –{'A': 0, 'B': 1, 'C': 3, 'F': 5}
import toolz d = {0:'A', 1:'B', 3:'C', 5:'F'}print(toolz.dicttoolz.itemmap(reversed, d))
Output –
{'A': 0, 'B': 1, 'C': 3, 'F': 5}
keyfilter(predicate, d[, factory]) – It filters items in dictionary by key.import toolz def func(key): return 5<= len(key)<7 d = {'python': 0, 'julia': 1, 'java': 3, 'javascript': 5}print(toolz.dicttoolz.keyfilter(func, d))Output –{'python': 0, 'julia': 1}
import toolz def func(key): return 5<= len(key)<7 d = {'python': 0, 'julia': 1, 'java': 3, 'javascript': 5}print(toolz.dicttoolz.keyfilter(func, d))
Output –
{'python': 0, 'julia': 1}
keymap(func, d[, factory] – Applies function to keys of dictionary .import toolz def func(key): return ''.join(reversed(key)) d = {'python': 0, 'julia': 1, 'java': 3, 'javascript': 5}print(toolz.dicttoolz.keymap(func, d))Output –{'nohtyp': 0, 'ailuj': 1, 'avaj': 3, 'tpircsavaj': 5}
import toolz def func(key): return ''.join(reversed(key)) d = {'python': 0, 'julia': 1, 'java': 3, 'javascript': 5}print(toolz.dicttoolz.keymap(func, d))
Output –
{'nohtyp': 0, 'ailuj': 1, 'avaj': 3, 'tpircsavaj': 5}
merge(*dicts, **kwargs) – It merges a collection of dictionaries.import toolz dict1 = {1:1, 2:4}dict2 = {3:9, 2:8, 4:16}print(toolz.dicttoolz.merge(dict1, dict2))Output –{1: 1, 2: 8, 3: 9, 4: 16}
import toolz dict1 = {1:1, 2:4}dict2 = {3:9, 2:8, 4:16}print(toolz.dicttoolz.merge(dict1, dict2))
Output –
{1: 1, 2: 8, 3: 9, 4: 16}
merge_with(func, *dicts, **kwargs) – Merges dictionaries and applies function to combined values.import toolz dict1 = {1:1, 2:4}dict2 = {3:9, 2:8, 1:1}print(toolz.dicttoolz.merge_with(sum, dict1, dict2))Output –{1: 2, 2: 12, 3: 9}
import toolz dict1 = {1:1, 2:4}dict2 = {3:9, 2:8, 1:1}print(toolz.dicttoolz.merge_with(sum, dict1, dict2))
Output –
{1: 2, 2: 12, 3: 9}
update_in(d, keys, func[, default, factory]) –Updates value in a nested dictionary. If keys = [k0, .., kX] and d[k0, ..., kX] = value, update_in returns a copy of the original dictionary with ‘value’ replaced by func(value).import toolz def func(value): return value//2 nested_dict = {1:{11:111}, 2:{22:222}}print(toolz.dicttoolz.update_in(nested_dict, [1, 11], func))Output –{1: {11: 55}, 2: {22: 222}}
import toolz def func(value): return value//2 nested_dict = {1:{11:111}, 2:{22:222}}print(toolz.dicttoolz.update_in(nested_dict, [1, 11], func))
Output –
{1: {11: 55}, 2: {22: 222}}
valfilter(predicate, d[, factory]) – Filter items in dictionary by value.import toolz def func(value): return 4<len(value)<7 d = {0: 'python', 1: 'julia', 3: 'java', 5: 'javascript'}print(toolz.dicttoolz.valfilter(func, d))Output –{0: 'python', 1: 'julia'}
import toolz def func(value): return 4<len(value)<7 d = {0: 'python', 1: 'julia', 3: 'java', 5: 'javascript'}print(toolz.dicttoolz.valfilter(func, d))
Output –
{0: 'python', 1: 'julia'}
valmap(func, d[, factory]) – Apply function to values of dictionary.import toolz def func(value): return ''.join(reversed(value)) d = {0: 'python', 1: 'julia', 3: 'java', 5: 'javascript'}print(toolz.dicttoolz.valmap(func, d))Output –{0: 'nohtyp', 1: 'ailuj', 3: 'avaj', 5: 'tpircsavaj'}
import toolz def func(value): return ''.join(reversed(value)) d = {0: 'python', 1: 'julia', 3: 'java', 5: 'javascript'}print(toolz.dicttoolz.valmap(func, d))
Output –
{0: 'nohtyp', 1: 'ailuj', 3: 'avaj', 5: 'tpircsavaj'}
Functions –
apply(*func_and_args, **kwargs) – It simply applies a function and returns the result.import toolz def double(n): return n + n print(toolz.functoolz.apply(double, 2))Output –4
import toolz def double(n): return n + n print(toolz.functoolz.apply(double, 2))
Output –
4
complement(func) – As its name suggests, it converts returns the logical complement of the input provided.import toolz def is_mulitple_of_5(n): return n % 5 == 0 not_multiple_of_5 = toolz.functoolz.complement(is_mulitple_of_5) print(is_mulitple_of_5(10))print(not_multiple_of_5(10))Output –True
False
import toolz def is_mulitple_of_5(n): return n % 5 == 0 not_multiple_of_5 = toolz.functoolz.complement(is_mulitple_of_5) print(is_mulitple_of_5(10))print(not_multiple_of_5(10))
Output –
True
False
compose(*funcs) – It returns a function that applies other functions in sequence. Functions are applied from right to left. If no arguments are provided, the identity function (f(x) = x) is returned.import toolz def func(n): return n + n def square(n): return n * n x = toolz.functoolz.compose(func, square)(3)print(x)Output –18
import toolz def func(n): return n + n def square(n): return n * n x = toolz.functoolz.compose(func, square)(3)print(x)
Output –
18
compose_left(*funcs) – It returns a function that applies other functions in sequence. Functions are applied from left to right. If no arguments are provided, the identity function (f(x) = x) is returned.import toolz def func(n): return n + n def square(n): return n * n x = toolz.functoolz.compose_left(func, square)(3)print(x)Output –36
import toolz def func(n): return n + n def square(n): return n * n x = toolz.functoolz.compose_left(func, square)(3)print(x)
Output –
36
flip – Call the function with the arguments in reverse order.import toolz def mod(a, b): return a % b print('7 % 3 :', toolz.functoolz.flip(mod, 3, 7))Output –7 % 3 : 1
import toolz def mod(a, b): return a % b print('7 % 3 :', toolz.functoolz.flip(mod, 3, 7))
Output –
7 % 3 : 1
identity(x) – Identity function, simply returns x.import toolz print(toolz.functoolz.identity(6))Output –6
import toolz print(toolz.functoolz.identity(6))
Output –
6
pipe(data, *funcs) – Pipe a value through a sequence of functions. It is equivalent to compose_left(*funcs)import toolz print(toolz.functoolz.pipe(3, double, square))Output –36
import toolz print(toolz.functoolz.pipe(3, double, square))
Output –
36
thread_first(val, *forms) – Thread value through a sequence of functions/forms.import toolz def mod(a, b): return a % b def double(n): return n + n print(toolz.functoolz.thread_first(3, (mod, 2), double))Output –2
import toolz def mod(a, b): return a % b def double(n): return n + n print(toolz.functoolz.thread_first(3, (mod, 2), double))
Output –
2
thread_last(val, *forms) – Thread value through a sequence of functions/forms.import toolz def mod(a, b): return a % b def double(n): return n + n print(toolz.functoolz.thread_last(3, (mod, 2), double))Output –4
import toolz def mod(a, b): return a % b def double(n): return n + n print(toolz.functoolz.thread_last(3, (mod, 2), double))
Output –
4
Functions –
accumulate(binop, seq[, initial]) – This is similar to ‘reduce’ function. It repeatedly applies a function to a sequence accumulating results.import toolzfrom operator import add print(list(toolz.itertoolz.accumulate(add, [1, 2, 3, 4])))Output –[1, 3, 6, 10]
import toolzfrom operator import add print(list(toolz.itertoolz.accumulate(add, [1, 2, 3, 4])))
Output –
[1, 3, 6, 10]
concat(seqs) – It concatenates two or more iterables.import toolz print(list(toolz.itertoolz.concat([[1], ['a'], [2, 3, 4]])))Output –[1, 'a', 2, 3, 4]
import toolz print(list(toolz.itertoolz.concat([[1], ['a'], [2, 3, 4]])))
Output –
[1, 'a', 2, 3, 4]
cons(item, seq) – It adds ‘item’ in the beginning of sequence. It is equivalent to insert(0, item).import toolz print(list(toolz.itertoolz.cons(1, ['a', 'b'])))Output –[1, 'a', 'b']
import toolz print(list(toolz.itertoolz.cons(1, ['a', 'b'])))
Output –
[1, 'a', 'b']
diff(*seqs, **kwargs) – It compares the elements at every index in both iterables and returns the list of differing pairs.import toolz print(list(toolz.itertoolz.diff([1, 2, 3], [2, 2, 4])))Output –[(1, 2), (3, 4)]
import toolz print(list(toolz.itertoolz.diff([1, 2, 3], [2, 2, 4])))
Output –
[(1, 2), (3, 4)]
drop(n, seq) – It drops the first n elements of sequence and returns the new sequence.import toolz print(list(toolz.itertoolz.drop(3, [2, 3, 2, 6, 4, 7])))Output –[6, 4, 7]
import toolz print(list(toolz.itertoolz.drop(3, [2, 3, 2, 6, 4, 7])))
Output –
[6, 4, 7]
frequencies(seq) – It returns a dictionary with elements and their count in sequence. It is equivalent to collections.Counter.import toolz print(toolz.itertoolz.frequencies(['c', 'b', 'c', 'b', 'd', 'e', 'h', 'h', 'b']))Output –{'c': 2, 'b': 3, 'd': 1, 'e': 1, 'h': 2}
import toolz print(toolz.itertoolz.frequencies(['c', 'b', 'c', 'b', 'd', 'e', 'h', 'h', 'b']))
Output –
{'c': 2, 'b': 3, 'd': 1, 'e': 1, 'h': 2}
groupby(func, seq) – It returns a dictionary after grouping the sequence elements according to func.import toolz print(toolz.itertoolz.groupby(len, ['geeks', 'for', 'geeks']))Output –{5: ['geeks', 'geeks'], 3: ['for']}
import toolz print(toolz.itertoolz.groupby(len, ['geeks', 'for', 'geeks']))
Output –
{5: ['geeks', 'geeks'], 3: ['for']}
isdistinct(seq) – It returns True if all elements in the sequence are distinct, else False.import toolz print(toolz.itertoolz.isdistinct('geeks'))Output –False
import toolz print(toolz.itertoolz.isdistinct('geeks'))
Output –
False
isiterable(x) – It returns True if x is an iterable, else False.print(toolz.itertoolz.isiterable([10]))Output - True
print(toolz.itertoolz.isiterable([10]))
Output - True
interleave(seqs) – It interleaves the sequences, i.e. concatenates the sequences index-wise.import toolz print(list(toolz.itertoolz.interleave([[10, 20], [5, 8, 11]])))Output –[10, 5, 20, 8, 11]
import toolz print(list(toolz.itertoolz.interleave([[10, 20], [5, 8, 11]])))
Output –
[10, 5, 20, 8, 11]
topk(k, seq[, key]) – It returns the top k largest elements of the sequence.import toolz print(list(toolz.itertoolz.topk(2, [10, 20, 5, 8, 11])))Output –[20, 11]
import toolz print(list(toolz.itertoolz.topk(2, [10, 20, 5, 8, 11])))
Output –
[20, 11]
unique(seq[, key]) – It returns the distinct elements of sequence just like set(seq).import toolz print(list(toolz.itertoolz.unique([10, 20, 5, 8, 10, 20])))Output –[10, 20, 5, 8]
import toolz print(list(toolz.itertoolz.unique([10, 20, 5, 8, 10, 20])))
Output –
[10, 20, 5, 8]
merge_sorted(*seqs, **kwargs) – It merges sorted iterables in such a way that the resulting collection is also sorted.import toolz print(list(toolz.itertoolz.merge_sorted([5, 10, 20], [4, 12, 24])))Output –[4, 5, 10, 12, 20, 24]
import toolz print(list(toolz.itertoolz.merge_sorted([5, 10, 20], [4, 12, 24])))
Output –
[4, 5, 10, 12, 20, 24]
mapcat(func, seqs) – It applies func to each sequence and concatenates the results.import toolz print(list(toolz.itertoolz.mapcat(lambda iter: [e * 2 for e in iter], [[5, 10, 20], [4, 12, 24]])))Output –[10, 20, 40, 8, 24, 48]
import toolz print(list(toolz.itertoolz.mapcat(lambda iter: [e * 2 for e in iter], [[5, 10, 20], [4, 12, 24]])))
Output –
[10, 20, 40, 8, 24, 48]
remove(predicate, seq) – It returns those elements from sequence for which predicate is False. It is complement function of filter.import toolz print(list(toolz.itertoolz.remove(lambda x: x % 2 == 0, [5, 21, 4, 12, 24])))Output –[5, 21]
import toolz print(list(toolz.itertoolz.remove(lambda x: x % 2 == 0, [5, 21, 4, 12, 24])))
Output –
[5, 21]
Functions –
countby(key, seq) – Count elements of a collection by a key function.import toolz def iseven(n): return n % 2 == 0 print(toolz.recipes.countby(iseven, [12, 123, 1234]))Output –{True: 2, False: 1}
import toolz def iseven(n): return n % 2 == 0 print(toolz.recipes.countby(iseven, [12, 123, 1234]))
Output –
{True: 2, False: 1}
partitionby(func, seq) – Partition a sequence according to a given function.import toolz def iseven(n): return n % 2 == 0 print(list(toolz.recipes.partitionby(iseven, [12, 123, 31, 1234])))Output –[(12, ), (123, 31), (1234, )]
import toolz def iseven(n): return n % 2 == 0 print(list(toolz.recipes.partitionby(iseven, [12, 123, 31, 1234])))
Output –
[(12, ), (123, 31), (1234, )]
Functions –
parallel.fold(binop, seq[, default, map, ...] – Reduce without guarantee of ordered reduction.import toolz def sum(a, b): return a + b print(toolz.sandbox.parallel.fold(sum, [1, 2, 3, 4]))Output –10
import toolz def sum(a, b): return a + b print(toolz.sandbox.parallel.fold(sum, [1, 2, 3, 4]))
Output –
10
core.unzip(seq) – Inverse of zip.import toolz l1, l2 = toolz.sandbox.core.unzip([(0, 1), (1, 2), (2, 3)]) print(list(l1), list(l2))Output –[0, 1, 2] [1, 2, 3]
My Personal Notes
arrow_drop_upSave
import toolz l1, l2 = toolz.sandbox.core.unzip([(0, 1), (1, 2), (2, 3)]) print(list(l1), list(l2))
Output –
[0, 1, 2] [1, 2, 3]
python-modules
Python
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
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python
|
[
{
"code": null,
"e": 24212,
"s": 24184,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 24506,
"s": 24212,
"text": "Toolz package provides a set of utility functions for iterators, functions, and dictionaries. These functions extend the standard libraries itertools and functools and borrow heavily from the standard libraries of contemporary functional languages. This package consists of following modules –"
},
{
"code": null,
"e": 24516,
"s": 24506,
"text": "dicttoolz"
},
{
"code": null,
"e": 24526,
"s": 24516,
"text": "functoolz"
},
{
"code": null,
"e": 24536,
"s": 24526,
"text": "itertoolz"
},
{
"code": null,
"e": 24544,
"s": 24536,
"text": "recipes"
},
{
"code": null,
"e": 24552,
"s": 24544,
"text": "sandbox"
},
{
"code": null,
"e": 24564,
"s": 24552,
"text": "Functions –"
},
{
"code": null,
"e": 24798,
"s": 24564,
"text": "assoc(d, key, value[, factory]) – Returns a new dict with new key value pair. It does not modify the initial dictionary.import toolz d = toolz.dicttoolz.assoc({'Geeks':0}, 'forGeeks', 1)print(d)Output –{'Geeks': 0, 'forGeeks': 1}\n"
},
{
"code": "import toolz d = toolz.dicttoolz.assoc({'Geeks':0}, 'forGeeks', 1)print(d)",
"e": 24876,
"s": 24798,
"text": null
},
{
"code": null,
"e": 24885,
"s": 24876,
"text": "Output –"
},
{
"code": null,
"e": 24914,
"s": 24885,
"text": "{'Geeks': 0, 'forGeeks': 1}\n"
},
{
"code": null,
"e": 25171,
"s": 24914,
"text": "assoc_in(d, keys, value[, factory]) – Returns a new dict with new, potentially nested, key value pairimport toolz d = toolz.dicttoolz.assoc_in({'Geeks':0}, 'forGeeks', 1)print(d)Output –{‘Geeks’: 0, ‘f’: {‘o’: {‘r’: {‘G’: {‘e’: {‘e’: {‘k’: {‘s’: 1}}}}}}}}"
},
{
"code": "import toolz d = toolz.dicttoolz.assoc_in({'Geeks':0}, 'forGeeks', 1)print(d)",
"e": 25250,
"s": 25171,
"text": null
},
{
"code": null,
"e": 25259,
"s": 25250,
"text": "Output –"
},
{
"code": null,
"e": 25329,
"s": 25259,
"text": "{‘Geeks’: 0, ‘f’: {‘o’: {‘r’: {‘G’: {‘e’: {‘e’: {‘k’: {‘s’: 1}}}}}}}}"
},
{
"code": null,
"e": 25609,
"s": 25329,
"text": "dissoc(d, *keys) – Returns a new dict with the given key(s) removed. It does not modify the initial dictionary.import toolz d = toolz.dicttoolz.dissoc({'g':0, 'e':1, 'k':2, 's':3}, 'k', 'e')print(d)Output –{'g': 0, 's': 3}\n"
},
{
"code": "import toolz d = toolz.dicttoolz.dissoc({'g':0, 'e':1, 'k':2, 's':3}, 'k', 'e')print(d)",
"e": 25753,
"s": 25609,
"text": null
},
{
"code": null,
"e": 25762,
"s": 25753,
"text": "Output –"
},
{
"code": null,
"e": 25780,
"s": 25762,
"text": "{'g': 0, 's': 3}\n"
},
{
"code": null,
"e": 26277,
"s": 25780,
"text": "get_in(keys, ds[, default, no_default]) – Returns ds[I0][I1]...[IX] where [I0, I1, ..., IX] are keys and ds is a nested dictionary. If ds[I0][I1]...[IX] cannot be found, it returns “default”.import toolz nested_dict ={'d1':{'k1':'v1', 'k2':'v2'}, 'd2':{'k3':{'d2A':{'k4':'v4'}}}} d = toolz.dicttoolz.get_in(['d1'], nested_dict)print(d) d = toolz.dicttoolz.get_in(['d2', 'k3', 'd2A'], nested_dict)print(d)Output –{'k1': 'v1', 'k2': 'v2'}\n{'k4': 'v4'}\n"
},
{
"code": "import toolz nested_dict ={'d1':{'k1':'v1', 'k2':'v2'}, 'd2':{'k3':{'d2A':{'k4':'v4'}}}} d = toolz.dicttoolz.get_in(['d1'], nested_dict)print(d) d = toolz.dicttoolz.get_in(['d2', 'k3', 'd2A'], nested_dict)print(d)",
"e": 26537,
"s": 26277,
"text": null
},
{
"code": null,
"e": 26546,
"s": 26537,
"text": "Output –"
},
{
"code": null,
"e": 26585,
"s": 26546,
"text": "{'k1': 'v1', 'k2': 'v2'}\n{'k4': 'v4'}\n"
},
{
"code": null,
"e": 26863,
"s": 26585,
"text": "itemfilter(predicate, d[, factory]) – It filters items in dictionary by item.import toolz def func(item): key, val = item return key == ord(val)-65 d = {0:'A', 1:'B', 3:'C', 5:'F'}print(toolz.dicttoolz.itemfilter(func, d))Output –{0: 'A', 1: 'B', 5: 'F'}\n"
},
{
"code": "import toolz def func(item): key, val = item return key == ord(val)-65 d = {0:'A', 1:'B', 3:'C', 5:'F'}print(toolz.dicttoolz.itemfilter(func, d))",
"e": 27031,
"s": 26863,
"text": null
},
{
"code": null,
"e": 27040,
"s": 27031,
"text": "Output –"
},
{
"code": null,
"e": 27066,
"s": 27040,
"text": "{0: 'A', 1: 'B', 5: 'F'}\n"
},
{
"code": null,
"e": 27269,
"s": 27066,
"text": "itemmap(func, d[, factory]) – Applies function to items of dictionary.import toolz d = {0:'A', 1:'B', 3:'C', 5:'F'}print(toolz.dicttoolz.itemmap(reversed, d))Output –{'A': 0, 'B': 1, 'C': 3, 'F': 5}\n"
},
{
"code": "import toolz d = {0:'A', 1:'B', 3:'C', 5:'F'}print(toolz.dicttoolz.itemmap(reversed, d))",
"e": 27361,
"s": 27269,
"text": null
},
{
"code": null,
"e": 27370,
"s": 27361,
"text": "Output –"
},
{
"code": null,
"e": 27404,
"s": 27370,
"text": "{'A': 0, 'B': 1, 'C': 3, 'F': 5}\n"
},
{
"code": null,
"e": 27669,
"s": 27404,
"text": "keyfilter(predicate, d[, factory]) – It filters items in dictionary by key.import toolz def func(key): return 5<= len(key)<7 d = {'python': 0, 'julia': 1, 'java': 3, 'javascript': 5}print(toolz.dicttoolz.keyfilter(func, d))Output –{'python': 0, 'julia': 1}\n"
},
{
"code": "import toolz def func(key): return 5<= len(key)<7 d = {'python': 0, 'julia': 1, 'java': 3, 'javascript': 5}print(toolz.dicttoolz.keyfilter(func, d))",
"e": 27825,
"s": 27669,
"text": null
},
{
"code": null,
"e": 27834,
"s": 27825,
"text": "Output –"
},
{
"code": null,
"e": 27861,
"s": 27834,
"text": "{'python': 0, 'julia': 1}\n"
},
{
"code": null,
"e": 28152,
"s": 27861,
"text": "keymap(func, d[, factory] – Applies function to keys of dictionary .import toolz def func(key): return ''.join(reversed(key)) d = {'python': 0, 'julia': 1, 'java': 3, 'javascript': 5}print(toolz.dicttoolz.keymap(func, d))Output –{'nohtyp': 0, 'ailuj': 1, 'avaj': 3, 'tpircsavaj': 5}\n"
},
{
"code": "import toolz def func(key): return ''.join(reversed(key)) d = {'python': 0, 'julia': 1, 'java': 3, 'javascript': 5}print(toolz.dicttoolz.keymap(func, d))",
"e": 28313,
"s": 28152,
"text": null
},
{
"code": null,
"e": 28322,
"s": 28313,
"text": "Output –"
},
{
"code": null,
"e": 28377,
"s": 28322,
"text": "{'nohtyp': 0, 'ailuj': 1, 'avaj': 3, 'tpircsavaj': 5}\n"
},
{
"code": null,
"e": 28577,
"s": 28377,
"text": "merge(*dicts, **kwargs) – It merges a collection of dictionaries.import toolz dict1 = {1:1, 2:4}dict2 = {3:9, 2:8, 4:16}print(toolz.dicttoolz.merge(dict1, dict2))Output –{1: 1, 2: 8, 3: 9, 4: 16}\n"
},
{
"code": "import toolz dict1 = {1:1, 2:4}dict2 = {3:9, 2:8, 4:16}print(toolz.dicttoolz.merge(dict1, dict2))",
"e": 28678,
"s": 28577,
"text": null
},
{
"code": null,
"e": 28687,
"s": 28678,
"text": "Output –"
},
{
"code": null,
"e": 28714,
"s": 28687,
"text": "{1: 1, 2: 8, 3: 9, 4: 16}\n"
},
{
"code": null,
"e": 28949,
"s": 28714,
"text": "merge_with(func, *dicts, **kwargs) – Merges dictionaries and applies function to combined values.import toolz dict1 = {1:1, 2:4}dict2 = {3:9, 2:8, 1:1}print(toolz.dicttoolz.merge_with(sum, dict1, dict2))Output –{1: 2, 2: 12, 3: 9}\n"
},
{
"code": "import toolz dict1 = {1:1, 2:4}dict2 = {3:9, 2:8, 1:1}print(toolz.dicttoolz.merge_with(sum, dict1, dict2))",
"e": 29059,
"s": 28949,
"text": null
},
{
"code": null,
"e": 29068,
"s": 29059,
"text": "Output –"
},
{
"code": null,
"e": 29089,
"s": 29068,
"text": "{1: 2, 2: 12, 3: 9}\n"
},
{
"code": null,
"e": 29508,
"s": 29089,
"text": "update_in(d, keys, func[, default, factory]) –Updates value in a nested dictionary. If keys = [k0, .., kX] and d[k0, ..., kX] = value, update_in returns a copy of the original dictionary with ‘value’ replaced by func(value).import toolz def func(value): return value//2 nested_dict = {1:{11:111}, 2:{22:222}}print(toolz.dicttoolz.update_in(nested_dict, [1, 11], func))Output –{1: {11: 55}, 2: {22: 222}}\n"
},
{
"code": "import toolz def func(value): return value//2 nested_dict = {1:{11:111}, 2:{22:222}}print(toolz.dicttoolz.update_in(nested_dict, [1, 11], func))",
"e": 29667,
"s": 29508,
"text": null
},
{
"code": null,
"e": 29676,
"s": 29667,
"text": "Output –"
},
{
"code": null,
"e": 29705,
"s": 29676,
"text": "{1: {11: 55}, 2: {22: 222}}\n"
},
{
"code": null,
"e": 29970,
"s": 29705,
"text": "valfilter(predicate, d[, factory]) – Filter items in dictionary by value.import toolz def func(value): return 4<len(value)<7 d = {0: 'python', 1: 'julia', 3: 'java', 5: 'javascript'}print(toolz.dicttoolz.valfilter(func, d))Output –{0: 'python', 1: 'julia'}\n"
},
{
"code": "import toolz def func(value): return 4<len(value)<7 d = {0: 'python', 1: 'julia', 3: 'java', 5: 'javascript'}print(toolz.dicttoolz.valfilter(func, d))",
"e": 30128,
"s": 29970,
"text": null
},
{
"code": null,
"e": 30137,
"s": 30128,
"text": "Output –"
},
{
"code": null,
"e": 30164,
"s": 30137,
"text": "{0: 'python', 1: 'julia'}\n"
},
{
"code": null,
"e": 30459,
"s": 30164,
"text": "valmap(func, d[, factory]) – Apply function to values of dictionary.import toolz def func(value): return ''.join(reversed(value)) d = {0: 'python', 1: 'julia', 3: 'java', 5: 'javascript'}print(toolz.dicttoolz.valmap(func, d))Output –{0: 'nohtyp', 1: 'ailuj', 3: 'avaj', 5: 'tpircsavaj'}\n"
},
{
"code": "import toolz def func(value): return ''.join(reversed(value)) d = {0: 'python', 1: 'julia', 3: 'java', 5: 'javascript'}print(toolz.dicttoolz.valmap(func, d))",
"e": 30624,
"s": 30459,
"text": null
},
{
"code": null,
"e": 30633,
"s": 30624,
"text": "Output –"
},
{
"code": null,
"e": 30688,
"s": 30633,
"text": "{0: 'nohtyp', 1: 'ailuj', 3: 'avaj', 5: 'tpircsavaj'}\n"
},
{
"code": null,
"e": 30700,
"s": 30688,
"text": "Functions –"
},
{
"code": null,
"e": 30884,
"s": 30700,
"text": "apply(*func_and_args, **kwargs) – It simply applies a function and returns the result.import toolz def double(n): return n + n print(toolz.functoolz.apply(double, 2))Output –4\n"
},
{
"code": "import toolz def double(n): return n + n print(toolz.functoolz.apply(double, 2))",
"e": 30972,
"s": 30884,
"text": null
},
{
"code": null,
"e": 30981,
"s": 30972,
"text": "Output –"
},
{
"code": null,
"e": 30984,
"s": 30981,
"text": "4\n"
},
{
"code": null,
"e": 31294,
"s": 30984,
"text": "complement(func) – As its name suggests, it converts returns the logical complement of the input provided.import toolz def is_mulitple_of_5(n): return n % 5 == 0 not_multiple_of_5 = toolz.functoolz.complement(is_mulitple_of_5) print(is_mulitple_of_5(10))print(not_multiple_of_5(10))Output –True\nFalse\n"
},
{
"code": "import toolz def is_mulitple_of_5(n): return n % 5 == 0 not_multiple_of_5 = toolz.functoolz.complement(is_mulitple_of_5) print(is_mulitple_of_5(10))print(not_multiple_of_5(10))",
"e": 31479,
"s": 31294,
"text": null
},
{
"code": null,
"e": 31488,
"s": 31479,
"text": "Output –"
},
{
"code": null,
"e": 31500,
"s": 31488,
"text": "True\nFalse\n"
},
{
"code": null,
"e": 31841,
"s": 31500,
"text": "compose(*funcs) – It returns a function that applies other functions in sequence. Functions are applied from right to left. If no arguments are provided, the identity function (f(x) = x) is returned.import toolz def func(n): return n + n def square(n): return n * n x = toolz.functoolz.compose(func, square)(3)print(x)Output –18\n"
},
{
"code": "import toolz def func(n): return n + n def square(n): return n * n x = toolz.functoolz.compose(func, square)(3)print(x)",
"e": 31972,
"s": 31841,
"text": null
},
{
"code": null,
"e": 31981,
"s": 31972,
"text": "Output –"
},
{
"code": null,
"e": 31985,
"s": 31981,
"text": "18\n"
},
{
"code": null,
"e": 32336,
"s": 31985,
"text": "compose_left(*funcs) – It returns a function that applies other functions in sequence. Functions are applied from left to right. If no arguments are provided, the identity function (f(x) = x) is returned.import toolz def func(n): return n + n def square(n): return n * n x = toolz.functoolz.compose_left(func, square)(3)print(x)Output –36\n"
},
{
"code": "import toolz def func(n): return n + n def square(n): return n * n x = toolz.functoolz.compose_left(func, square)(3)print(x)",
"e": 32472,
"s": 32336,
"text": null
},
{
"code": null,
"e": 32481,
"s": 32472,
"text": "Output –"
},
{
"code": null,
"e": 32485,
"s": 32481,
"text": "36\n"
},
{
"code": null,
"e": 32662,
"s": 32485,
"text": "flip – Call the function with the arguments in reverse order.import toolz def mod(a, b): return a % b print('7 % 3 :', toolz.functoolz.flip(mod, 3, 7))Output –7 % 3 : 1\n"
},
{
"code": "import toolz def mod(a, b): return a % b print('7 % 3 :', toolz.functoolz.flip(mod, 3, 7))",
"e": 32760,
"s": 32662,
"text": null
},
{
"code": null,
"e": 32769,
"s": 32760,
"text": "Output –"
},
{
"code": null,
"e": 32780,
"s": 32769,
"text": "7 % 3 : 1\n"
},
{
"code": null,
"e": 32891,
"s": 32780,
"text": "identity(x) – Identity function, simply returns x.import toolz print(toolz.functoolz.identity(6))Output –6\n"
},
{
"code": "import toolz print(toolz.functoolz.identity(6))",
"e": 32942,
"s": 32891,
"text": null
},
{
"code": null,
"e": 32951,
"s": 32942,
"text": "Output –"
},
{
"code": null,
"e": 32954,
"s": 32951,
"text": "6\n"
},
{
"code": null,
"e": 33135,
"s": 32954,
"text": "pipe(data, *funcs) – Pipe a value through a sequence of functions. It is equivalent to compose_left(*funcs)import toolz print(toolz.functoolz.pipe(3, double, square))Output –36\n"
},
{
"code": "import toolz print(toolz.functoolz.pipe(3, double, square))",
"e": 33198,
"s": 33135,
"text": null
},
{
"code": null,
"e": 33207,
"s": 33198,
"text": "Output –"
},
{
"code": null,
"e": 33211,
"s": 33207,
"text": "36\n"
},
{
"code": null,
"e": 33437,
"s": 33211,
"text": "thread_first(val, *forms) – Thread value through a sequence of functions/forms.import toolz def mod(a, b): return a % b def double(n): return n + n print(toolz.functoolz.thread_first(3, (mod, 2), double))Output –2\n"
},
{
"code": "import toolz def mod(a, b): return a % b def double(n): return n + n print(toolz.functoolz.thread_first(3, (mod, 2), double))",
"e": 33574,
"s": 33437,
"text": null
},
{
"code": null,
"e": 33583,
"s": 33574,
"text": "Output –"
},
{
"code": null,
"e": 33586,
"s": 33583,
"text": "2\n"
},
{
"code": null,
"e": 33810,
"s": 33586,
"text": "thread_last(val, *forms) – Thread value through a sequence of functions/forms.import toolz def mod(a, b): return a % b def double(n): return n + n print(toolz.functoolz.thread_last(3, (mod, 2), double))Output –4\n"
},
{
"code": "import toolz def mod(a, b): return a % b def double(n): return n + n print(toolz.functoolz.thread_last(3, (mod, 2), double))",
"e": 33946,
"s": 33810,
"text": null
},
{
"code": null,
"e": 33955,
"s": 33946,
"text": "Output –"
},
{
"code": null,
"e": 33958,
"s": 33955,
"text": "4\n"
},
{
"code": null,
"e": 33970,
"s": 33958,
"text": "Functions –"
},
{
"code": null,
"e": 34231,
"s": 33970,
"text": "accumulate(binop, seq[, initial]) – This is similar to ‘reduce’ function. It repeatedly applies a function to a sequence accumulating results.import toolzfrom operator import add print(list(toolz.itertoolz.accumulate(add, [1, 2, 3, 4])))Output –[1, 3, 6, 10]\n"
},
{
"code": "import toolzfrom operator import add print(list(toolz.itertoolz.accumulate(add, [1, 2, 3, 4])))",
"e": 34328,
"s": 34231,
"text": null
},
{
"code": null,
"e": 34337,
"s": 34328,
"text": "Output –"
},
{
"code": null,
"e": 34352,
"s": 34337,
"text": "[1, 3, 6, 10]\n"
},
{
"code": null,
"e": 34574,
"s": 34352,
"text": "concat(seqs) – It concatenates two or more iterables.import toolz print(list(toolz.itertoolz.concat([[1], ['a'], [2, 3, 4]])))Output –[1, 'a', 2, 3, 4]\n"
},
{
"code": "import toolz print(list(toolz.itertoolz.concat([[1], ['a'], [2, 3, 4]])))",
"e": 34717,
"s": 34574,
"text": null
},
{
"code": null,
"e": 34726,
"s": 34717,
"text": "Output –"
},
{
"code": null,
"e": 34745,
"s": 34726,
"text": "[1, 'a', 2, 3, 4]\n"
},
{
"code": null,
"e": 34931,
"s": 34745,
"text": "cons(item, seq) – It adds ‘item’ in the beginning of sequence. It is equivalent to insert(0, item).import toolz print(list(toolz.itertoolz.cons(1, ['a', 'b'])))Output –[1, 'a', 'b']\n"
},
{
"code": "import toolz print(list(toolz.itertoolz.cons(1, ['a', 'b'])))",
"e": 34996,
"s": 34931,
"text": null
},
{
"code": null,
"e": 35005,
"s": 34996,
"text": "Output –"
},
{
"code": null,
"e": 35020,
"s": 35005,
"text": "[1, 'a', 'b']\n"
},
{
"code": null,
"e": 35239,
"s": 35020,
"text": "diff(*seqs, **kwargs) – It compares the elements at every index in both iterables and returns the list of differing pairs.import toolz print(list(toolz.itertoolz.diff([1, 2, 3], [2, 2, 4])))Output –[(1, 2), (3, 4)]\n"
},
{
"code": "import toolz print(list(toolz.itertoolz.diff([1, 2, 3], [2, 2, 4])))",
"e": 35311,
"s": 35239,
"text": null
},
{
"code": null,
"e": 35320,
"s": 35311,
"text": "Output –"
},
{
"code": null,
"e": 35338,
"s": 35320,
"text": "[(1, 2), (3, 4)]\n"
},
{
"code": null,
"e": 35513,
"s": 35338,
"text": "drop(n, seq) – It drops the first n elements of sequence and returns the new sequence.import toolz print(list(toolz.itertoolz.drop(3, [2, 3, 2, 6, 4, 7])))Output –[6, 4, 7]\n"
},
{
"code": "import toolz print(list(toolz.itertoolz.drop(3, [2, 3, 2, 6, 4, 7])))",
"e": 35584,
"s": 35513,
"text": null
},
{
"code": null,
"e": 35593,
"s": 35584,
"text": "Output –"
},
{
"code": null,
"e": 35604,
"s": 35593,
"text": "[6, 4, 7]\n"
},
{
"code": null,
"e": 36152,
"s": 35604,
"text": "frequencies(seq) – It returns a dictionary with elements and their count in sequence. It is equivalent to collections.Counter.import toolz print(toolz.itertoolz.frequencies(['c', 'b', 'c', 'b', 'd', 'e', 'h', 'h', 'b']))Output –{'c': 2, 'b': 3, 'd': 1, 'e': 1, 'h': 2}\n"
},
{
"code": "import toolz print(toolz.itertoolz.frequencies(['c', 'b', 'c', 'b', 'd', 'e', 'h', 'h', 'b']))",
"e": 36525,
"s": 36152,
"text": null
},
{
"code": null,
"e": 36534,
"s": 36525,
"text": "Output –"
},
{
"code": null,
"e": 36576,
"s": 36534,
"text": "{'c': 2, 'b': 3, 'd': 1, 'e': 1, 'h': 2}\n"
},
{
"code": null,
"e": 36827,
"s": 36576,
"text": "groupby(func, seq) – It returns a dictionary after grouping the sequence elements according to func.import toolz print(toolz.itertoolz.groupby(len, ['geeks', 'for', 'geeks']))Output –{5: ['geeks', 'geeks'], 3: ['for']}\n"
},
{
"code": "import toolz print(toolz.itertoolz.groupby(len, ['geeks', 'for', 'geeks']))",
"e": 36934,
"s": 36827,
"text": null
},
{
"code": null,
"e": 36943,
"s": 36934,
"text": "Output –"
},
{
"code": null,
"e": 36980,
"s": 36943,
"text": "{5: ['geeks', 'geeks'], 3: ['for']}\n"
},
{
"code": null,
"e": 37142,
"s": 36980,
"text": "isdistinct(seq) – It returns True if all elements in the sequence are distinct, else False.import toolz print(toolz.itertoolz.isdistinct('geeks'))Output –False\n"
},
{
"code": "import toolz print(toolz.itertoolz.isdistinct('geeks'))",
"e": 37199,
"s": 37142,
"text": null
},
{
"code": null,
"e": 37208,
"s": 37199,
"text": "Output –"
},
{
"code": null,
"e": 37215,
"s": 37208,
"text": "False\n"
},
{
"code": null,
"e": 37333,
"s": 37215,
"text": "isiterable(x) – It returns True if x is an iterable, else False.print(toolz.itertoolz.isiterable([10]))Output - True\n"
},
{
"code": "print(toolz.itertoolz.isiterable([10]))",
"e": 37373,
"s": 37333,
"text": null
},
{
"code": null,
"e": 37388,
"s": 37373,
"text": "Output - True\n"
},
{
"code": null,
"e": 37626,
"s": 37388,
"text": "interleave(seqs) – It interleaves the sequences, i.e. concatenates the sequences index-wise.import toolz print(list(toolz.itertoolz.interleave([[10, 20], [5, 8, 11]])))Output –[10, 5, 20, 8, 11]\n"
},
{
"code": "import toolz print(list(toolz.itertoolz.interleave([[10, 20], [5, 8, 11]])))",
"e": 37745,
"s": 37626,
"text": null
},
{
"code": null,
"e": 37754,
"s": 37745,
"text": "Output –"
},
{
"code": null,
"e": 37774,
"s": 37754,
"text": "[10, 5, 20, 8, 11]\n"
},
{
"code": null,
"e": 37969,
"s": 37774,
"text": "topk(k, seq[, key]) – It returns the top k largest elements of the sequence.import toolz print(list(toolz.itertoolz.topk(2, [10, 20, 5, 8, 11])))Output –[20, 11]\n"
},
{
"code": "import toolz print(list(toolz.itertoolz.topk(2, [10, 20, 5, 8, 11])))",
"e": 38071,
"s": 37969,
"text": null
},
{
"code": null,
"e": 38080,
"s": 38071,
"text": "Output –"
},
{
"code": null,
"e": 38090,
"s": 38080,
"text": "[20, 11]\n"
},
{
"code": null,
"e": 38443,
"s": 38090,
"text": "unique(seq[, key]) – It returns the distinct elements of sequence just like set(seq).import toolz print(list(toolz.itertoolz.unique([10, 20, 5, 8, 10, 20])))Output –[10, 20, 5, 8]\n"
},
{
"code": "import toolz print(list(toolz.itertoolz.unique([10, 20, 5, 8, 10, 20])))",
"e": 38688,
"s": 38443,
"text": null
},
{
"code": null,
"e": 38697,
"s": 38688,
"text": "Output –"
},
{
"code": null,
"e": 38713,
"s": 38697,
"text": "[10, 20, 5, 8]\n"
},
{
"code": null,
"e": 38984,
"s": 38713,
"text": "merge_sorted(*seqs, **kwargs) – It merges sorted iterables in such a way that the resulting collection is also sorted.import toolz print(list(toolz.itertoolz.merge_sorted([5, 10, 20], [4, 12, 24])))Output –[4, 5, 10, 12, 20, 24]\n"
},
{
"code": "import toolz print(list(toolz.itertoolz.merge_sorted([5, 10, 20], [4, 12, 24])))",
"e": 39106,
"s": 38984,
"text": null
},
{
"code": null,
"e": 39115,
"s": 39106,
"text": "Output –"
},
{
"code": null,
"e": 39139,
"s": 39115,
"text": "[4, 5, 10, 12, 20, 24]\n"
},
{
"code": null,
"e": 39437,
"s": 39139,
"text": "mapcat(func, seqs) – It applies func to each sequence and concatenates the results.import toolz print(list(toolz.itertoolz.mapcat(lambda iter: [e * 2 for e in iter], [[5, 10, 20], [4, 12, 24]])))Output –[10, 20, 40, 8, 24, 48]\n"
},
{
"code": "import toolz print(list(toolz.itertoolz.mapcat(lambda iter: [e * 2 for e in iter], [[5, 10, 20], [4, 12, 24]])))",
"e": 39620,
"s": 39437,
"text": null
},
{
"code": null,
"e": 39629,
"s": 39620,
"text": "Output –"
},
{
"code": null,
"e": 39654,
"s": 39629,
"text": "[10, 20, 40, 8, 24, 48]\n"
},
{
"code": null,
"e": 39926,
"s": 39654,
"text": "remove(predicate, seq) – It returns those elements from sequence for which predicate is False. It is complement function of filter.import toolz print(list(toolz.itertoolz.remove(lambda x: x % 2 == 0, [5, 21, 4, 12, 24])))Output –[5, 21]\n"
},
{
"code": "import toolz print(list(toolz.itertoolz.remove(lambda x: x % 2 == 0, [5, 21, 4, 12, 24])))",
"e": 40051,
"s": 39926,
"text": null
},
{
"code": null,
"e": 40060,
"s": 40051,
"text": "Output –"
},
{
"code": null,
"e": 40069,
"s": 40060,
"text": "[5, 21]\n"
},
{
"code": null,
"e": 40081,
"s": 40069,
"text": "Functions –"
},
{
"code": null,
"e": 40285,
"s": 40081,
"text": "countby(key, seq) – Count elements of a collection by a key function.import toolz def iseven(n): return n % 2 == 0 print(toolz.recipes.countby(iseven, [12, 123, 1234]))Output –{True: 2, False: 1}\n"
},
{
"code": "import toolz def iseven(n): return n % 2 == 0 print(toolz.recipes.countby(iseven, [12, 123, 1234]))",
"e": 40392,
"s": 40285,
"text": null
},
{
"code": null,
"e": 40401,
"s": 40392,
"text": "Output –"
},
{
"code": null,
"e": 40422,
"s": 40401,
"text": "{True: 2, False: 1}\n"
},
{
"code": null,
"e": 40733,
"s": 40422,
"text": "partitionby(func, seq) – Partition a sequence according to a given function.import toolz def iseven(n): return n % 2 == 0 print(list(toolz.recipes.partitionby(iseven, [12, 123, 31, 1234])))Output –[(12, ), (123, 31), (1234, )]\n"
},
{
"code": "import toolz def iseven(n): return n % 2 == 0 print(list(toolz.recipes.partitionby(iseven, [12, 123, 31, 1234])))",
"e": 40930,
"s": 40733,
"text": null
},
{
"code": null,
"e": 40939,
"s": 40930,
"text": "Output –"
},
{
"code": null,
"e": 40970,
"s": 40939,
"text": "[(12, ), (123, 31), (1234, )]\n"
},
{
"code": null,
"e": 40982,
"s": 40970,
"text": "Functions –"
},
{
"code": null,
"e": 41186,
"s": 40982,
"text": "parallel.fold(binop, seq[, default, map, ...] – Reduce without guarantee of ordered reduction.import toolz def sum(a, b): return a + b print(toolz.sandbox.parallel.fold(sum, [1, 2, 3, 4]))Output –10"
},
{
"code": "import toolz def sum(a, b): return a + b print(toolz.sandbox.parallel.fold(sum, [1, 2, 3, 4]))",
"e": 41286,
"s": 41186,
"text": null
},
{
"code": null,
"e": 41295,
"s": 41286,
"text": "Output –"
},
{
"code": null,
"e": 41298,
"s": 41295,
"text": "10"
},
{
"code": null,
"e": 41563,
"s": 41298,
"text": "core.unzip(seq) – Inverse of zip.import toolz l1, l2 = toolz.sandbox.core.unzip([(0, 1), (1, 2), (2, 3)]) print(list(l1), list(l2))Output –[0, 1, 2] [1, 2, 3]\nMy Personal Notes\narrow_drop_upSave"
},
{
"code": "import toolz l1, l2 = toolz.sandbox.core.unzip([(0, 1), (1, 2), (2, 3)]) print(list(l1), list(l2))",
"e": 41732,
"s": 41563,
"text": null
},
{
"code": null,
"e": 41741,
"s": 41732,
"text": "Output –"
},
{
"code": null,
"e": 41762,
"s": 41741,
"text": "[0, 1, 2] [1, 2, 3]\n"
},
{
"code": null,
"e": 41777,
"s": 41762,
"text": "python-modules"
},
{
"code": null,
"e": 41784,
"s": 41777,
"text": "Python"
},
{
"code": null,
"e": 41882,
"s": 41784,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41891,
"s": 41882,
"text": "Comments"
},
{
"code": null,
"e": 41904,
"s": 41891,
"text": "Old Comments"
},
{
"code": null,
"e": 41936,
"s": 41904,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 41992,
"s": 41936,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 42013,
"s": 41992,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 42052,
"s": 42013,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 42094,
"s": 42052,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 42121,
"s": 42094,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 42152,
"s": 42121,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 42194,
"s": 42152,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 42230,
"s": 42194,
"text": "Python | Pandas dataframe.groupby()"
}
] |
How to add a rounded border with CSS ? - GeeksforGeeks
|
23 Sep, 2020
The purpose of this article is to add a rounded border to a HTML element by using the border-radius property in CSS. It is used to round the corner of an element. The property sets the border-radius for the element.
Syntax:
border-radius: 1-4 length|% / 1-4 length|%|initial|inherit
Example:
<!DOCTYPE html><html> <head> <style> .GFG { border-radius: 75px 75px; background: blue; padding: 16px; text-align: center; width: 300px; height: 120px; } </style></head> <body> <center> <h1> GeeksForGeeks </h1> <h2> How to add a rounded border with css ? </h2> <div class="GFG"> <h4> Rounded corners Borders </h4> </div> </center></body> </html>
Output:
Supported Browsers:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set input type date in dd-mm-yyyy format using HTML ?
HTML | <img> align Attribute
Form validation using HTML and JavaScript
How to set the default value for an HTML <select> element ?
|
[
{
"code": null,
"e": 24985,
"s": 24957,
"text": "\n23 Sep, 2020"
},
{
"code": null,
"e": 25201,
"s": 24985,
"text": "The purpose of this article is to add a rounded border to a HTML element by using the border-radius property in CSS. It is used to round the corner of an element. The property sets the border-radius for the element."
},
{
"code": null,
"e": 25209,
"s": 25201,
"text": "Syntax:"
},
{
"code": null,
"e": 25268,
"s": 25209,
"text": "border-radius: 1-4 length|% / 1-4 length|%|initial|inherit"
},
{
"code": null,
"e": 25277,
"s": 25268,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <style> .GFG { border-radius: 75px 75px; background: blue; padding: 16px; text-align: center; width: 300px; height: 120px; } </style></head> <body> <center> <h1> GeeksForGeeks </h1> <h2> How to add a rounded border with css ? </h2> <div class=\"GFG\"> <h4> Rounded corners Borders </h4> </div> </center></body> </html> ",
"e": 25834,
"s": 25277,
"text": null
},
{
"code": null,
"e": 25842,
"s": 25834,
"text": "Output:"
},
{
"code": null,
"e": 25862,
"s": 25842,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 25876,
"s": 25862,
"text": "Google Chrome"
},
{
"code": null,
"e": 25894,
"s": 25876,
"text": "Internet Explorer"
},
{
"code": null,
"e": 25902,
"s": 25894,
"text": "Firefox"
},
{
"code": null,
"e": 25908,
"s": 25902,
"text": "Opera"
},
{
"code": null,
"e": 25915,
"s": 25908,
"text": "Safari"
},
{
"code": null,
"e": 26052,
"s": 25915,
"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": 26061,
"s": 26052,
"text": "CSS-Misc"
},
{
"code": null,
"e": 26071,
"s": 26061,
"text": "HTML-Misc"
},
{
"code": null,
"e": 26075,
"s": 26071,
"text": "CSS"
},
{
"code": null,
"e": 26080,
"s": 26075,
"text": "HTML"
},
{
"code": null,
"e": 26097,
"s": 26080,
"text": "Web Technologies"
},
{
"code": null,
"e": 26102,
"s": 26097,
"text": "HTML"
},
{
"code": null,
"e": 26200,
"s": 26102,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26209,
"s": 26200,
"text": "Comments"
},
{
"code": null,
"e": 26222,
"s": 26209,
"text": "Old Comments"
},
{
"code": null,
"e": 26259,
"s": 26222,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 26288,
"s": 26259,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 26327,
"s": 26288,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 26369,
"s": 26327,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 26404,
"s": 26369,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 26465,
"s": 26404,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 26494,
"s": 26465,
"text": "HTML | <img> align Attribute"
},
{
"code": null,
"e": 26536,
"s": 26494,
"text": "Form validation using HTML and JavaScript"
}
] |
Program to find covariance - GeeksforGeeks
|
24 Nov, 2021
Given a two set of random variable, find Covariance. Covariance is a measure of how much two random variables vary together. It’s similar to variance, but where variance tells you how a single variable varies, covariance tells you how two variables vary together. Covariance can be calculated by using the formula Where x’ and y’ are the means of two given sets.
Examples:
Input : arr1[] = {65.21, 64.75, 65.26, 65.76, 65.96}
arr2[] = {67.25, 66.39, 66.12, 65.70, 66.64}
Output : -0.0580511
Input : arr1[] = {5, 20, 40, 80, 100}
arr2[] = {10, 24, 33, 54, 10}
Output : 187.75
C++
Java
Python3
C#
PHP
Javascript
// C++ Program to find// covariance of two set.#include<bits/stdc++.h>using namespace std; // Function to find mean.float mean(float arr[], int n){ float sum = 0; for(int i = 0; i < n; i++) sum = sum + arr[i]; return sum / n;} // Function to find covariance.float covariance(float arr1[], float arr2[], int n){ float sum = 0; float mean_arr1 = mean(arr1,n); float mean_arr2 = mean(arr2,n); for(int i = 0; i < n; i++) sum = sum + (arr1[i] - mean_arr1) * (arr2[i] - mean_arr2); return sum / (n - 1);} // Driver function.int main(){ float arr1[] = {65.21, 64.75, 65.26, 65.76, 65.96}; int n = sizeof(arr1) / sizeof(arr1[0]); float arr2[] = {67.25, 66.39, 66.12, 65.70, 66.64}; int m = sizeof(arr2) / sizeof(arr2[0]); if (m == n) cout << covariance(arr1, arr2, m); return 0;}
// Java Program to find// covariance of two set.import java.io.*; class GFG { // Function to find mean.static float mean(float arr[], int n){ float sum = 0; for(int i = 0; i < n; i++) sum = sum + arr[i]; return sum / n;} // Function to find covariance.static float covariance(float arr1[], float arr2[], int n){ float sum = 0; float mean_arr1 = mean(arr1,n); float mean_arr2 = mean(arr2,n); for(int i = 0; i < n; i++) sum = sum + (arr1[i] - mean_arr1) * (arr2[i] - mean_arr2); return sum / (n - 1);} // Driver code public static void main (String[] args) { float arr1[] = {65.21f, 64.75f, 65.26f, 65.76f, 65.96f}; int n = arr1.length; float arr2[] = {67.25f, 66.39f, 66.12f, 65.70f, 66.64f}; int m = arr2.length; if (m == n) System.out.println(covariance(arr1, arr2, m)); }} // This code is contributed by Gitanjali.
# Python3 Program to find# covariance of two set.import math # Function to find mean. def mean(arr, n): sum = 0 for i in range(0, n): sum = sum + arr[i] return sum / n # Function to find covariance. def covariance(arr1, arr2, n): sum = 0 mean_arr1 = mean(arr1, n) mean_arr2 = mean(arr2, n) for i in range(0, n): sum = (sum + (arr1[i] - mean_arr1) * (arr2[i] - mean_arr2)) return sum / (n - 1) # Driver methodarr1 = [65.21, 64.75, 65.26, 65.76, 65.96]n = len(arr1) arr2 = [67.25, 66.39, 66.12, 65.70, 66.64]m = len(arr2) if (m == n): print(covariance(arr1, arr2, m)) # This code is contributed by Gitanjali.
// C# Program to find// covariance of two set.using System; class GFG { // Function to find mean. static float mean(float []arr, int n) { float sum = 0; for(int i = 0; i < n; i++) sum = sum + arr[i]; return sum / n; } // Function to find covariance. static float covariance(float []arr1, float []arr2, int n) { float sum = 0; float mean_arr1 = mean(arr1,n); float mean_arr2 = mean(arr2,n); for(int i = 0; i < n; i++) sum = sum + (arr1[i] - mean_arr1) * (arr2[i] - mean_arr2); return sum / (n - 1); } // Driver code public static void Main () { float []arr1 = {65.21f, 64.75f, 65.26f, 65.76f, 65.96f}; int n = arr1.Length; float []arr2 = {67.25f, 66.39f, 66.12f, 65.70f, 66.64f}; int m = arr2.Length; if (m == n) Console.WriteLine(covariance(arr1, arr2, m)); }} // This code is contributed by vt_m.
<?php// PHP Program to find// covariance of two set. // Function to find mean.function mean( $arr, $n){ $sum = 0; for( $i = 0; $i < $n; $i++) $sum = $sum + $arr[$i]; return $sum / $n;} // Function to find covariance.function covariance( $arr1, $arr2, $n){ $sum = 0; $mean_arr1 = mean($arr1,$n); $mean_arr2 = mean($arr2,$n); for( $i = 0; $i < $n; $i++) $sum = $sum + ($arr1[$i] - $mean_arr1) * ($arr2[$i] - $mean_arr2); return $sum / ($n - 1);} // Driver function.$arr1 = array(65.21, 64.75, 65.26, 65.76, 65.96);$n = count($arr1); $arr2 = array(67.25, 66.39, 66.12, 65.70, 66.64);$m =count($arr2); if ($m == $n) echo covariance($arr1, $arr2, $m); // This code is contributed by anuj_67.?>
<script> // Javascript program to find// covariance of two set. // Function to find mean.function mean(arr, n){ let sum = 0; for(let i = 0; i < n; i++) sum = sum + arr[i]; return sum / n;} // Function to find covariance.function covariance(arr1, arr2, n){ let sum = 0; let mean_arr1 = mean(arr1, n); let mean_arr2 = mean(arr2, n); for(let i = 0; i < n; i++) sum = sum + (arr1[i] - mean_arr1) * (arr2[i] - mean_arr2); return sum / (n - 1);} // Driver codelet arr1 = [ 65.21, 64.75, 65.26, 65.76, 65.96 ];let n = arr1.length; let arr2 = [ 67.25, 66.39, 66.12, 65.70, 66.64 ];let m = arr2.length; if (m == n) document.write(covariance(arr1, arr2, m)); // This code is contributed by souravmahato348 </script>
Output:
-0.0580511
Time Complexity: O(N)Auxiliary Space: O(1)
vt_m
souravmahato348
pankajsharmagfg
ashutoshsinghgeeksforgeeks
statistical-algorithms
Algorithms
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Introduction to Algorithms
Playfair Cipher with Examples
How to write a Pseudo Code?
Recursive Practice Problems with Solutions
K means Clustering - Introduction
Converting Roman Numerals to Decimal lying between 1 to 3999
SCAN (Elevator) Disk Scheduling Algorithms
Difference Between Symmetric and Asymmetric Key Encryption
|
[
{
"code": null,
"e": 24697,
"s": 24669,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 25060,
"s": 24697,
"text": "Given a two set of random variable, find Covariance. Covariance is a measure of how much two random variables vary together. It’s similar to variance, but where variance tells you how a single variable varies, covariance tells you how two variables vary together. Covariance can be calculated by using the formula Where x’ and y’ are the means of two given sets."
},
{
"code": null,
"e": 25071,
"s": 25060,
"text": "Examples: "
},
{
"code": null,
"e": 25290,
"s": 25071,
"text": "Input : arr1[] = {65.21, 64.75, 65.26, 65.76, 65.96}\n arr2[] = {67.25, 66.39, 66.12, 65.70, 66.64}\nOutput : -0.0580511\n\nInput : arr1[] = {5, 20, 40, 80, 100}\n arr2[] = {10, 24, 33, 54, 10}\nOutput : 187.75"
},
{
"code": null,
"e": 25294,
"s": 25290,
"text": "C++"
},
{
"code": null,
"e": 25299,
"s": 25294,
"text": "Java"
},
{
"code": null,
"e": 25307,
"s": 25299,
"text": "Python3"
},
{
"code": null,
"e": 25310,
"s": 25307,
"text": "C#"
},
{
"code": null,
"e": 25314,
"s": 25310,
"text": "PHP"
},
{
"code": null,
"e": 25325,
"s": 25314,
"text": "Javascript"
},
{
"code": "// C++ Program to find// covariance of two set.#include<bits/stdc++.h>using namespace std; // Function to find mean.float mean(float arr[], int n){ float sum = 0; for(int i = 0; i < n; i++) sum = sum + arr[i]; return sum / n;} // Function to find covariance.float covariance(float arr1[], float arr2[], int n){ float sum = 0; float mean_arr1 = mean(arr1,n); float mean_arr2 = mean(arr2,n); for(int i = 0; i < n; i++) sum = sum + (arr1[i] - mean_arr1) * (arr2[i] - mean_arr2); return sum / (n - 1);} // Driver function.int main(){ float arr1[] = {65.21, 64.75, 65.26, 65.76, 65.96}; int n = sizeof(arr1) / sizeof(arr1[0]); float arr2[] = {67.25, 66.39, 66.12, 65.70, 66.64}; int m = sizeof(arr2) / sizeof(arr2[0]); if (m == n) cout << covariance(arr1, arr2, m); return 0;}",
"e": 26193,
"s": 25325,
"text": null
},
{
"code": "// Java Program to find// covariance of two set.import java.io.*; class GFG { // Function to find mean.static float mean(float arr[], int n){ float sum = 0; for(int i = 0; i < n; i++) sum = sum + arr[i]; return sum / n;} // Function to find covariance.static float covariance(float arr1[], float arr2[], int n){ float sum = 0; float mean_arr1 = mean(arr1,n); float mean_arr2 = mean(arr2,n); for(int i = 0; i < n; i++) sum = sum + (arr1[i] - mean_arr1) * (arr2[i] - mean_arr2); return sum / (n - 1);} // Driver code public static void main (String[] args) { float arr1[] = {65.21f, 64.75f, 65.26f, 65.76f, 65.96f}; int n = arr1.length; float arr2[] = {67.25f, 66.39f, 66.12f, 65.70f, 66.64f}; int m = arr2.length; if (m == n) System.out.println(covariance(arr1, arr2, m)); }} // This code is contributed by Gitanjali.",
"e": 27191,
"s": 26193,
"text": null
},
{
"code": "# Python3 Program to find# covariance of two set.import math # Function to find mean. def mean(arr, n): sum = 0 for i in range(0, n): sum = sum + arr[i] return sum / n # Function to find covariance. def covariance(arr1, arr2, n): sum = 0 mean_arr1 = mean(arr1, n) mean_arr2 = mean(arr2, n) for i in range(0, n): sum = (sum + (arr1[i] - mean_arr1) * (arr2[i] - mean_arr2)) return sum / (n - 1) # Driver methodarr1 = [65.21, 64.75, 65.26, 65.76, 65.96]n = len(arr1) arr2 = [67.25, 66.39, 66.12, 65.70, 66.64]m = len(arr2) if (m == n): print(covariance(arr1, arr2, m)) # This code is contributed by Gitanjali.",
"e": 27860,
"s": 27191,
"text": null
},
{
"code": "// C# Program to find// covariance of two set.using System; class GFG { // Function to find mean. static float mean(float []arr, int n) { float sum = 0; for(int i = 0; i < n; i++) sum = sum + arr[i]; return sum / n; } // Function to find covariance. static float covariance(float []arr1, float []arr2, int n) { float sum = 0; float mean_arr1 = mean(arr1,n); float mean_arr2 = mean(arr2,n); for(int i = 0; i < n; i++) sum = sum + (arr1[i] - mean_arr1) * (arr2[i] - mean_arr2); return sum / (n - 1); } // Driver code public static void Main () { float []arr1 = {65.21f, 64.75f, 65.26f, 65.76f, 65.96f}; int n = arr1.Length; float []arr2 = {67.25f, 66.39f, 66.12f, 65.70f, 66.64f}; int m = arr2.Length; if (m == n) Console.WriteLine(covariance(arr1, arr2, m)); }} // This code is contributed by vt_m.",
"e": 28977,
"s": 27860,
"text": null
},
{
"code": "<?php// PHP Program to find// covariance of two set. // Function to find mean.function mean( $arr, $n){ $sum = 0; for( $i = 0; $i < $n; $i++) $sum = $sum + $arr[$i]; return $sum / $n;} // Function to find covariance.function covariance( $arr1, $arr2, $n){ $sum = 0; $mean_arr1 = mean($arr1,$n); $mean_arr2 = mean($arr2,$n); for( $i = 0; $i < $n; $i++) $sum = $sum + ($arr1[$i] - $mean_arr1) * ($arr2[$i] - $mean_arr2); return $sum / ($n - 1);} // Driver function.$arr1 = array(65.21, 64.75, 65.26, 65.76, 65.96);$n = count($arr1); $arr2 = array(67.25, 66.39, 66.12, 65.70, 66.64);$m =count($arr2); if ($m == $n) echo covariance($arr1, $arr2, $m); // This code is contributed by anuj_67.?>",
"e": 29817,
"s": 28977,
"text": null
},
{
"code": "<script> // Javascript program to find// covariance of two set. // Function to find mean.function mean(arr, n){ let sum = 0; for(let i = 0; i < n; i++) sum = sum + arr[i]; return sum / n;} // Function to find covariance.function covariance(arr1, arr2, n){ let sum = 0; let mean_arr1 = mean(arr1, n); let mean_arr2 = mean(arr2, n); for(let i = 0; i < n; i++) sum = sum + (arr1[i] - mean_arr1) * (arr2[i] - mean_arr2); return sum / (n - 1);} // Driver codelet arr1 = [ 65.21, 64.75, 65.26, 65.76, 65.96 ];let n = arr1.length; let arr2 = [ 67.25, 66.39, 66.12, 65.70, 66.64 ];let m = arr2.length; if (m == n) document.write(covariance(arr1, arr2, m)); // This code is contributed by souravmahato348 </script>",
"e": 30618,
"s": 29817,
"text": null
},
{
"code": null,
"e": 30627,
"s": 30618,
"text": "Output: "
},
{
"code": null,
"e": 30638,
"s": 30627,
"text": "-0.0580511"
},
{
"code": null,
"e": 30683,
"s": 30638,
"text": "Time Complexity: O(N)Auxiliary Space: O(1) "
},
{
"code": null,
"e": 30688,
"s": 30683,
"text": "vt_m"
},
{
"code": null,
"e": 30704,
"s": 30688,
"text": "souravmahato348"
},
{
"code": null,
"e": 30720,
"s": 30704,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 30747,
"s": 30720,
"text": "ashutoshsinghgeeksforgeeks"
},
{
"code": null,
"e": 30770,
"s": 30747,
"text": "statistical-algorithms"
},
{
"code": null,
"e": 30781,
"s": 30770,
"text": "Algorithms"
},
{
"code": null,
"e": 30792,
"s": 30781,
"text": "Algorithms"
},
{
"code": null,
"e": 30890,
"s": 30792,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30899,
"s": 30890,
"text": "Comments"
},
{
"code": null,
"e": 30912,
"s": 30899,
"text": "Old Comments"
},
{
"code": null,
"e": 30961,
"s": 30912,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 30986,
"s": 30961,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 31013,
"s": 30986,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 31043,
"s": 31013,
"text": "Playfair Cipher with Examples"
},
{
"code": null,
"e": 31071,
"s": 31043,
"text": "How to write a Pseudo Code?"
},
{
"code": null,
"e": 31114,
"s": 31071,
"text": "Recursive Practice Problems with Solutions"
},
{
"code": null,
"e": 31148,
"s": 31114,
"text": "K means Clustering - Introduction"
},
{
"code": null,
"e": 31209,
"s": 31148,
"text": "Converting Roman Numerals to Decimal lying between 1 to 3999"
},
{
"code": null,
"e": 31252,
"s": 31209,
"text": "SCAN (Elevator) Disk Scheduling Algorithms"
}
] |
NHibernate - QueryOver Queries
|
In this chapter, we will be covering QueryOver Queries. It is a new syntax which is more like LINQ using the method chain syntax as shown in the following query.
var customers = session.QueryOver<Customer>() .Where(x => x.FirstName == "Laverne");
It is still criteria under the covers, but now our queries are strongly typed.
It is still criteria under the covers, but now our queries are strongly typed.
As we have seen in the criteria query, the first name is just an opaque string, now we're actually using an x.FirstName, so the first name gets refactored and renamed that gets changed in the link style criteria query using the query over.
As we have seen in the criteria query, the first name is just an opaque string, now we're actually using an x.FirstName, so the first name gets refactored and renamed that gets changed in the link style criteria query using the query over.
We can still do many similar things, but you cannot use the query comprehension syntax with query over, you have to use the method chain syntax and you can't mix and match the link and the criteria.
We can still do many similar things, but you cannot use the query comprehension syntax with query over, you have to use the method chain syntax and you can't mix and match the link and the criteria.
For a lot of queries, the query over API is very useful and provides a much easier to comprehend object syntax than using Criteria directly.
For a lot of queries, the query over API is very useful and provides a much easier to comprehend object syntax than using Criteria directly.
Let’s have a look into a simple example in which we will retrieve a customer whose first name is Laverne using a query over.
using System;
using System.Data;
using System.Linq;
using System.Reflection;
using HibernatingRhinos.Profiler.Appender.NHibernate;
using NHibernate.Cfg;
using NHibernate.Criterion;
using NHibernate.Dialect;
using NHibernate.Driver;
using NHibernate.Linq;
namespace NHibernateDemo {
internal class Program {
private static void Main() {
var cfg = ConfigureNHibernate();
var sessionFactory = cfg.BuildSessionFactory();
using(var session = sessionFactory.OpenSession())
using(var tx = session.BeginTransaction()) {
var customers = session.QueryOver<Customer>()
.Where(x => x.FirstName == "Laverne");
foreach (var customer in customers.List()) {
Console.WriteLine(customer);
}
tx.Commit();
}
Console.WriteLine("Press <ENTER> to exit...");
Console.ReadLine();
}
private static Configuration ConfigureNHibernate() {
NHibernateProfiler.Initialize();
var cfg = new Configuration();
cfg.DataBaseIntegration(x => {
x.ConnectionStringName = "default";
x.Driver<SqlClientDriver>();
x.Dialect<MsSql2008Dialect>();
x.IsolationLevel = IsolationLevel.RepeatableRead;
x.Timeout = 10;
x.BatchSize = 10;
});
cfg.SessionFactory().GenerateStatistics();
cfg.AddAssembly(Assembly.GetExecutingAssembly());
return cfg;
}
}
}
As you can see that it is still Criteria underneath the covers, but is just a nicer syntax.
When the above code is compiled and executed, you will see the following output.
Laverne Hegmann (4e97c816-6bce-11e1-b095-6cf049ee52be)
Points: 74
HasGoldStatus: True
MemberSince: 4/4/2009 12:00:00 AM (Utc)
CreditRating: Neutral
AverageRating: 0
Orders:
Order Id: 4ea14d96-6bce-11e1-b095-6cf049ee52be
Order Id: 4ea14d96-6bce-11e1-b096-6cf049ee52be
Order Id: 4ea14d96-6bce-11e1-b097-6cf049ee52be
Order Id: 4ea14d96-6bce-11e1-b098-6cf049ee52be
Press <ENTER> to exit...
One of the disadvantages is that, let's say we want to say that FirstName.StartsWith(“A”) as shown in the following program.
var customers = session.QueryOver<Customer>() .Where(x => x.FirstName.StartsWith("A"));
foreach (var customer in customers.List()) {
Console.WriteLine(customer);
}
tx.Commit();
Now let’s run the application again and you will see that this is not a LINQ provider as it doesn't know what this StartsWith method is, so you will get a RunTime exception.
The exception says unrecognized method call. Here we are doing the obvious thing, but it doesn't necessarily work.
Let's try something else, like FirstName is equal to “A%” as shown in the following code.
var customers = session.QueryOver<Customer>() .Where(x => x.FirstName == "A%");
foreach (var customer in customers.List()) {
Console.WriteLine(customer);
}
Let’s run this once again and you will see that we're not going to get any results back as shown below.
Press <ENTER> to exit...
To understand this why we are not getting any results, let’s have a look at NHibernate profiler.
As you can see that the first name is equal to A% which is not. A% is used in SQL using with the like operator. Now we need to create a restriction into WHERE clause as shown in the following program.
var customers = session.QueryOver<Customer>()
.Where(Restrictions.On<Customer>(c => c.FirstName).IsLike("A%"));
foreach (var customer in customers.List()) {
Console.WriteLine(customer);
}
Let’s run your application again and you will see that all the customers are retrieved with first name starts with A.
Alejandrin Will (4ea3aef6-6bce-11e1-b0b4-6cf049ee52be)
Points: 24
HasGoldStatus: False
MemberSince: 10/1/2011 12:00:00 AM (Utc)
CreditRating: VeryVeryGood
AverageRating: 0
Orders:
Order Id: 4ea3aef6-6bce-11e1-b0b5-6cf049ee52be
Austyn Nolan (4ea871b6-6bce-11e1-b110-6cf049ee52be)
Points: 67
HasGoldStatus: True
MemberSince: 12/29/2007 12:00:00 AM (Utc)
CreditRating: Neutral
AverageRating: 0
Orders:
Order Id: 4ea871b6-6bce-11e1-b111-6cf049ee52be
Antonia Murphy (4ea871b6-6bce-11e1-b121-6cf049ee52be)
Points: 72
HasGoldStatus: True
MemberSince: 6/15/2009 12:00:00 AM (Utc)
CreditRating: Terrible
AverageRating: 0
Orders:
Order Id: 4ea871b6-6bce-11e1-b122-6cf049ee52be
Order Id: 4ea871b6-6bce-11e1-b123-6cf049ee52be
Order Id: 4ea871b6-6bce-11e1-b124-6cf049ee52be
Order Id: 4ea871b6-6bce-11e1-b125-6cf049ee52be
Order Id: 4ea871b6-6bce-11e1-b126-6cf049ee52be
Order Id: 4ea871b6-6bce-11e1-b127-6cf049ee52be
Order Id: 4ea871b6-6bce-11e1-b128-6cf049ee52be
Order Id: 4ea871b6-6bce-11e1-b129-6cf049ee52be
Order Id: 4ea871b6-6bce-11e1-b12a-6cf049ee52be
It works the same way as it did before, except using this new QueryOver syntax. Many developers find that LINQ syntax is more approachable and often does the right things.
If LINQ can't handle it, then you will start looking at HQL or Criteria to see if that's going to be more suitable.
It just gives you a different syntax, so Criteria, both the create criteria and the QueryOver provide you just yet another querying mechanism that allows you to pull data out of the database using NHibernate.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2495,
"s": 2333,
"text": "In this chapter, we will be covering QueryOver Queries. It is a new syntax which is more like LINQ using the method chain syntax as shown in the following query."
},
{
"code": null,
"e": 2581,
"s": 2495,
"text": "var customers = session.QueryOver<Customer>() .Where(x => x.FirstName == \"Laverne\");\n"
},
{
"code": null,
"e": 2660,
"s": 2581,
"text": "It is still criteria under the covers, but now our queries are strongly typed."
},
{
"code": null,
"e": 2739,
"s": 2660,
"text": "It is still criteria under the covers, but now our queries are strongly typed."
},
{
"code": null,
"e": 2979,
"s": 2739,
"text": "As we have seen in the criteria query, the first name is just an opaque string, now we're actually using an x.FirstName, so the first name gets refactored and renamed that gets changed in the link style criteria query using the query over."
},
{
"code": null,
"e": 3219,
"s": 2979,
"text": "As we have seen in the criteria query, the first name is just an opaque string, now we're actually using an x.FirstName, so the first name gets refactored and renamed that gets changed in the link style criteria query using the query over."
},
{
"code": null,
"e": 3418,
"s": 3219,
"text": "We can still do many similar things, but you cannot use the query comprehension syntax with query over, you have to use the method chain syntax and you can't mix and match the link and the criteria."
},
{
"code": null,
"e": 3617,
"s": 3418,
"text": "We can still do many similar things, but you cannot use the query comprehension syntax with query over, you have to use the method chain syntax and you can't mix and match the link and the criteria."
},
{
"code": null,
"e": 3758,
"s": 3617,
"text": "For a lot of queries, the query over API is very useful and provides a much easier to comprehend object syntax than using Criteria directly."
},
{
"code": null,
"e": 3899,
"s": 3758,
"text": "For a lot of queries, the query over API is very useful and provides a much easier to comprehend object syntax than using Criteria directly."
},
{
"code": null,
"e": 4024,
"s": 3899,
"text": "Let’s have a look into a simple example in which we will retrieve a customer whose first name is Laverne using a query over."
},
{
"code": null,
"e": 5635,
"s": 4024,
"text": "using System; \nusing System.Data; \nusing System.Linq; \nusing System.Reflection; \n\nusing HibernatingRhinos.Profiler.Appender.NHibernate; \nusing NHibernate.Cfg; \nusing NHibernate.Criterion; \nusing NHibernate.Dialect; \nusing NHibernate.Driver; \nusing NHibernate.Linq;\n\nnamespace NHibernateDemo { \n\n internal class Program { \n \n private static void Main() { \n\t\t\n var cfg = ConfigureNHibernate(); \n var sessionFactory = cfg.BuildSessionFactory();\n using(var session = sessionFactory.OpenSession()) \n \n using(var tx = session.BeginTransaction()) { \n var customers = session.QueryOver<Customer>() \n .Where(x => x.FirstName == \"Laverne\"); \n \n foreach (var customer in customers.List()) { \n Console.WriteLine(customer); \n } \n\t\t\t\t\n tx.Commit(); \n }\n\t\t\t\n Console.WriteLine(\"Press <ENTER> to exit...\"); \n Console.ReadLine(); \n }\n \n private static Configuration ConfigureNHibernate() { \n\t\t\n NHibernateProfiler.Initialize();\n var cfg = new Configuration(); \n \n cfg.DataBaseIntegration(x => { \n x.ConnectionStringName = \"default\"; \n x.Driver<SqlClientDriver>(); \n x.Dialect<MsSql2008Dialect>(); \n x.IsolationLevel = IsolationLevel.RepeatableRead; \n x.Timeout = 10; \n x.BatchSize = 10; \n });\n\t\t\t\n cfg.SessionFactory().GenerateStatistics();\n cfg.AddAssembly(Assembly.GetExecutingAssembly()); \n return cfg; \n } \n } \n}"
},
{
"code": null,
"e": 5727,
"s": 5635,
"text": "As you can see that it is still Criteria underneath the covers, but is just a nicer syntax."
},
{
"code": null,
"e": 5808,
"s": 5727,
"text": "When the above code is compiled and executed, you will see the following output."
},
{
"code": null,
"e": 6241,
"s": 5808,
"text": "Laverne Hegmann (4e97c816-6bce-11e1-b095-6cf049ee52be)\n Points: 74\n HasGoldStatus: True\n MemberSince: 4/4/2009 12:00:00 AM (Utc)\n CreditRating: Neutral\n AverageRating: 0\n\n Orders:\n Order Id: 4ea14d96-6bce-11e1-b095-6cf049ee52be\n Order Id: 4ea14d96-6bce-11e1-b096-6cf049ee52be\n Order Id: 4ea14d96-6bce-11e1-b097-6cf049ee52be\n Order Id: 4ea14d96-6bce-11e1-b098-6cf049ee52be\n\t\t\nPress <ENTER> to exit...\n"
},
{
"code": null,
"e": 6366,
"s": 6241,
"text": "One of the disadvantages is that, let's say we want to say that FirstName.StartsWith(“A”) as shown in the following program."
},
{
"code": null,
"e": 6552,
"s": 6366,
"text": "var customers = session.QueryOver<Customer>() .Where(x => x.FirstName.StartsWith(\"A\"));\n \nforeach (var customer in customers.List()) { \n Console.WriteLine(customer); \n} \n\ntx.Commit();"
},
{
"code": null,
"e": 6726,
"s": 6552,
"text": "Now let’s run the application again and you will see that this is not a LINQ provider as it doesn't know what this StartsWith method is, so you will get a RunTime exception."
},
{
"code": null,
"e": 6841,
"s": 6726,
"text": "The exception says unrecognized method call. Here we are doing the obvious thing, but it doesn't necessarily work."
},
{
"code": null,
"e": 6931,
"s": 6841,
"text": "Let's try something else, like FirstName is equal to “A%” as shown in the following code."
},
{
"code": null,
"e": 7094,
"s": 6931,
"text": "var customers = session.QueryOver<Customer>() .Where(x => x.FirstName == \"A%\"); \n\nforeach (var customer in customers.List()) { \n Console.WriteLine(customer); \n}"
},
{
"code": null,
"e": 7198,
"s": 7094,
"text": "Let’s run this once again and you will see that we're not going to get any results back as shown below."
},
{
"code": null,
"e": 7224,
"s": 7198,
"text": "Press <ENTER> to exit...\n"
},
{
"code": null,
"e": 7321,
"s": 7224,
"text": "To understand this why we are not getting any results, let’s have a look at NHibernate profiler."
},
{
"code": null,
"e": 7522,
"s": 7321,
"text": "As you can see that the first name is equal to A% which is not. A% is used in SQL using with the like operator. Now we need to create a restriction into WHERE clause as shown in the following program."
},
{
"code": null,
"e": 7722,
"s": 7522,
"text": "var customers = session.QueryOver<Customer>() \n .Where(Restrictions.On<Customer>(c => c.FirstName).IsLike(\"A%\")); \n\t\nforeach (var customer in customers.List()) { \n Console.WriteLine(customer); \n}"
},
{
"code": null,
"e": 7840,
"s": 7722,
"text": "Let’s run your application again and you will see that all the customers are retrieved with first name starts with A."
},
{
"code": null,
"e": 9009,
"s": 7840,
"text": "Alejandrin Will (4ea3aef6-6bce-11e1-b0b4-6cf049ee52be)\n Points: 24\n HasGoldStatus: False\n MemberSince: 10/1/2011 12:00:00 AM (Utc)\n CreditRating: VeryVeryGood\n AverageRating: 0\n\n Orders:\n Order Id: 4ea3aef6-6bce-11e1-b0b5-6cf049ee52be\n\nAustyn Nolan (4ea871b6-6bce-11e1-b110-6cf049ee52be)\n Points: 67\n HasGoldStatus: True\n MemberSince: 12/29/2007 12:00:00 AM (Utc)\n CreditRating: Neutral\n AverageRating: 0\n\n Orders:\n Order Id: 4ea871b6-6bce-11e1-b111-6cf049ee52be\n\nAntonia Murphy (4ea871b6-6bce-11e1-b121-6cf049ee52be)\n Points: 72\n HasGoldStatus: True\n MemberSince: 6/15/2009 12:00:00 AM (Utc)\n CreditRating: Terrible\n AverageRating: 0\n\n Orders:\n Order Id: 4ea871b6-6bce-11e1-b122-6cf049ee52be\n Order Id: 4ea871b6-6bce-11e1-b123-6cf049ee52be\n Order Id: 4ea871b6-6bce-11e1-b124-6cf049ee52be\n Order Id: 4ea871b6-6bce-11e1-b125-6cf049ee52be\n Order Id: 4ea871b6-6bce-11e1-b126-6cf049ee52be\n Order Id: 4ea871b6-6bce-11e1-b127-6cf049ee52be\n Order Id: 4ea871b6-6bce-11e1-b128-6cf049ee52be\n Order Id: 4ea871b6-6bce-11e1-b129-6cf049ee52be\n Order Id: 4ea871b6-6bce-11e1-b12a-6cf049ee52be\n"
},
{
"code": null,
"e": 9181,
"s": 9009,
"text": "It works the same way as it did before, except using this new QueryOver syntax. Many developers find that LINQ syntax is more approachable and often does the right things."
},
{
"code": null,
"e": 9297,
"s": 9181,
"text": "If LINQ can't handle it, then you will start looking at HQL or Criteria to see if that's going to be more suitable."
},
{
"code": null,
"e": 9506,
"s": 9297,
"text": "It just gives you a different syntax, so Criteria, both the create criteria and the QueryOver provide you just yet another querying mechanism that allows you to pull data out of the database using NHibernate."
},
{
"code": null,
"e": 9513,
"s": 9506,
"text": " Print"
},
{
"code": null,
"e": 9524,
"s": 9513,
"text": " Add Notes"
}
] |
Select parent element of known element in Selenium.
|
We can select the parent element of a known element with Selenium webdriver. First of all we have to identify the known element with the help of any of the locators like id, classname and so on. Then we have to identify its parent element with findElement(By.xpath()) method.
We can identify the parent element from its child by localizing it with the child and then passing ( ./..) as a parameter to the findElement(By.xpath()). Let us identify the parent element with tagname ul from the child element with the tagname li in below html code −
Also we can identify the parent element of a known element with the help of Javascript Executor. We have to pass the Javascript command return arguments[0].parentNode and the webelement as parameters to the method executeScript. The parentNode command in Javascript is used to point to the parent of an element.
Code Implementation with xpath
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class ParentElement{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
// identify element
WebElement c=driver.findElement(By.xpath("//li[@class='heading']"));
//identify parent element with ./.. expression in xpath
WebElement p = c.findElement(By.xpath("./.."));
//getTagName to get tagname of parent
System.out.println("Parent tagname is: " + p.getTagName());
driver.close();
}
}
Code Implementation with Javascript Executor.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class ParentElementJS{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
// identify element
WebElement c=driver.findElement(By.xpath("//li[@class='heading']"));
//identify parent element parentNode expression in Javascript command
WebElement p = (WebElement) ((JavascriptExecutor) driver).executeScript( "return arguments[0].parentNode;", c);
//getTagName to get tagname of parent
System.out.println("Parent tagname is: " + p.getTagName());
driver.close();
}
}
|
[
{
"code": null,
"e": 1338,
"s": 1062,
"text": "We can select the parent element of a known element with Selenium webdriver. First of all we have to identify the known element with the help of any of the locators like id, classname and so on. Then we have to identify its parent element with findElement(By.xpath()) method."
},
{
"code": null,
"e": 1607,
"s": 1338,
"text": "We can identify the parent element from its child by localizing it with the child and then passing ( ./..) as a parameter to the findElement(By.xpath()). Let us identify the parent element with tagname ul from the child element with the tagname li in below html code −"
},
{
"code": null,
"e": 1919,
"s": 1607,
"text": "Also we can identify the parent element of a known element with the help of Javascript Executor. We have to pass the Javascript command return arguments[0].parentNode and the webelement as parameters to the method executeScript. The parentNode command in Javascript is used to point to the parent of an element."
},
{
"code": null,
"e": 1950,
"s": 1919,
"text": "Code Implementation with xpath"
},
{
"code": null,
"e": 2871,
"s": 1950,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\npublic class ParentElement{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n driver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\");\n // identify element\n WebElement c=driver.findElement(By.xpath(\"//li[@class='heading']\"));\n //identify parent element with ./.. expression in xpath\n WebElement p = c.findElement(By.xpath(\"./..\"));\n //getTagName to get tagname of parent\n System.out.println(\"Parent tagname is: \" + p.getTagName());\n driver.close();\n }\n}"
},
{
"code": null,
"e": 2917,
"s": 2871,
"text": "Code Implementation with Javascript Executor."
},
{
"code": null,
"e": 3965,
"s": 2917,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport org.openqa.selenium.JavascriptExecutor;\npublic class ParentElementJS{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n driver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\");\n // identify element\n WebElement c=driver.findElement(By.xpath(\"//li[@class='heading']\"));\n //identify parent element parentNode expression in Javascript command\n WebElement p = (WebElement) ((JavascriptExecutor) driver).executeScript( \"return arguments[0].parentNode;\", c);\n //getTagName to get tagname of parent\n System.out.println(\"Parent tagname is: \" + p.getTagName());\n driver.close();\n }\n}"
}
] |
Image Data Labelling and Annotation — Everything you need to know | by Sabina Pokhrel | Towards Data Science
|
Data labelling is an essential step in a supervised machine learning task. Garbage In Garbage Out is a phrase commonly used in the machine learning community, which means that the quality of the training data determines the quality of the model. The same is true for annotations used for data labelling. If you show a child a tomato and say its a potato, the next time the child sees a tomato, it is very likely that he classifies it as a potato. As a machine learning model learns in a similar way, by looking at examples, the result of the model depends on the labels we feed in during its training phase.
Data labelling is a task that requires a lot of manual work. If you can find a good open dataset for your project, that is labelled, LUCK IS ON YOUR SIDE! But mostly, this is not the case. It is very likely that you will have to go through the process of data annotation by yourself.
In this post, we will look at the types of annotation for images, commonly used annotation format and some tools that you can use for image data labelling.
Before jumping into image annotations, it is useful to know about the different annotation types that exist so that you pick the right type for your use-case.
Here are a few different types of annotations:
Bounding boxes: Bounding boxes are the most commonly used type of annotation in computer vision. Bounding boxes are rectangular boxes used to define the location of the target object. They can be determined by the x and y axis coordinates in the upper-left corner and the x and y axis coordinates in the lower-right corner of the rectangle. Bounding boxes are generally used in object detection and localisation tasks.
Bounding boxes are usually represented by either two coordinates (x1, y1) and (x2, y2) or by one co-ordinate (x1, y1) and width (w) and height (h) of the bounding box. (See image below)
Polygonal Segmentation: Objects are not always rectangle in shape. With this idea, polygonal segmentations is another type of data annotation where complex polygons are used instead of rectangles to define the shape and location of the object in a much precise way.
Semantic Segmentation: Semantic segmentation is a pixel wise annotation, where every pixel in the image is assigned to a class. These classes could be pedestrian, car, bus, road, sidewalk, etc., and each pixel carry a semantic meaning.
Semantic Segmentation is primarily used in cases where environmental context is very important. For example, it is used in self-driving cars and robotics because for the models to understand the environment they are operating in.
3D cuboids: 3D cuboids are similar to bounding boxes with additional depth information about the object. Thus, with 3D cuboids you can get a 3D representation of the object, allowing systems to distinguish features like volume and position in a 3D space.
A use-case of 3D cuboids is in self-driving cars where it can use the depth information to measure the distance of objects from the car.
Key-Point and Landmark: Key-point and landmark annotation is used to detect small objects and shape variations by creating dots across the image. This type of annotation is useful for detecting facial features, facial expressions, emotions, human body parts and poses.
Lines and Splines: As the name suggests, this type is annotation is created by using lines and splines. It is commonly used in autonomous vehicles for lane detection and recognition.
There is no single standard format when it comes to image annotation. Below are few commonly used annotation formats:
COCO: COCO has five annotation types: for object detection, keypoint detection, stuff segmentation, panoptic segmentation, and image captioning. The annotations are stored using JSON.
For object detection, COCO follows the following format:
annotation{"id" : int,"image_id": int,"category_id": int,"segmentation": RLE or [polygon],"area": float,"bbox": [x,y,width,height],"iscrowd": 0 or 1,}categories[{"id": int,"name": str,"supercategory": str,}]
Pascal VOC: Pascal VOC stores annotation in XML file. Below is an example of Pascal VOC annotation file for object detection.
<annotation> <folder>Train</folder> <filename>01.png</filename> <path>/path/Train/01.png</path> <source> <database>Unknown</database> </source> <size> <width>224</width> <height>224</height> <depth>3</depth> </size> <segmented>0</segmented> <object> <name>36</name> <pose>Frontal</pose> <truncated>0</truncated> <difficult>0</difficult> <occluded>0</occluded> <bndbox> <xmin>90</xmin> <xmax>190</xmax> <ymin>54</ymin> <ymax>70</ymax> </bndbox> </object></annotation>
YOLO: In YOLO labeling format, a .txt file with the same name is created for each image file in the same directory. Each .txt file contains the annotations for the corresponding image file, that is object class, object coordinates, height and width.
<object-class> <x> <y> <width> <height>
For each object, a new line is created.
Below is an example of annotation in YOLO format where the image contains two different objects.
0 45 55 29 671 99 83 28 44
Here is a list of tools that you can use for annotating images:
MakeSense.AILabelImgVGG image annotatorLabelMeScalableRectLabel
MakeSense.AI
LabelImg
VGG image annotator
LabelMe
Scalable
RectLabel
In this post, we covered what data annotation/labelling is and why it is important for machine learning. We looked at 6 different types of annotations of images: bounding boxes, Polygonal Segmentation, Semantic Segmentation, 3D cuboids, Key-Point and Landmark, and Lines and Splines, and 3 different annotation formats: COCO, Pascal VOC and YOLO. We also listed a few image annotation tools that are available.
In the next post, we will cover how to annotate image data in detail.
Stay tuned!
What image annotation type do you commonly use? Which format do you use for annotating your image? Leave your thoughts as comments below.
Originally published in www.xailient.com/blog.
Looking for a pre-trained face detection model. Click here to download.
Check-out this post for more details on creating a robust object detection model.
References:
hackernoon.com
hackernoon.com
lionbridge.ai
About the author
Sabina Pokhrel works at Xailient, a computer-vision start-up that has built the world’s fastest Edge-optimized object detector.
|
[
{
"code": null,
"e": 780,
"s": 172,
"text": "Data labelling is an essential step in a supervised machine learning task. Garbage In Garbage Out is a phrase commonly used in the machine learning community, which means that the quality of the training data determines the quality of the model. The same is true for annotations used for data labelling. If you show a child a tomato and say its a potato, the next time the child sees a tomato, it is very likely that he classifies it as a potato. As a machine learning model learns in a similar way, by looking at examples, the result of the model depends on the labels we feed in during its training phase."
},
{
"code": null,
"e": 1064,
"s": 780,
"text": "Data labelling is a task that requires a lot of manual work. If you can find a good open dataset for your project, that is labelled, LUCK IS ON YOUR SIDE! But mostly, this is not the case. It is very likely that you will have to go through the process of data annotation by yourself."
},
{
"code": null,
"e": 1220,
"s": 1064,
"text": "In this post, we will look at the types of annotation for images, commonly used annotation format and some tools that you can use for image data labelling."
},
{
"code": null,
"e": 1379,
"s": 1220,
"text": "Before jumping into image annotations, it is useful to know about the different annotation types that exist so that you pick the right type for your use-case."
},
{
"code": null,
"e": 1426,
"s": 1379,
"text": "Here are a few different types of annotations:"
},
{
"code": null,
"e": 1845,
"s": 1426,
"text": "Bounding boxes: Bounding boxes are the most commonly used type of annotation in computer vision. Bounding boxes are rectangular boxes used to define the location of the target object. They can be determined by the x and y axis coordinates in the upper-left corner and the x and y axis coordinates in the lower-right corner of the rectangle. Bounding boxes are generally used in object detection and localisation tasks."
},
{
"code": null,
"e": 2031,
"s": 1845,
"text": "Bounding boxes are usually represented by either two coordinates (x1, y1) and (x2, y2) or by one co-ordinate (x1, y1) and width (w) and height (h) of the bounding box. (See image below)"
},
{
"code": null,
"e": 2297,
"s": 2031,
"text": "Polygonal Segmentation: Objects are not always rectangle in shape. With this idea, polygonal segmentations is another type of data annotation where complex polygons are used instead of rectangles to define the shape and location of the object in a much precise way."
},
{
"code": null,
"e": 2533,
"s": 2297,
"text": "Semantic Segmentation: Semantic segmentation is a pixel wise annotation, where every pixel in the image is assigned to a class. These classes could be pedestrian, car, bus, road, sidewalk, etc., and each pixel carry a semantic meaning."
},
{
"code": null,
"e": 2763,
"s": 2533,
"text": "Semantic Segmentation is primarily used in cases where environmental context is very important. For example, it is used in self-driving cars and robotics because for the models to understand the environment they are operating in."
},
{
"code": null,
"e": 3018,
"s": 2763,
"text": "3D cuboids: 3D cuboids are similar to bounding boxes with additional depth information about the object. Thus, with 3D cuboids you can get a 3D representation of the object, allowing systems to distinguish features like volume and position in a 3D space."
},
{
"code": null,
"e": 3155,
"s": 3018,
"text": "A use-case of 3D cuboids is in self-driving cars where it can use the depth information to measure the distance of objects from the car."
},
{
"code": null,
"e": 3424,
"s": 3155,
"text": "Key-Point and Landmark: Key-point and landmark annotation is used to detect small objects and shape variations by creating dots across the image. This type of annotation is useful for detecting facial features, facial expressions, emotions, human body parts and poses."
},
{
"code": null,
"e": 3607,
"s": 3424,
"text": "Lines and Splines: As the name suggests, this type is annotation is created by using lines and splines. It is commonly used in autonomous vehicles for lane detection and recognition."
},
{
"code": null,
"e": 3725,
"s": 3607,
"text": "There is no single standard format when it comes to image annotation. Below are few commonly used annotation formats:"
},
{
"code": null,
"e": 3909,
"s": 3725,
"text": "COCO: COCO has five annotation types: for object detection, keypoint detection, stuff segmentation, panoptic segmentation, and image captioning. The annotations are stored using JSON."
},
{
"code": null,
"e": 3966,
"s": 3909,
"text": "For object detection, COCO follows the following format:"
},
{
"code": null,
"e": 4174,
"s": 3966,
"text": "annotation{\"id\" : int,\"image_id\": int,\"category_id\": int,\"segmentation\": RLE or [polygon],\"area\": float,\"bbox\": [x,y,width,height],\"iscrowd\": 0 or 1,}categories[{\"id\": int,\"name\": str,\"supercategory\": str,}]"
},
{
"code": null,
"e": 4300,
"s": 4174,
"text": "Pascal VOC: Pascal VOC stores annotation in XML file. Below is an example of Pascal VOC annotation file for object detection."
},
{
"code": null,
"e": 4880,
"s": 4300,
"text": "<annotation> <folder>Train</folder> <filename>01.png</filename> <path>/path/Train/01.png</path> <source> <database>Unknown</database> </source> <size> <width>224</width> <height>224</height> <depth>3</depth> </size> <segmented>0</segmented> <object> <name>36</name> <pose>Frontal</pose> <truncated>0</truncated> <difficult>0</difficult> <occluded>0</occluded> <bndbox> <xmin>90</xmin> <xmax>190</xmax> <ymin>54</ymin> <ymax>70</ymax> </bndbox> </object></annotation>"
},
{
"code": null,
"e": 5130,
"s": 4880,
"text": "YOLO: In YOLO labeling format, a .txt file with the same name is created for each image file in the same directory. Each .txt file contains the annotations for the corresponding image file, that is object class, object coordinates, height and width."
},
{
"code": null,
"e": 5170,
"s": 5130,
"text": "<object-class> <x> <y> <width> <height>"
},
{
"code": null,
"e": 5210,
"s": 5170,
"text": "For each object, a new line is created."
},
{
"code": null,
"e": 5307,
"s": 5210,
"text": "Below is an example of annotation in YOLO format where the image contains two different objects."
},
{
"code": null,
"e": 5334,
"s": 5307,
"text": "0 45 55 29 671 99 83 28 44"
},
{
"code": null,
"e": 5398,
"s": 5334,
"text": "Here is a list of tools that you can use for annotating images:"
},
{
"code": null,
"e": 5462,
"s": 5398,
"text": "MakeSense.AILabelImgVGG image annotatorLabelMeScalableRectLabel"
},
{
"code": null,
"e": 5475,
"s": 5462,
"text": "MakeSense.AI"
},
{
"code": null,
"e": 5484,
"s": 5475,
"text": "LabelImg"
},
{
"code": null,
"e": 5504,
"s": 5484,
"text": "VGG image annotator"
},
{
"code": null,
"e": 5512,
"s": 5504,
"text": "LabelMe"
},
{
"code": null,
"e": 5521,
"s": 5512,
"text": "Scalable"
},
{
"code": null,
"e": 5531,
"s": 5521,
"text": "RectLabel"
},
{
"code": null,
"e": 5942,
"s": 5531,
"text": "In this post, we covered what data annotation/labelling is and why it is important for machine learning. We looked at 6 different types of annotations of images: bounding boxes, Polygonal Segmentation, Semantic Segmentation, 3D cuboids, Key-Point and Landmark, and Lines and Splines, and 3 different annotation formats: COCO, Pascal VOC and YOLO. We also listed a few image annotation tools that are available."
},
{
"code": null,
"e": 6012,
"s": 5942,
"text": "In the next post, we will cover how to annotate image data in detail."
},
{
"code": null,
"e": 6024,
"s": 6012,
"text": "Stay tuned!"
},
{
"code": null,
"e": 6162,
"s": 6024,
"text": "What image annotation type do you commonly use? Which format do you use for annotating your image? Leave your thoughts as comments below."
},
{
"code": null,
"e": 6209,
"s": 6162,
"text": "Originally published in www.xailient.com/blog."
},
{
"code": null,
"e": 6281,
"s": 6209,
"text": "Looking for a pre-trained face detection model. Click here to download."
},
{
"code": null,
"e": 6363,
"s": 6281,
"text": "Check-out this post for more details on creating a robust object detection model."
},
{
"code": null,
"e": 6375,
"s": 6363,
"text": "References:"
},
{
"code": null,
"e": 6390,
"s": 6375,
"text": "hackernoon.com"
},
{
"code": null,
"e": 6405,
"s": 6390,
"text": "hackernoon.com"
},
{
"code": null,
"e": 6419,
"s": 6405,
"text": "lionbridge.ai"
},
{
"code": null,
"e": 6436,
"s": 6419,
"text": "About the author"
}
] |
How to set the layout weight of a textview programmatically in Android?
|
This example demonstrates how do I set the layout weight of a textView programmatically 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:gravity="center"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:onClick="expand"
android:textSize="24sp"
android:text="Hello World"
android:layout_centerInParent="true"/>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity {
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void expand(View view) {
int height = RelativeLayout.LayoutParams.MATCH_PARENT;
int width = 500;
RelativeLayout.LayoutParams layoutParams= new RelativeLayout.LayoutParams(width,height);
button = findViewById(R.id.button);
button.setLayoutParams(layoutParams);
}
}
Step 4 - Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code.
|
[
{
"code": null,
"e": 1162,
"s": 1062,
"text": "This example demonstrates how do I set the layout weight of a textView programmatically in android."
},
{
"code": null,
"e": 1291,
"s": 1162,
"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": 1356,
"s": 1291,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1940,
"s": 1356,
"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:gravity=\"center\"\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:textStyle=\"bold\"\n android:onClick=\"expand\"\n android:textSize=\"24sp\"\n android:text=\"Hello World\"\n android:layout_centerInParent=\"true\"/>\n</RelativeLayout>"
},
{
"code": null,
"e": 1997,
"s": 1940,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2707,
"s": 1997,
"text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.RelativeLayout;\npublic class MainActivity extends AppCompatActivity {\n Button button;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n public void expand(View view) {\n int height = RelativeLayout.LayoutParams.MATCH_PARENT;\n int width = 500;\n RelativeLayout.LayoutParams layoutParams= new RelativeLayout.LayoutParams(width,height);\n button = findViewById(R.id.button);\n button.setLayoutParams(layoutParams);\n }\n}"
},
{
"code": null,
"e": 2762,
"s": 2707,
"text": "Step 4 - Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3435,
"s": 2762,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest 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 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": 3782,
"s": 3435,
"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": 3823,
"s": 3782,
"text": "Click here to download the project code."
}
] |
Angular 2 - Navigation
|
In Angular 2, it is also possible to carry out manual navigation. Following are the steps.
Step 1 − Add the following code to the Inventory.component.ts file.
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component ({
selector: 'my-app',
template: 'Inventory
<a class = "button" (click) = "onBack()">Back to Products</a>'
})
export class AppInventory {
constructor(private _router: Router){}
onBack(): void {
this._router.navigate(['/Product']);
}
}
The following points need to be noted about the above program −
Declare an html tag which has an onBack function tagged to the click event. Thus, when a user clicks this, they will be directed back to the Products page.
Declare an html tag which has an onBack function tagged to the click event. Thus, when a user clicks this, they will be directed back to the Products page.
In the onBack function, use the router.navigate to navigate to the required page.
In the onBack function, use the router.navigate to navigate to the required page.
Step 2 − Now, save all the code and run the application using npm. Go to the browser, you will see the following output.
Step 3 − Click the Inventory link.
Step 4 − Click the ‘Back to products’ link, you will get the following output which takes you back to the Products page.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2388,
"s": 2297,
"text": "In Angular 2, it is also possible to carry out manual navigation. Following are the steps."
},
{
"code": null,
"e": 2456,
"s": 2388,
"text": "Step 1 − Add the following code to the Inventory.component.ts file."
},
{
"code": null,
"e": 2832,
"s": 2456,
"text": "import { Component } from '@angular/core'; \nimport { Router } from '@angular/router'; \n\n@Component ({ \n selector: 'my-app', \n template: 'Inventory \n <a class = \"button\" (click) = \"onBack()\">Back to Products</a>' \n}) \n\nexport class AppInventory { \n constructor(private _router: Router){} \n\n onBack(): void { \n this._router.navigate(['/Product']); \n } \n}"
},
{
"code": null,
"e": 2896,
"s": 2832,
"text": "The following points need to be noted about the above program −"
},
{
"code": null,
"e": 3052,
"s": 2896,
"text": "Declare an html tag which has an onBack function tagged to the click event. Thus, when a user clicks this, they will be directed back to the Products page."
},
{
"code": null,
"e": 3208,
"s": 3052,
"text": "Declare an html tag which has an onBack function tagged to the click event. Thus, when a user clicks this, they will be directed back to the Products page."
},
{
"code": null,
"e": 3290,
"s": 3208,
"text": "In the onBack function, use the router.navigate to navigate to the required page."
},
{
"code": null,
"e": 3372,
"s": 3290,
"text": "In the onBack function, use the router.navigate to navigate to the required page."
},
{
"code": null,
"e": 3493,
"s": 3372,
"text": "Step 2 − Now, save all the code and run the application using npm. Go to the browser, you will see the following output."
},
{
"code": null,
"e": 3528,
"s": 3493,
"text": "Step 3 − Click the Inventory link."
},
{
"code": null,
"e": 3649,
"s": 3528,
"text": "Step 4 − Click the ‘Back to products’ link, you will get the following output which takes you back to the Products page."
},
{
"code": null,
"e": 3684,
"s": 3649,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3698,
"s": 3684,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3733,
"s": 3698,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3747,
"s": 3733,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3782,
"s": 3747,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 3802,
"s": 3782,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 3837,
"s": 3802,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3854,
"s": 3837,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3887,
"s": 3854,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3899,
"s": 3887,
"text": " Senol Atac"
},
{
"code": null,
"e": 3934,
"s": 3899,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3946,
"s": 3934,
"text": " Senol Atac"
},
{
"code": null,
"e": 3953,
"s": 3946,
"text": " Print"
},
{
"code": null,
"e": 3964,
"s": 3953,
"text": " Add Notes"
}
] |
How to find the first date of a given year using Python?
|
In this program, we have to print the first day of the year. We have to take a year as a user input.
Step 1: Import the datetime library.
Step 2: Take year as input from the user.
Step 3: Get the first day of the year by passing month, day and year as parameters to the datetime.datetime() function
Step 4: Display the first day using strftime() function.
Live Demo
import datetime
year = int(input("Enter year: "))
firstday = datetime.datetime(year, 1,1)
print("First Day of ", year, " = ", firstday.strftime("%A"))
First Day of 2021 = Friday
|
[
{
"code": null,
"e": 1163,
"s": 1062,
"text": "In this program, we have to print the first day of the year. We have to take a year as a user input."
},
{
"code": null,
"e": 1418,
"s": 1163,
"text": "Step 1: Import the datetime library.\nStep 2: Take year as input from the user.\nStep 3: Get the first day of the year by passing month, day and year as parameters to the datetime.datetime() function\nStep 4: Display the first day using strftime() function."
},
{
"code": null,
"e": 1428,
"s": 1418,
"text": "Live Demo"
},
{
"code": null,
"e": 1579,
"s": 1428,
"text": "import datetime\nyear = int(input(\"Enter year: \"))\nfirstday = datetime.datetime(year, 1,1)\nprint(\"First Day of \", year, \" = \", firstday.strftime(\"%A\"))"
},
{
"code": null,
"e": 1609,
"s": 1579,
"text": "First Day of 2021 = Friday"
}
] |
Python - API.retweets() in Tweepy - GeeksforGeeks
|
05 Jun, 2020
Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication.
The API.retweets() method of the API class in Tweepy module is used to return a list of retweets of a tweet.
Syntax : API.retweets(parameters)
Parameters :
id : The ID of the tweet which has to be retweeted.
count : The number of retweets to be retrieved.
Returns : a list of objects of the class Status
Example 1 : List of users who retweeted the following tweet :
# import the moduleimport tweepy # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = "" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # the ID of the tweetID = 1265889240300257280 # getting the retweetersretweets_list = api.retweets(ID) # printing the screen names of the retweetersfor retweet in retweets_list: print(retweet.user.screen_name)
Output :
harshitabambure
codedailybot
UVahalkar
codedailybot
ProjectLearn_io
codedailybot
ryokugyu_
AaronCuddeback
strong>Example 2 : Using the retweets() method with count parameter to only fetch a certain number of retweets. Print the screen names of only 3 retweeters of the following tweet :
# the ID of the tweetID = 1263387365051183107 # number to retweets to be retrievedcount = 3 # getting the retweetersretweets_list = api.retweets(ID, count) # printing the screen names of the retweetersfor retweet in retweets_list: print(retweet.user.screen_name)
Output :
murali_ch
sushmitaraj13
rgsharma_me
Python-Tweepy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
Selecting rows in pandas DataFrame based on conditions
|
[
{
"code": null,
"e": 24366,
"s": 24338,
"text": "\n05 Jun, 2020"
},
{
"code": null,
"e": 24766,
"s": 24366,
"text": "Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication."
},
{
"code": null,
"e": 24875,
"s": 24766,
"text": "The API.retweets() method of the API class in Tweepy module is used to return a list of retweets of a tweet."
},
{
"code": null,
"e": 24909,
"s": 24875,
"text": "Syntax : API.retweets(parameters)"
},
{
"code": null,
"e": 24922,
"s": 24909,
"text": "Parameters :"
},
{
"code": null,
"e": 24974,
"s": 24922,
"text": "id : The ID of the tweet which has to be retweeted."
},
{
"code": null,
"e": 25022,
"s": 24974,
"text": "count : The number of retweets to be retrieved."
},
{
"code": null,
"e": 25070,
"s": 25022,
"text": "Returns : a list of objects of the class Status"
},
{
"code": null,
"e": 25132,
"s": 25070,
"text": "Example 1 : List of users who retweeted the following tweet :"
},
{
"code": "# import the moduleimport tweepy # assign the values accordinglyconsumer_key = \"\"consumer_secret = \"\"access_token = \"\"access_token_secret = \"\" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # the ID of the tweetID = 1265889240300257280 # getting the retweetersretweets_list = api.retweets(ID) # printing the screen names of the retweetersfor retweet in retweets_list: print(retweet.user.screen_name)",
"e": 25754,
"s": 25132,
"text": null
},
{
"code": null,
"e": 25763,
"s": 25754,
"text": "Output :"
},
{
"code": null,
"e": 25870,
"s": 25763,
"text": "harshitabambure\ncodedailybot\nUVahalkar\ncodedailybot\nProjectLearn_io\ncodedailybot\nryokugyu_\nAaronCuddeback\n"
},
{
"code": null,
"e": 26051,
"s": 25870,
"text": "strong>Example 2 : Using the retweets() method with count parameter to only fetch a certain number of retweets. Print the screen names of only 3 retweeters of the following tweet :"
},
{
"code": "# the ID of the tweetID = 1263387365051183107 # number to retweets to be retrievedcount = 3 # getting the retweetersretweets_list = api.retweets(ID, count) # printing the screen names of the retweetersfor retweet in retweets_list: print(retweet.user.screen_name)",
"e": 26320,
"s": 26051,
"text": null
},
{
"code": null,
"e": 26329,
"s": 26320,
"text": "Output :"
},
{
"code": null,
"e": 26366,
"s": 26329,
"text": "murali_ch\nsushmitaraj13\nrgsharma_me\n"
},
{
"code": null,
"e": 26380,
"s": 26366,
"text": "Python-Tweepy"
},
{
"code": null,
"e": 26387,
"s": 26380,
"text": "Python"
},
{
"code": null,
"e": 26485,
"s": 26387,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26494,
"s": 26485,
"text": "Comments"
},
{
"code": null,
"e": 26507,
"s": 26494,
"text": "Old Comments"
},
{
"code": null,
"e": 26525,
"s": 26507,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26560,
"s": 26525,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26582,
"s": 26560,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26612,
"s": 26582,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26644,
"s": 26612,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26686,
"s": 26644,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26712,
"s": 26686,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26749,
"s": 26712,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26793,
"s": 26749,
"text": "Reading and Writing to text files in Python"
}
] |
Audio Context.close() in Web APIs - GeeksforGeeks
|
07 Sep, 2021
Web Audio APIs help to make the audio of a website application sound correct. Sounds make the site more fun and attractive. Using Audio APIs, many music or sound applications can be built. In this article, we will learn about audiocontext.close() along with some basic information about Audio APIs.
Audio Context is an object that is used to do various manipulations in the audio for the website or application. It is a pre-built function that can be used on various browsers like google and Firefox Before making changes to any audio the source of the audio has to be stored. There are 3 major types of audio sources.
Oscillator: it is used to produce a mathematically computed sounds
Audio Samples: to get audio from various files
Audio stream: getting audio from webcam or microphone
After the audio is been streamed by using either of the sources, one can either emphasize or attenuate the parts of audio by using different nodes. After the node functions are performed the audio is connected to the destination and then the sound is played. Some of the different nodes are Filter,ChannelSpiltterNode,AudioWorkletNode,etc...
AudioContext.close(): This audio context function can close the audiocontext and thereby detaching any hardware resources associated with the audiocontent. i.e. the function doesn’t further take/give any inputs to the sound device. But the already stored audio before using close() can be manipulated. This is very meaningful in low power devices like mobile. If the audiocontext stays on the device’s resources stay on and thus causing the power loss.
Syntax:
// Declaring audiocontext constructor
var audioContext=new AudioContext();
audioContext.close().then(function()
{.
.
. });
await audioContext.close()
Example: In the following code, a small HTML page is created with 3 buttons. Clicking on each button performs respective functions related to the audio. In the example, the audio can be started and the stopped,i.e, resume. Note that the resume is different from a stop as resuming the audio means temporarily pausing the audio and restart from where it was stopped. Whereas stopping the audio using close() completely removes the audio from the sound devices and setting the state as beginning state.
Javascript
<!DOCTYPE html><html> <head> <meta charset="utf-8" /> <title>states</title> <link rel="stylesheet" href="" /> <style> body { background: lightcoral; color: #323232; font-weight: 300; height: 100vh; margin: 0; display: flex; align-items: center; justify-content: center; text-align: center; font-family: Helvetica neue, roboto; } .button:hover { background-color: aquamarine; } .btn-group .button { background-color: bisque; border: 1px solid black; color: black; padding: 15px 32px; text-align: center; text-decoration: none; font-size: 16px; cursor: pointer; width: 150px; display: block; margin: 4px 2px; } .button:hover { background-color: whitesmoke; } h1 { font-weight: 200; font-style: 26px; margin: 10px; } </style> </head> <body> <div class="btn-group"> <button id="start" class="button"> Start Audio </button> <button id="sus" class="button"> Suspend Audio </button> <button id="stop" class="button"> Stop Audio </button> <p>Current context time: No context exists.</p> </div> <script> let AudioContext; const start = document.getElementById("start"); const susres = document.getElementById("sus"); const stop = document.getElementById("stop"); const timeDisplay = document.querySelector("p"); susres.setAttribute("disabled", "disabled"); stop.setAttribute("disabled", "disabled"); start.onclick = function () { start.setAttribute("disabled", "disabled"); susres.removeAttribute("disabled"); stop.removeAttribute("disabled"); // Create web audio api context AudioContext = window.AudioContext || window.webkitAudioContext; AudioContext = new AudioContext(); // Create Oscillator and filter const oscillator = AudioContext.createOscillator(); const filter = AudioContext.createBiquadFilter(); // Connect oscillator to filter to speakers oscillator.connect(filter); filter.connect(AudioContext.destination); // Make audio/noise oscillator.type = "sine"; // hertz frequency oscillator.frequency.value = 100; oscillator.start(0); }; // Suspend/resume the audiocontext,i.e, // the audio can be played back susres.onclick = function () { if (AudioContext.state === "running") { AudioContext.suspend().then(function () { susres.textContent = "Resume Audio"; }); } else if (AudioContext.state === "suspended") { AudioContext.resume().then(function () { susres.textContent = "Suspend Audio"; }); } }; // Close the audiocontext,i.e, the audio is // completely stopped after the stop button // is clicked by promise the audio resets // the response to beginning state(Create Audio) stop.onclick = function () { AudioContext.close().then(function () { start.removeAttribute("disabled"); susres.setAttribute("disabled", "disabled"); stop.setAttribute("disabled", "disabled"); }); }; function displayTime() { if (AudioContext && AudioContext.state !== "closed") { timeDisplay.textContent = "audio time " + AudioContext.currentTime.toFixed(3); } else { timeDisplay.textContent = "Context not started"; } requestAnimationFrame(displayTime); } displayTime(); </script> </body></html>
Output : The audio starts by clicking ‘Create Audio’ , audio can temporarily stopped by ‘Suspend Audio’ and again started without time lapse ‘Resume Audio’. The audio is stopped by ‘Stop Audio’ using Audiocontext.close()
Akanksha_Rai
kapoorsagar226
Web-API
CSS
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a web page using HTML and CSS
Form validation using jQuery
How to style a checkbox using CSS?
Search Bar using HTML, CSS and JavaScript
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
|
[
{
"code": null,
"e": 26731,
"s": 26703,
"text": "\n07 Sep, 2021"
},
{
"code": null,
"e": 27031,
"s": 26731,
"text": "Web Audio APIs help to make the audio of a website application sound correct. Sounds make the site more fun and attractive. Using Audio APIs, many music or sound applications can be built. In this article, we will learn about audiocontext.close() along with some basic information about Audio APIs. "
},
{
"code": null,
"e": 27351,
"s": 27031,
"text": "Audio Context is an object that is used to do various manipulations in the audio for the website or application. It is a pre-built function that can be used on various browsers like google and Firefox Before making changes to any audio the source of the audio has to be stored. There are 3 major types of audio sources."
},
{
"code": null,
"e": 27418,
"s": 27351,
"text": "Oscillator: it is used to produce a mathematically computed sounds"
},
{
"code": null,
"e": 27465,
"s": 27418,
"text": "Audio Samples: to get audio from various files"
},
{
"code": null,
"e": 27519,
"s": 27465,
"text": "Audio stream: getting audio from webcam or microphone"
},
{
"code": null,
"e": 27861,
"s": 27519,
"text": "After the audio is been streamed by using either of the sources, one can either emphasize or attenuate the parts of audio by using different nodes. After the node functions are performed the audio is connected to the destination and then the sound is played. Some of the different nodes are Filter,ChannelSpiltterNode,AudioWorkletNode,etc..."
},
{
"code": null,
"e": 28314,
"s": 27861,
"text": "AudioContext.close(): This audio context function can close the audiocontext and thereby detaching any hardware resources associated with the audiocontent. i.e. the function doesn’t further take/give any inputs to the sound device. But the already stored audio before using close() can be manipulated. This is very meaningful in low power devices like mobile. If the audiocontext stays on the device’s resources stay on and thus causing the power loss."
},
{
"code": null,
"e": 28322,
"s": 28314,
"text": "Syntax:"
},
{
"code": null,
"e": 28489,
"s": 28322,
"text": "// Declaring audiocontext constructor\nvar audioContext=new AudioContext();\naudioContext.close().then(function()\n {.\n .\n . });\nawait audioContext.close()"
},
{
"code": null,
"e": 28994,
"s": 28493,
"text": "Example: In the following code, a small HTML page is created with 3 buttons. Clicking on each button performs respective functions related to the audio. In the example, the audio can be started and the stopped,i.e, resume. Note that the resume is different from a stop as resuming the audio means temporarily pausing the audio and restart from where it was stopped. Whereas stopping the audio using close() completely removes the audio from the sound devices and setting the state as beginning state."
},
{
"code": null,
"e": 29005,
"s": 28994,
"text": "Javascript"
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\" /> <title>states</title> <link rel=\"stylesheet\" href=\"\" /> <style> body { background: lightcoral; color: #323232; font-weight: 300; height: 100vh; margin: 0; display: flex; align-items: center; justify-content: center; text-align: center; font-family: Helvetica neue, roboto; } .button:hover { background-color: aquamarine; } .btn-group .button { background-color: bisque; border: 1px solid black; color: black; padding: 15px 32px; text-align: center; text-decoration: none; font-size: 16px; cursor: pointer; width: 150px; display: block; margin: 4px 2px; } .button:hover { background-color: whitesmoke; } h1 { font-weight: 200; font-style: 26px; margin: 10px; } </style> </head> <body> <div class=\"btn-group\"> <button id=\"start\" class=\"button\"> Start Audio </button> <button id=\"sus\" class=\"button\"> Suspend Audio </button> <button id=\"stop\" class=\"button\"> Stop Audio </button> <p>Current context time: No context exists.</p> </div> <script> let AudioContext; const start = document.getElementById(\"start\"); const susres = document.getElementById(\"sus\"); const stop = document.getElementById(\"stop\"); const timeDisplay = document.querySelector(\"p\"); susres.setAttribute(\"disabled\", \"disabled\"); stop.setAttribute(\"disabled\", \"disabled\"); start.onclick = function () { start.setAttribute(\"disabled\", \"disabled\"); susres.removeAttribute(\"disabled\"); stop.removeAttribute(\"disabled\"); // Create web audio api context AudioContext = window.AudioContext || window.webkitAudioContext; AudioContext = new AudioContext(); // Create Oscillator and filter const oscillator = AudioContext.createOscillator(); const filter = AudioContext.createBiquadFilter(); // Connect oscillator to filter to speakers oscillator.connect(filter); filter.connect(AudioContext.destination); // Make audio/noise oscillator.type = \"sine\"; // hertz frequency oscillator.frequency.value = 100; oscillator.start(0); }; // Suspend/resume the audiocontext,i.e, // the audio can be played back susres.onclick = function () { if (AudioContext.state === \"running\") { AudioContext.suspend().then(function () { susres.textContent = \"Resume Audio\"; }); } else if (AudioContext.state === \"suspended\") { AudioContext.resume().then(function () { susres.textContent = \"Suspend Audio\"; }); } }; // Close the audiocontext,i.e, the audio is // completely stopped after the stop button // is clicked by promise the audio resets // the response to beginning state(Create Audio) stop.onclick = function () { AudioContext.close().then(function () { start.removeAttribute(\"disabled\"); susres.setAttribute(\"disabled\", \"disabled\"); stop.setAttribute(\"disabled\", \"disabled\"); }); }; function displayTime() { if (AudioContext && AudioContext.state !== \"closed\") { timeDisplay.textContent = \"audio time \" + AudioContext.currentTime.toFixed(3); } else { timeDisplay.textContent = \"Context not started\"; } requestAnimationFrame(displayTime); } displayTime(); </script> </body></html>",
"e": 33628,
"s": 29005,
"text": null
},
{
"code": null,
"e": 33849,
"s": 33628,
"text": "Output : The audio starts by clicking ‘Create Audio’ , audio can temporarily stopped by ‘Suspend Audio’ and again started without time lapse ‘Resume Audio’. The audio is stopped by ‘Stop Audio’ using Audiocontext.close()"
},
{
"code": null,
"e": 33862,
"s": 33849,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 33877,
"s": 33862,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 33885,
"s": 33877,
"text": "Web-API"
},
{
"code": null,
"e": 33889,
"s": 33885,
"text": "CSS"
},
{
"code": null,
"e": 33894,
"s": 33889,
"text": "HTML"
},
{
"code": null,
"e": 33905,
"s": 33894,
"text": "JavaScript"
},
{
"code": null,
"e": 33922,
"s": 33905,
"text": "Web Technologies"
},
{
"code": null,
"e": 33927,
"s": 33922,
"text": "HTML"
},
{
"code": null,
"e": 34025,
"s": 33927,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34064,
"s": 34025,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 34101,
"s": 34064,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 34130,
"s": 34101,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 34165,
"s": 34130,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 34207,
"s": 34165,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 34267,
"s": 34207,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 34320,
"s": 34267,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 34381,
"s": 34320,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 34405,
"s": 34381,
"text": "REST API (Introduction)"
}
] |
Simple way to deploy machine learning models to cloud | by Tanuj Jain | Towards Data Science
|
The Machine learning world currently sees Data Scientists (DS) performing one or both of the following 2 prominent roles:
Where a DS receives a data dump, applies some Machine learning algo on the data and reports back the results in the form of some presentation or report.Where the DS creates a usable piece of software for the stakeholders to consume the machine learning models.
Where a DS receives a data dump, applies some Machine learning algo on the data and reports back the results in the form of some presentation or report.
Where the DS creates a usable piece of software for the stakeholders to consume the machine learning models.
In this blog post, I’m attempting to display an example approach to the second aspect of a DS’s job i.e., creating some software that can be used by the stakeholders. Specifically, we would create a web-service that can be queried to obtain the predictions from a machine learning model. The post is mostly intended for machine learning practitioners who would like to go beyond only developing models.
Tech-stack: Python, Flask, Docker, AWS ec2
The workflow can be broken down into following basic steps:
Training a machine learning model on a local system.Wrapping the inference logic into a flask application.Using docker to containerize the flask application.Hosting the docker container on an AWS ec2 instance and consuming the web-service.
Training a machine learning model on a local system.
Wrapping the inference logic into a flask application.
Using docker to containerize the flask application.
Hosting the docker container on an AWS ec2 instance and consuming the web-service.
DISCLAIMER: The system presented here is light years away from what a commercial production system should look like. The key takeaways from this blogpost should be the development workflow, acquaintance with the tech stack and getting the first taste of building an ML production system.
Let’s start with the first step.
We need some machine learning model that we can wrap in a web-service. For demo purpose, I chose a logistic regression model to do multiclass classification on iris dataset (Yep, super easy! #LazinessFTW). The model was trained on a local system using python 3.6.
Using the familiar scikit-learn, the above mentioned model can be trained quickly. For model development, refer the notebook ‘Model_training.ipynb’ in the github repo for this blog. There are only 2 important aspects of model development that I would like to highlight:
The model file generated after training is stored as a pickle file which is a serialized format for storing objects. (In the repo, the file is named ‘iris_trained_model.pkl’)The inference call (.predict()) call requires 4 features per test sample in the form of a numpy array.
The model file generated after training is stored as a pickle file which is a serialized format for storing objects. (In the repo, the file is named ‘iris_trained_model.pkl’)
The inference call (.predict()) call requires 4 features per test sample in the form of a numpy array.
Now that we have the trained model file, we are ready to query the model to get a class label for a test sample. The inference is as simple as calling a predict() function on the trained model with the test data. However, we would like to build the inference as a web-service. For this purpose, we would use Flask.
Flask is a powerful python microwebserver framework that allows us to build REST API based web-services quickly with minimum configuration hassle. Let’s dive into the code:
a. First, let’s define a simple function to load the trained model file.
Here, we define a global variable called ‘model’ and populate it within the load_model() function. The purpose of using a global variable will become clear shortly.
b. Next, we instantiate a Flask object called ‘app’:
c. Now, we define a home endpoint, which when hit, returns a ‘Hello World!’ message.
Notice the use of app.route decorator.
d. Now, we define a ‘predict’ endpoint. The endpoint accepts a ‘POST’ request wherein the test data on which we wish to get a prediction is received by the endpoint. Keeping things simple, the function works only when a single test sample needs to be predicted (won’t work if multiple samples need to be predicted in a single call to the endpoint).
Notice the direct call to the predict function through the ‘model’ variable.
e. Finally, declare the main function:
Here, a call to the load_model() function ensures that the variable ‘model’ is populated with the trained model attributes (and hence the need for a global model variable). So, there is no need to load the model repeatedly with every call to the predict endpoint. This allows the web-service to be quick. The response is returned as a string which is the predicted class label.
The complete flask specific code is as below:
At this point, the web-service is ready to be run locally. Let’s test this.
Execute the command python app.py from the terminal. Go to the browser and hit the url 0.0.0.0:80 to get a message Hello World! displayed. This corresponds to the home endpoint return message.
NOTE: A permission error may be received at this point. In this case, change the port number to 5000 in app.run() command in app.py. (Port 80 is a privileged port, so change it to some port that isn't, eg: 5000)
Next, let’s test if we can get predictions using this web-service using the following curl post request on the terminal:
curl -X POST \ 0.0.0.0:80/predict \ -H 'Content-Type: application/json' \ -d '[5.9,3.0,5.1,1.8]'
The curl request posts one test sample [5.9,3.0,5.1,1.8]to our web-server and returns a single class label.
Up to this point, we have a web-service that runs locally. Our ultimate intention is to be able to run this piece of code on a cloud virtual machine.
In the Software Development world, there is a famous justification given by a developer whose code was found to be broken by a tester: ‘But it worked on my machine!’. The problem portrayed here can usually be attributed to a lack of consistent environment that runs the software across different machines. Ideally, our code itself should be independent of the underlying machine/OS that runs it. Containerization allows developers to provide such isolation.
How is it important here?
Our intention is to run our web-service on a cloud VM. The cloud VM itself may run any OS. Containerization of our web-server allows us to avoid the trouble of running into environment related issues. If the containerized code works on one machine, it will surely run on another irrespective of the characteristics of the machine. Docker is the most famous containerized technology out there at this point and we will be using the same here. For a quick tutorial on docker, check this link.
Let’s dive into the Dockerfile that comprises a set of instructions for docker daemon to build the docker image.
We pull the base docker image from python dockerhub repo on which our specific build instructions are executed. The COPY commands are simply taking specific files from the current folder and copying them over to a folder called ‘deploy’ within the docker image we are trying to build. In addition to app.py and model file, we also need a requirements file that lists specific versions of python packages we use to run our code. The WORKDIR command changes the working directory to ‘deploy/’ within the image. We then issue a RUN command to install specific python packages using the requirements file. The EXPOSE command makes the port 80 accessible to the outside world (our flask service runs on port 80; we need this port inside the container to be accessible outside the container).
Issue the build command to end up with a docker image:
docker build -t app-iris .
(Don’t forget the period at the end of the command).
Use command ‘docker images’ to see a docker image with a docker repository named ‘app-iris’ created. (Another repository named python will also be seen since it is the base image on top of which we build our custom image.)
Now, the image is built and ready to be run. We can do this using the command:
docker run -p 80:80 app-iris .
The above commands uses -p flag to map port 80 of the local system to the port 80 of the docker container for the redirection of traffic on local HTTP port 80 to port 80 of the container. (If you are using local port 5000 instead of port 80, change the port mapping part of the command to 5000:80).
Let’s test if this works by hitting the URL: http://0.0.0.0:80 on the browser which should display ‘Hello World!’ which is the home endpoint output message (If port 5000 is used, modify the http port to 5000 in the url). Also, use the curl request mentioned earlier to check if the predicted class label is returned.
We already have a containerized application that works on our local system. Now, what if someone else wishes to consume the service? What happens if we need to build an architectural ecosystem around the service that needs to be available, automated and scalable? It’s easy to see that having a web-service running locally would be a very bad idea. So, we wish to host the web-service somewhere on the internet to fulfil the requirements we listed. For this blog, we choose to host our service on an AWS ec2 instance.
As a prerequisite, one needs to have an AWS account for using the ec2 instance. For new users, there are several AWS resources that are available for free for a period of 1 year (usually up to some limit). In this blog, I would be using a ‘t2.micro’ ec2 instance type which is free tier eligible. For users who have exhausted their AWS free-tier period, this instance costs around 1 cent(USD) per hour at the time of writing this blog; a super negligible amount to pay.
Let’s start with the process.
Log into the AWS management console and search for ec2 in the search bar to navigate to EC2 dashboard.
Look for the below pane, select ‘Key Pairs’ and create one.
This will download a ‘.pem’ file that is the key. Save this file somewhere safely. Now navigate to the location of this file on your system and issue the below command with key file name replaced by yours:
chmod 400 key-file-name.pem
This commands changes permissions on your key pair file to private. The use of key pairs will be explained later.
Next, click ‘Launch Instance’ on the EC2 dashboard:
Choose the Amazon Machine Instance (AMI) from the list of options. An AMI determines the OS that the VM will be running (plus some other stuff we don’t care about at this point). For this blog, I chose ‘Amazon Linux 2 AMI’ which was the default selection.
The next screen allows you to select the instance type. This is where the hardware part of the VM can be selected. As mentioned previously, we will work with ‘t2.micro’ instance.
You can select ‘Review and Launch’ that takes you to ‘Step 7: Review Instance Launch’ screen. Here, you need to click the ‘Edit Security Groups’ link:
You now have to modify the security group to allow HTTP traffic on port 80 of your instance to be accessible by the outside world. This can be done by creating a rule. At the end, you should end up with such a screen:
In the absence of this rule, your web-service will never be reachable. For more on security groups and configuration, refer AWS documentation. Clicking on the ‘Launch’ icon will lead to a pop up seeking a confirmation on having a key-pair. Use the name of the key pair that was generated earlier and launch the VM.
You would be redirected to a Launch screen:
Use the ‘View Instance’ button to navigate to a screen that displays the ec2 instance being launched. When the instance state turns to ‘running’, then it is ready to be used.
We will now ssh into the ec2 machine from our local system terminal using the command with the field public-dns-name replaced with your ec2 instance name (of the form: ec2–x–x–x–x.compute-1.amazonaws.com) and the path of the key pair pem file you saved earlier.
ssh -i /path/my-key-pair.pem ec2-user@public-dns-name
This will get us into the prompt of our instance where we’ll first install docker. This is required for our workflow since we will build the docker image within the ec2 instance (There are better, but slightly complicated alternatives to this step). For the AMI we selected, the following bunch of commands can be used:
sudo amazon-linux-extras install dockersudo yum install dockersudo service docker startsudo usermod -a -G docker ec2-user
For an explanation of the commands, check the documentation.
Log out of the ec2 instance using the ‘exit’ command and log back in again using the ssh command. Check if docker works by issuing the ‘docker info’ command. Log out again or open another terminal window.
Now let’s copy the files we need to build the docker image within the ec2 instance. Issue the command from your local terminal (not from within ec2):
scp -i /path/my-key-pair.pem file-to-copy ec2-user@public-dns-name:/home/ec2-user
We would need to copy requirements.txt, app.py, trained model file and Dockerfile to build the docker image as was done earlier. Log back into the ec2 instance and issue ‘ls’ command to see if the copied files exist. Next, build and run the docker image using the exact same commands that were used in the local system (Use port 80 at all locations in the code/commands this time).
Hit the home endpoint from your browser using the public dns name to see the familiar ‘Hello World!’ message:
Now send a curl request to your web-service from local terminal with your test sample data after replacing the public-dns-name by yours:
curl -X POST \public-dns-name:80/predict \-H 'Content-Type: application/json' \-d '[5.9,3.0,5.1,1.8]'
This should get you the same predicted class label as the one you got locally.
And you are done! You can now share this curl request with anyone who wishes to consume your web-service with their test samples.
When you no longer need the web-service, do not forget to stop or terminate the ec2 instance:
This is a super basic workflow intended for ML practitioners itching to go beyond model development. A huge number of things need to be changed to make this system into one that is more suited to a real production system. Some suggestions (far from complete):
Use a Web Server Gateway Interface (WSGI) such as gunicorn in the flask app. Bonus points for using nginx reverse proxy and async workers.Improve security of the ec2 instance: The service is currently open to the entire world. Suggestions: Restrict access to a set of IPs.Write test cases for the app: Software without testing = Shooting yourself in the leg and then throwing yourself in a cage full of hungry lions all the while being pelted with stones. (Moral: Do not float a production software without thoroughly testing first)
Use a Web Server Gateway Interface (WSGI) such as gunicorn in the flask app. Bonus points for using nginx reverse proxy and async workers.
Improve security of the ec2 instance: The service is currently open to the entire world. Suggestions: Restrict access to a set of IPs.
Write test cases for the app: Software without testing = Shooting yourself in the leg and then throwing yourself in a cage full of hungry lions all the while being pelted with stones. (Moral: Do not float a production software without thoroughly testing first)
A lot more could be added to the above list, but maybe that’s something for another blog post.
Github repo: https://github.com/tanujjain/deploy-ml-model
It would be great to hear your feedback!
|
[
{
"code": null,
"e": 294,
"s": 172,
"text": "The Machine learning world currently sees Data Scientists (DS) performing one or both of the following 2 prominent roles:"
},
{
"code": null,
"e": 555,
"s": 294,
"text": "Where a DS receives a data dump, applies some Machine learning algo on the data and reports back the results in the form of some presentation or report.Where the DS creates a usable piece of software for the stakeholders to consume the machine learning models."
},
{
"code": null,
"e": 708,
"s": 555,
"text": "Where a DS receives a data dump, applies some Machine learning algo on the data and reports back the results in the form of some presentation or report."
},
{
"code": null,
"e": 817,
"s": 708,
"text": "Where the DS creates a usable piece of software for the stakeholders to consume the machine learning models."
},
{
"code": null,
"e": 1220,
"s": 817,
"text": "In this blog post, I’m attempting to display an example approach to the second aspect of a DS’s job i.e., creating some software that can be used by the stakeholders. Specifically, we would create a web-service that can be queried to obtain the predictions from a machine learning model. The post is mostly intended for machine learning practitioners who would like to go beyond only developing models."
},
{
"code": null,
"e": 1263,
"s": 1220,
"text": "Tech-stack: Python, Flask, Docker, AWS ec2"
},
{
"code": null,
"e": 1323,
"s": 1263,
"text": "The workflow can be broken down into following basic steps:"
},
{
"code": null,
"e": 1563,
"s": 1323,
"text": "Training a machine learning model on a local system.Wrapping the inference logic into a flask application.Using docker to containerize the flask application.Hosting the docker container on an AWS ec2 instance and consuming the web-service."
},
{
"code": null,
"e": 1616,
"s": 1563,
"text": "Training a machine learning model on a local system."
},
{
"code": null,
"e": 1671,
"s": 1616,
"text": "Wrapping the inference logic into a flask application."
},
{
"code": null,
"e": 1723,
"s": 1671,
"text": "Using docker to containerize the flask application."
},
{
"code": null,
"e": 1806,
"s": 1723,
"text": "Hosting the docker container on an AWS ec2 instance and consuming the web-service."
},
{
"code": null,
"e": 2094,
"s": 1806,
"text": "DISCLAIMER: The system presented here is light years away from what a commercial production system should look like. The key takeaways from this blogpost should be the development workflow, acquaintance with the tech stack and getting the first taste of building an ML production system."
},
{
"code": null,
"e": 2127,
"s": 2094,
"text": "Let’s start with the first step."
},
{
"code": null,
"e": 2391,
"s": 2127,
"text": "We need some machine learning model that we can wrap in a web-service. For demo purpose, I chose a logistic regression model to do multiclass classification on iris dataset (Yep, super easy! #LazinessFTW). The model was trained on a local system using python 3.6."
},
{
"code": null,
"e": 2661,
"s": 2391,
"text": "Using the familiar scikit-learn, the above mentioned model can be trained quickly. For model development, refer the notebook ‘Model_training.ipynb’ in the github repo for this blog. There are only 2 important aspects of model development that I would like to highlight:"
},
{
"code": null,
"e": 2938,
"s": 2661,
"text": "The model file generated after training is stored as a pickle file which is a serialized format for storing objects. (In the repo, the file is named ‘iris_trained_model.pkl’)The inference call (.predict()) call requires 4 features per test sample in the form of a numpy array."
},
{
"code": null,
"e": 3113,
"s": 2938,
"text": "The model file generated after training is stored as a pickle file which is a serialized format for storing objects. (In the repo, the file is named ‘iris_trained_model.pkl’)"
},
{
"code": null,
"e": 3216,
"s": 3113,
"text": "The inference call (.predict()) call requires 4 features per test sample in the form of a numpy array."
},
{
"code": null,
"e": 3531,
"s": 3216,
"text": "Now that we have the trained model file, we are ready to query the model to get a class label for a test sample. The inference is as simple as calling a predict() function on the trained model with the test data. However, we would like to build the inference as a web-service. For this purpose, we would use Flask."
},
{
"code": null,
"e": 3704,
"s": 3531,
"text": "Flask is a powerful python microwebserver framework that allows us to build REST API based web-services quickly with minimum configuration hassle. Let’s dive into the code:"
},
{
"code": null,
"e": 3777,
"s": 3704,
"text": "a. First, let’s define a simple function to load the trained model file."
},
{
"code": null,
"e": 3942,
"s": 3777,
"text": "Here, we define a global variable called ‘model’ and populate it within the load_model() function. The purpose of using a global variable will become clear shortly."
},
{
"code": null,
"e": 3995,
"s": 3942,
"text": "b. Next, we instantiate a Flask object called ‘app’:"
},
{
"code": null,
"e": 4080,
"s": 3995,
"text": "c. Now, we define a home endpoint, which when hit, returns a ‘Hello World!’ message."
},
{
"code": null,
"e": 4119,
"s": 4080,
"text": "Notice the use of app.route decorator."
},
{
"code": null,
"e": 4468,
"s": 4119,
"text": "d. Now, we define a ‘predict’ endpoint. The endpoint accepts a ‘POST’ request wherein the test data on which we wish to get a prediction is received by the endpoint. Keeping things simple, the function works only when a single test sample needs to be predicted (won’t work if multiple samples need to be predicted in a single call to the endpoint)."
},
{
"code": null,
"e": 4545,
"s": 4468,
"text": "Notice the direct call to the predict function through the ‘model’ variable."
},
{
"code": null,
"e": 4584,
"s": 4545,
"text": "e. Finally, declare the main function:"
},
{
"code": null,
"e": 4962,
"s": 4584,
"text": "Here, a call to the load_model() function ensures that the variable ‘model’ is populated with the trained model attributes (and hence the need for a global model variable). So, there is no need to load the model repeatedly with every call to the predict endpoint. This allows the web-service to be quick. The response is returned as a string which is the predicted class label."
},
{
"code": null,
"e": 5008,
"s": 4962,
"text": "The complete flask specific code is as below:"
},
{
"code": null,
"e": 5084,
"s": 5008,
"text": "At this point, the web-service is ready to be run locally. Let’s test this."
},
{
"code": null,
"e": 5277,
"s": 5084,
"text": "Execute the command python app.py from the terminal. Go to the browser and hit the url 0.0.0.0:80 to get a message Hello World! displayed. This corresponds to the home endpoint return message."
},
{
"code": null,
"e": 5489,
"s": 5277,
"text": "NOTE: A permission error may be received at this point. In this case, change the port number to 5000 in app.run() command in app.py. (Port 80 is a privileged port, so change it to some port that isn't, eg: 5000)"
},
{
"code": null,
"e": 5610,
"s": 5489,
"text": "Next, let’s test if we can get predictions using this web-service using the following curl post request on the terminal:"
},
{
"code": null,
"e": 5713,
"s": 5610,
"text": "curl -X POST \\ 0.0.0.0:80/predict \\ -H 'Content-Type: application/json' \\ -d '[5.9,3.0,5.1,1.8]'"
},
{
"code": null,
"e": 5821,
"s": 5713,
"text": "The curl request posts one test sample [5.9,3.0,5.1,1.8]to our web-server and returns a single class label."
},
{
"code": null,
"e": 5971,
"s": 5821,
"text": "Up to this point, we have a web-service that runs locally. Our ultimate intention is to be able to run this piece of code on a cloud virtual machine."
},
{
"code": null,
"e": 6429,
"s": 5971,
"text": "In the Software Development world, there is a famous justification given by a developer whose code was found to be broken by a tester: ‘But it worked on my machine!’. The problem portrayed here can usually be attributed to a lack of consistent environment that runs the software across different machines. Ideally, our code itself should be independent of the underlying machine/OS that runs it. Containerization allows developers to provide such isolation."
},
{
"code": null,
"e": 6455,
"s": 6429,
"text": "How is it important here?"
},
{
"code": null,
"e": 6946,
"s": 6455,
"text": "Our intention is to run our web-service on a cloud VM. The cloud VM itself may run any OS. Containerization of our web-server allows us to avoid the trouble of running into environment related issues. If the containerized code works on one machine, it will surely run on another irrespective of the characteristics of the machine. Docker is the most famous containerized technology out there at this point and we will be using the same here. For a quick tutorial on docker, check this link."
},
{
"code": null,
"e": 7059,
"s": 6946,
"text": "Let’s dive into the Dockerfile that comprises a set of instructions for docker daemon to build the docker image."
},
{
"code": null,
"e": 7846,
"s": 7059,
"text": "We pull the base docker image from python dockerhub repo on which our specific build instructions are executed. The COPY commands are simply taking specific files from the current folder and copying them over to a folder called ‘deploy’ within the docker image we are trying to build. In addition to app.py and model file, we also need a requirements file that lists specific versions of python packages we use to run our code. The WORKDIR command changes the working directory to ‘deploy/’ within the image. We then issue a RUN command to install specific python packages using the requirements file. The EXPOSE command makes the port 80 accessible to the outside world (our flask service runs on port 80; we need this port inside the container to be accessible outside the container)."
},
{
"code": null,
"e": 7901,
"s": 7846,
"text": "Issue the build command to end up with a docker image:"
},
{
"code": null,
"e": 7928,
"s": 7901,
"text": "docker build -t app-iris ."
},
{
"code": null,
"e": 7981,
"s": 7928,
"text": "(Don’t forget the period at the end of the command)."
},
{
"code": null,
"e": 8204,
"s": 7981,
"text": "Use command ‘docker images’ to see a docker image with a docker repository named ‘app-iris’ created. (Another repository named python will also be seen since it is the base image on top of which we build our custom image.)"
},
{
"code": null,
"e": 8283,
"s": 8204,
"text": "Now, the image is built and ready to be run. We can do this using the command:"
},
{
"code": null,
"e": 8314,
"s": 8283,
"text": "docker run -p 80:80 app-iris ."
},
{
"code": null,
"e": 8613,
"s": 8314,
"text": "The above commands uses -p flag to map port 80 of the local system to the port 80 of the docker container for the redirection of traffic on local HTTP port 80 to port 80 of the container. (If you are using local port 5000 instead of port 80, change the port mapping part of the command to 5000:80)."
},
{
"code": null,
"e": 8930,
"s": 8613,
"text": "Let’s test if this works by hitting the URL: http://0.0.0.0:80 on the browser which should display ‘Hello World!’ which is the home endpoint output message (If port 5000 is used, modify the http port to 5000 in the url). Also, use the curl request mentioned earlier to check if the predicted class label is returned."
},
{
"code": null,
"e": 9448,
"s": 8930,
"text": "We already have a containerized application that works on our local system. Now, what if someone else wishes to consume the service? What happens if we need to build an architectural ecosystem around the service that needs to be available, automated and scalable? It’s easy to see that having a web-service running locally would be a very bad idea. So, we wish to host the web-service somewhere on the internet to fulfil the requirements we listed. For this blog, we choose to host our service on an AWS ec2 instance."
},
{
"code": null,
"e": 9918,
"s": 9448,
"text": "As a prerequisite, one needs to have an AWS account for using the ec2 instance. For new users, there are several AWS resources that are available for free for a period of 1 year (usually up to some limit). In this blog, I would be using a ‘t2.micro’ ec2 instance type which is free tier eligible. For users who have exhausted their AWS free-tier period, this instance costs around 1 cent(USD) per hour at the time of writing this blog; a super negligible amount to pay."
},
{
"code": null,
"e": 9948,
"s": 9918,
"text": "Let’s start with the process."
},
{
"code": null,
"e": 10051,
"s": 9948,
"text": "Log into the AWS management console and search for ec2 in the search bar to navigate to EC2 dashboard."
},
{
"code": null,
"e": 10111,
"s": 10051,
"text": "Look for the below pane, select ‘Key Pairs’ and create one."
},
{
"code": null,
"e": 10317,
"s": 10111,
"text": "This will download a ‘.pem’ file that is the key. Save this file somewhere safely. Now navigate to the location of this file on your system and issue the below command with key file name replaced by yours:"
},
{
"code": null,
"e": 10345,
"s": 10317,
"text": "chmod 400 key-file-name.pem"
},
{
"code": null,
"e": 10459,
"s": 10345,
"text": "This commands changes permissions on your key pair file to private. The use of key pairs will be explained later."
},
{
"code": null,
"e": 10511,
"s": 10459,
"text": "Next, click ‘Launch Instance’ on the EC2 dashboard:"
},
{
"code": null,
"e": 10767,
"s": 10511,
"text": "Choose the Amazon Machine Instance (AMI) from the list of options. An AMI determines the OS that the VM will be running (plus some other stuff we don’t care about at this point). For this blog, I chose ‘Amazon Linux 2 AMI’ which was the default selection."
},
{
"code": null,
"e": 10946,
"s": 10767,
"text": "The next screen allows you to select the instance type. This is where the hardware part of the VM can be selected. As mentioned previously, we will work with ‘t2.micro’ instance."
},
{
"code": null,
"e": 11097,
"s": 10946,
"text": "You can select ‘Review and Launch’ that takes you to ‘Step 7: Review Instance Launch’ screen. Here, you need to click the ‘Edit Security Groups’ link:"
},
{
"code": null,
"e": 11315,
"s": 11097,
"text": "You now have to modify the security group to allow HTTP traffic on port 80 of your instance to be accessible by the outside world. This can be done by creating a rule. At the end, you should end up with such a screen:"
},
{
"code": null,
"e": 11630,
"s": 11315,
"text": "In the absence of this rule, your web-service will never be reachable. For more on security groups and configuration, refer AWS documentation. Clicking on the ‘Launch’ icon will lead to a pop up seeking a confirmation on having a key-pair. Use the name of the key pair that was generated earlier and launch the VM."
},
{
"code": null,
"e": 11674,
"s": 11630,
"text": "You would be redirected to a Launch screen:"
},
{
"code": null,
"e": 11849,
"s": 11674,
"text": "Use the ‘View Instance’ button to navigate to a screen that displays the ec2 instance being launched. When the instance state turns to ‘running’, then it is ready to be used."
},
{
"code": null,
"e": 12111,
"s": 11849,
"text": "We will now ssh into the ec2 machine from our local system terminal using the command with the field public-dns-name replaced with your ec2 instance name (of the form: ec2–x–x–x–x.compute-1.amazonaws.com) and the path of the key pair pem file you saved earlier."
},
{
"code": null,
"e": 12165,
"s": 12111,
"text": "ssh -i /path/my-key-pair.pem ec2-user@public-dns-name"
},
{
"code": null,
"e": 12485,
"s": 12165,
"text": "This will get us into the prompt of our instance where we’ll first install docker. This is required for our workflow since we will build the docker image within the ec2 instance (There are better, but slightly complicated alternatives to this step). For the AMI we selected, the following bunch of commands can be used:"
},
{
"code": null,
"e": 12607,
"s": 12485,
"text": "sudo amazon-linux-extras install dockersudo yum install dockersudo service docker startsudo usermod -a -G docker ec2-user"
},
{
"code": null,
"e": 12668,
"s": 12607,
"text": "For an explanation of the commands, check the documentation."
},
{
"code": null,
"e": 12873,
"s": 12668,
"text": "Log out of the ec2 instance using the ‘exit’ command and log back in again using the ssh command. Check if docker works by issuing the ‘docker info’ command. Log out again or open another terminal window."
},
{
"code": null,
"e": 13023,
"s": 12873,
"text": "Now let’s copy the files we need to build the docker image within the ec2 instance. Issue the command from your local terminal (not from within ec2):"
},
{
"code": null,
"e": 13105,
"s": 13023,
"text": "scp -i /path/my-key-pair.pem file-to-copy ec2-user@public-dns-name:/home/ec2-user"
},
{
"code": null,
"e": 13487,
"s": 13105,
"text": "We would need to copy requirements.txt, app.py, trained model file and Dockerfile to build the docker image as was done earlier. Log back into the ec2 instance and issue ‘ls’ command to see if the copied files exist. Next, build and run the docker image using the exact same commands that were used in the local system (Use port 80 at all locations in the code/commands this time)."
},
{
"code": null,
"e": 13597,
"s": 13487,
"text": "Hit the home endpoint from your browser using the public dns name to see the familiar ‘Hello World!’ message:"
},
{
"code": null,
"e": 13734,
"s": 13597,
"text": "Now send a curl request to your web-service from local terminal with your test sample data after replacing the public-dns-name by yours:"
},
{
"code": null,
"e": 13836,
"s": 13734,
"text": "curl -X POST \\public-dns-name:80/predict \\-H 'Content-Type: application/json' \\-d '[5.9,3.0,5.1,1.8]'"
},
{
"code": null,
"e": 13915,
"s": 13836,
"text": "This should get you the same predicted class label as the one you got locally."
},
{
"code": null,
"e": 14045,
"s": 13915,
"text": "And you are done! You can now share this curl request with anyone who wishes to consume your web-service with their test samples."
},
{
"code": null,
"e": 14139,
"s": 14045,
"text": "When you no longer need the web-service, do not forget to stop or terminate the ec2 instance:"
},
{
"code": null,
"e": 14399,
"s": 14139,
"text": "This is a super basic workflow intended for ML practitioners itching to go beyond model development. A huge number of things need to be changed to make this system into one that is more suited to a real production system. Some suggestions (far from complete):"
},
{
"code": null,
"e": 14932,
"s": 14399,
"text": "Use a Web Server Gateway Interface (WSGI) such as gunicorn in the flask app. Bonus points for using nginx reverse proxy and async workers.Improve security of the ec2 instance: The service is currently open to the entire world. Suggestions: Restrict access to a set of IPs.Write test cases for the app: Software without testing = Shooting yourself in the leg and then throwing yourself in a cage full of hungry lions all the while being pelted with stones. (Moral: Do not float a production software without thoroughly testing first)"
},
{
"code": null,
"e": 15071,
"s": 14932,
"text": "Use a Web Server Gateway Interface (WSGI) such as gunicorn in the flask app. Bonus points for using nginx reverse proxy and async workers."
},
{
"code": null,
"e": 15206,
"s": 15071,
"text": "Improve security of the ec2 instance: The service is currently open to the entire world. Suggestions: Restrict access to a set of IPs."
},
{
"code": null,
"e": 15467,
"s": 15206,
"text": "Write test cases for the app: Software without testing = Shooting yourself in the leg and then throwing yourself in a cage full of hungry lions all the while being pelted with stones. (Moral: Do not float a production software without thoroughly testing first)"
},
{
"code": null,
"e": 15562,
"s": 15467,
"text": "A lot more could be added to the above list, but maybe that’s something for another blog post."
},
{
"code": null,
"e": 15620,
"s": 15562,
"text": "Github repo: https://github.com/tanujjain/deploy-ml-model"
}
] |
How to add color breezing effect using pygame? - GeeksforGeeks
|
19 Apr, 2022
Pygame is a python library that can be used specifically to design and build games. Pygame supports only 2d games that are built using different sprites. Pygame is not particularly best for designing games as it is very complex to use and doesn’t have a proper GUI like unity but it definitely builds logic for further complex projects.
Before initializing pygame library we need to install it. To install it type the below command in the terminal.
pip install pygame
Pygame contains color coding in the format of a tuple that contains three values, these values indicate the intensities of the three core colors i.e. red, blue, green. The values of the individual colors can be changed in order to make another unique color. As the values of the tuple are mutable at the run time too, it gives us the flexibility to add some color effects to make our game/application more unique and beautiful.
one of the color effects is a breezing effect, a breezing effect is an effect in which the color changes from one shade to another smoothly without sudden or abrupt change. These effects can be seen in the RGB keyboard and mouse.
Example:
Python3
import pygameimport randomimport sys # initializing the constructorpygame.init() # setting up variable screenscreen = pygame.display.set_mode((720,720)) # three arguments of the color tuplec1 = random.randint(0,255)c2 = random.randint(0,255)c3 = random.randint(0,255) # setting up variable clockclock = pygame.time.Clock() while True: for ev in pygame.event.get(): if ev.type == pygame.QUIT: pygame.quit() # increases the shade of # the current color if 0 < c1 < 255: c1 += 1 # if value of c1 exceeds # 255 it resets it to 0 elif c1 >= 255: c1 -= 255 # if value of c1 precedes 0 # it is incremented by 3 elif c1 <= 0: c1 += 3 # sets game fps to 60 clock.tick(60) # sets bg color to tuple # (c1,c2,c3) screen.fill((c1,c2,c3)) # updates the frames of # the game pygame.display.update()
Output:
anshitaagarwal
gabaa406
sagartomar9927
Python-PyGame
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 25823,
"s": 25795,
"text": "\n19 Apr, 2022"
},
{
"code": null,
"e": 26160,
"s": 25823,
"text": "Pygame is a python library that can be used specifically to design and build games. Pygame supports only 2d games that are built using different sprites. Pygame is not particularly best for designing games as it is very complex to use and doesn’t have a proper GUI like unity but it definitely builds logic for further complex projects."
},
{
"code": null,
"e": 26272,
"s": 26160,
"text": "Before initializing pygame library we need to install it. To install it type the below command in the terminal."
},
{
"code": null,
"e": 26291,
"s": 26272,
"text": "pip install pygame"
},
{
"code": null,
"e": 26719,
"s": 26291,
"text": "Pygame contains color coding in the format of a tuple that contains three values, these values indicate the intensities of the three core colors i.e. red, blue, green. The values of the individual colors can be changed in order to make another unique color. As the values of the tuple are mutable at the run time too, it gives us the flexibility to add some color effects to make our game/application more unique and beautiful."
},
{
"code": null,
"e": 26949,
"s": 26719,
"text": "one of the color effects is a breezing effect, a breezing effect is an effect in which the color changes from one shade to another smoothly without sudden or abrupt change. These effects can be seen in the RGB keyboard and mouse."
},
{
"code": null,
"e": 26958,
"s": 26949,
"text": "Example:"
},
{
"code": null,
"e": 26966,
"s": 26958,
"text": "Python3"
},
{
"code": "import pygameimport randomimport sys # initializing the constructorpygame.init() # setting up variable screenscreen = pygame.display.set_mode((720,720)) # three arguments of the color tuplec1 = random.randint(0,255)c2 = random.randint(0,255)c3 = random.randint(0,255) # setting up variable clockclock = pygame.time.Clock() while True: for ev in pygame.event.get(): if ev.type == pygame.QUIT: pygame.quit() # increases the shade of # the current color if 0 < c1 < 255: c1 += 1 # if value of c1 exceeds # 255 it resets it to 0 elif c1 >= 255: c1 -= 255 # if value of c1 precedes 0 # it is incremented by 3 elif c1 <= 0: c1 += 3 # sets game fps to 60 clock.tick(60) # sets bg color to tuple # (c1,c2,c3) screen.fill((c1,c2,c3)) # updates the frames of # the game pygame.display.update()",
"e": 27894,
"s": 26966,
"text": null
},
{
"code": null,
"e": 27903,
"s": 27894,
"text": "Output: "
},
{
"code": null,
"e": 27920,
"s": 27905,
"text": "anshitaagarwal"
},
{
"code": null,
"e": 27929,
"s": 27920,
"text": "gabaa406"
},
{
"code": null,
"e": 27944,
"s": 27929,
"text": "sagartomar9927"
},
{
"code": null,
"e": 27958,
"s": 27944,
"text": "Python-PyGame"
},
{
"code": null,
"e": 27965,
"s": 27958,
"text": "Python"
},
{
"code": null,
"e": 28063,
"s": 27965,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28081,
"s": 28063,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28116,
"s": 28081,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28148,
"s": 28116,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28170,
"s": 28148,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28212,
"s": 28170,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28242,
"s": 28212,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28268,
"s": 28242,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28297,
"s": 28268,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28341,
"s": 28297,
"text": "Reading and Writing to text files in Python"
}
] |
Java RMI - Quick Guide
|
RMI stands for Remote Method Invocation. It is a mechanism that allows an object residing in one system (JVM) to access/invoke an object running on another JVM.
RMI is used to build distributed applications; it provides remote communication between Java programs. It is provided in the package java.rmi.
In an RMI application, we write two programs, a server program (resides on the server) and a client program (resides on the client).
Inside the server program, a remote object is created and reference of that object is made available for the client (using the registry).
Inside the server program, a remote object is created and reference of that object is made available for the client (using the registry).
The client program requests the remote objects on the server and tries to invoke its methods.
The client program requests the remote objects on the server and tries to invoke its methods.
The following diagram shows the architecture of an RMI application.
Let us now discuss the components of this architecture.
Transport Layer − This layer connects the client and the server. It manages the existing connection and also sets up new connections.
Transport Layer − This layer connects the client and the server. It manages the existing connection and also sets up new connections.
Stub − A stub is a representation (proxy) of the remote object at client. It resides in the client system; it acts as a gateway for the client program.
Stub − A stub is a representation (proxy) of the remote object at client. It resides in the client system; it acts as a gateway for the client program.
Skeleton − This is the object which resides on the server side. stub communicates with this skeleton to pass request to the remote object.
Skeleton − This is the object which resides on the server side. stub communicates with this skeleton to pass request to the remote object.
RRL(Remote Reference Layer) − It is the layer which manages the references made by the client to the remote object.
RRL(Remote Reference Layer) − It is the layer which manages the references made by the client to the remote object.
The following points summarize how an RMI application works −
When the client makes a call to the remote object, it is received by the stub which eventually passes this request to the RRL.
When the client makes a call to the remote object, it is received by the stub which eventually passes this request to the RRL.
When the client-side RRL receives the request, it invokes a method called invoke() of the object remoteRef. It passes the request to the RRL on the server side.
When the client-side RRL receives the request, it invokes a method called invoke() of the object remoteRef. It passes the request to the RRL on the server side.
The RRL on the server side passes the request to the Skeleton (proxy on the server) which finally invokes the required object on the server.
The RRL on the server side passes the request to the Skeleton (proxy on the server) which finally invokes the required object on the server.
The result is passed all the way back to the client.
The result is passed all the way back to the client.
Whenever a client invokes a method that accepts parameters on a remote object, the parameters are bundled into a message before being sent over the network. These parameters may be of primitive type or objects. In case of primitive type, the parameters are put together and a header is attached to it. In case the parameters are objects, then they are serialized. This process is known as marshalling.
At the server side, the packed parameters are unbundled and then the required method is invoked. This process is known as unmarshalling.
RMI registry is a namespace on which all server objects are placed. Each time the server creates an object, it registers this object with the RMIregistry (using bind() or reBind() methods). These are registered using a unique name known as bind name.
To invoke a remote object, the client needs a reference of that object. At that time, the client fetches the object from the registry using its bind name (using lookup() method).
The following illustration explains the entire process −
Following are the goals of RMI −
To minimize the complexity of the application.
To preserve type safety.
Distributed garbage collection.
Minimize the difference between working with local and remote objects.
To write an RMI Java application, you would have to follow the steps given below −
Define the remote interface
Develop the implementation class (remote object)
Develop the server program
Develop the client program
Compile the application
Execute the application
A remote interface provides the description of all the methods of a particular remote object. The client communicates with this remote interface.
To create a remote interface −
Create an interface that extends the predefined interface Remote which belongs to the package.
Create an interface that extends the predefined interface Remote which belongs to the package.
Declare all the business methods that can be invoked by the client in this interface.
Declare all the business methods that can be invoked by the client in this interface.
Since there is a chance of network issues during remote calls, an exception named RemoteException may occur; throw it.
Since there is a chance of network issues during remote calls, an exception named RemoteException may occur; throw it.
Following is an example of a remote interface. Here we have defined an interface with the name Hello and it has a method called printMsg().
import java.rmi.Remote;
import java.rmi.RemoteException;
// Creating Remote interface for our application
public interface Hello extends Remote {
void printMsg() throws RemoteException;
}
We need to implement the remote interface created in the earlier step. (We can write an implementation class separately or we can directly make the server program implement this interface.)
To develop an implementation class −
Implement the interface created in the previous step.
Provide implementation to all the abstract methods of the remote interface.
Following is an implementation class. Here, we have created a class named ImplExample and implemented the interface Hello created in the previous step and provided body for this method which prints a message.
// Implementing the remote interface
public class ImplExample implements Hello {
// Implementing the interface method
public void printMsg() {
System.out.println("This is an example RMI program");
}
}
An RMI server program should implement the remote interface or extend the implementation class. Here, we should create a remote object and bind it to the RMIregistry.
To develop a server program −
Create a client class from where you want invoke the remote object.
Create a client class from where you want invoke the remote object.
Create a remote object by instantiating the implementation class as shown below.
Create a remote object by instantiating the implementation class as shown below.
Export the remote object using the method exportObject() of the class named UnicastRemoteObject which belongs to the package java.rmi.server.
Export the remote object using the method exportObject() of the class named UnicastRemoteObject which belongs to the package java.rmi.server.
Get the RMI registry using the getRegistry() method of the LocateRegistry class which belongs to the package java.rmi.registry.
Get the RMI registry using the getRegistry() method of the LocateRegistry class which belongs to the package java.rmi.registry.
Bind the remote object created to the registry using the bind() method of the class named Registry. To this method, pass a string representing the bind name and the object exported, as parameters.
Bind the remote object created to the registry using the bind() method of the class named Registry. To this method, pass a string representing the bind name and the object exported, as parameters.
Following is an example of an RMI server program.
import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class Server extends ImplExample {
public Server() {}
public static void main(String args[]) {
try {
// Instantiating the implementation class
ImplExample obj = new ImplExample();
// Exporting the object of implementation class
// (here we are exporting the remote object to the stub)
Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);
// Binding the remote object (stub) in the registry
Registry registry = LocateRegistry.getRegistry();
registry.bind("Hello", stub);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
Write a client program in it, fetch the remote object and invoke the required method using this object.
To develop a client program −
Create a client class from where your intended to invoke the remote object.
Create a client class from where your intended to invoke the remote object.
Get the RMI registry using the getRegistry() method of the LocateRegistry class which belongs to the package java.rmi.registry.
Get the RMI registry using the getRegistry() method of the LocateRegistry class which belongs to the package java.rmi.registry.
Fetch the object from the registry using the method lookup() of the class Registry which belongs to the package java.rmi.registry.
To this method, you need to pass a string value representing the bind name as a parameter. This will return you the remote object.
Fetch the object from the registry using the method lookup() of the class Registry which belongs to the package java.rmi.registry.
To this method, you need to pass a string value representing the bind name as a parameter. This will return you the remote object.
The lookup() returns an object of type remote, down cast it to the type Hello.
The lookup() returns an object of type remote, down cast it to the type Hello.
Finally invoke the required method using the obtained remote object.
Finally invoke the required method using the obtained remote object.
Following is an example of an RMI client program.
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Client {
private Client() {}
public static void main(String[] args) {
try {
// Getting the registry
Registry registry = LocateRegistry.getRegistry(null);
// Looking up the registry for the remote object
Hello stub = (Hello) registry.lookup("Hello");
// Calling the remote method using the obtained object
stub.printMsg();
// System.out.println("Remote method invoked");
} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
}
To compile the application −
Compile the Remote interface.
Compile the implementation class.
Compile the server program.
Compile the client program.
Or,
Open the folder where you have stored all the programs and compile all the Java files as shown below.
Javac *.java
Step 1 − Start the rmi registry using the following command.
start rmiregistry
This will start an rmi registry on a separate window as shown below.
Step 2 − Run the server class file as shown below.
Java Server
Step 3 − Run the client class file as shown below.
java Client
Verification − As soon you start the client, you would see the following output in the server.
In the previous chapter, we created a sample RMI application. In this chapter, we will explain how to create an RMI application where a client invokes a method which displays a GUI window (JavaFX).
Here, we are defining a remote interface named Hello with a method named animation() in it.
import java.rmi.Remote;
import java.rmi.RemoteException;
// Creating Remote interface for our application
public interface Hello extends Remote {
void animation() throws RemoteException;
}
In the Implementation class (Remote Object) of this application, we are trying to create a window which displays GUI content, using JavaFX.
import javafx.animation.RotateTransition;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.scene.paint.Color;
import javafx.scene.paint.PhongMaterial;
import javafx.scene.shape.Box;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.transform.Rotate;
import javafx.stage.Stage;
import javafx.util.Duration;
// Implementing the remote interface
public class FxSample extends Application implements Hello {
@Override
public void start(Stage stage) {
// Drawing a Box
Box box = new Box();
// Setting the properties of the Box
box.setWidth(150.0);
box.setHeight(150.0);
box.setDepth(100.0);
// Setting the position of the box
box.setTranslateX(350);
box.setTranslateY(150);
box.setTranslateZ(50);
// Setting the text
Text text = new Text(
"Type any letter to rotate the box, and click on the box to stop the rotation");
// Setting the font of the text
text.setFont(Font.font(null, FontWeight.BOLD, 15));
// Setting the color of the text
text.setFill(Color.CRIMSON);
// Setting the position of the text
text.setX(20);
text.setY(50);
// Setting the material of the box
PhongMaterial material = new PhongMaterial();
material.setDiffuseColor(Color.DARKSLATEBLUE);
// Setting the diffuse color material to box
box.setMaterial(material);
// Setting the rotation animation to the box
RotateTransition rotateTransition = new RotateTransition();
// Setting the duration for the transition
rotateTransition.setDuration(Duration.millis(1000));
// Setting the node for the transition
rotateTransition.setNode(box);
// Setting the axis of the rotation
rotateTransition.setAxis(Rotate.Y_AXIS);
// Setting the angle of the rotation
rotateTransition.setByAngle(360);
// Setting the cycle count for the transition
rotateTransition.setCycleCount(50);
// Setting auto reverse value to false
rotateTransition.setAutoReverse(false);
// Creating a text filed
TextField textField = new TextField();
// Setting the position of the text field
textField.setLayoutX(50);
textField.setLayoutY(100);
// Handling the key typed event
EventHandler<KeyEvent> eventHandlerTextField = new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
// Playing the animation
rotateTransition.play();
}
};
// Adding an event handler to the text feld
textField.addEventHandler(KeyEvent.KEY_TYPED, eventHandlerTextField);
// Handling the mouse clicked event(on box)
EventHandler<javafx.scene.input.MouseEvent> eventHandlerBox =
new EventHandler<javafx.scene.input.MouseEvent>() {
@Override
public void handle(javafx.scene.input.MouseEvent e) {
rotateTransition.stop();
}
};
// Adding the event handler to the box
box.addEventHandler(javafx.scene.input.MouseEvent.MOUSE_CLICKED, eventHandlerBox);
// Creating a Group object
Group root = new Group(box, textField, text);
// Creating a scene object
Scene scene = new Scene(root, 600, 300);
// Setting camera
PerspectiveCamera camera = new PerspectiveCamera(false);
camera.setTranslateX(0);
camera.setTranslateY(0);
camera.setTranslateZ(0);
scene.setCamera(camera);
// Setting title to the Stage
stage.setTitle("Event Handlers Example");
// Adding scene to the stage
stage.setScene(scene);
// Displaying the contents of the stage
stage.show();
}
// Implementing the interface method
public void animation() {
launch();
}
}
An RMI server program should implement the remote interface or extend the implementation class. Here, we should create a remote object and bind it to the RMIregistry.
Following is the server program of this application. Here, we will extend the above created class, create a remote object, and registered it to the RMI registry with the bind name hello.
import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class Server extends FxSample {
public Server() {}
public static void main(String args[]) {
try {
// Instantiating the implementation class
FxSample obj = new FxSample();
// Exporting the object of implementation class
// (here we are exporting the remote object to the stub)
Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);
// Binding the remote object (stub) in the registry
Registry registry = LocateRegistry.getRegistry();
registry.bind("Hello", stub);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
Following is the client program of this application. Here, we are fetching the remote object and invoking its method named animation().
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Client {
private Client() {}
public static void main(String[] args) {
try {
// Getting the registry
Registry registry = LocateRegistry.getRegistry(null);
// Looking up the registry for the remote object
Hello stub = (Hello) registry.lookup("Hello");
// Calling the remote method using the obtained object
stub.animation();
System.out.println("Remote method invoked");
} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
}
Following are the steps to run our RMI Example.
Step 1 − Open the folder where you have stored all the programs and compile all the Java files as shown below.
Javac *.java
Step 2 − Start the rmi registry using the following command.
start rmiregistry
This will start an rmi registry on a separate window as shown below.
Step 3 − Run the server class file as shown below.
Java Server
Step 4 − Run the client class file as shown below.
java Client
Verification − As soon you start the client, you would see the following output in the server.
In the previous chapter, we created a sample RMI application where a client invokes a method which displays a GUI window (JavaFX).
In this chapter, we will take an example to see how a client program can retrieve the records of a table in MySQL database residing on the server.
Assume we have a table named student_data in the database details as shown below.
+----+--------+--------+------------+---------------------+
| ID | NAME | BRANCH | PERCENTAGE | EMAIL |
+----+--------+--------+------------+---------------------+
| 1 | Ram | IT | 85 | ram123@gmail.com |
| 2 | Rahim | EEE | 95 | rahim123@gmail.com |
| 3 | Robert | ECE | 90 | robert123@gmail.com |
+----+--------+--------+------------+---------------------+
Assume the name of the user is myuser and its password is password.
Create a Student class with setter and getter methods as shown below.
public class Student implements java.io.Serializable {
private int id, percent;
private String name, branch, email;
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getBranch() {
return branch;
}
public int getPercent() {
return percent;
}
public String getEmail() {
return email;
}
public void setID(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setBranch(String branch) {
this.branch = branch;
}
public void setPercent(int percent) {
this.percent = percent;
}
public void setEmail(String email) {
this.email = email;
}
}
Define the remote interface. Here, we are defining a remote interface named Hello with a method named getStudents () in it. This method returns a list which contains the object of the class Student.
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.*;
// Creating Remote interface for our application
public interface Hello extends Remote {
public List<Student> getStudents() throws Exception;
}
Create a class and implement the above created interface.
Here we are implementing the getStudents() method of the Remote interface. When you invoke this method, it retrieves the records of a table named student_data. Sets these values to the Student class using its setter methods, adds it to a list object and returns that list.
import java.sql.*;
import java.util.*;
// Implementing the remote interface
public class ImplExample implements Hello {
// Implementing the interface method
public List<Student> getStudents() throws Exception {
List<Student> list = new ArrayList<Student>();
// JDBC driver name and database URL
String JDBC_DRIVER = "com.mysql.jdbc.Driver";
String DB_URL = "jdbc:mysql://localhost:3306/details";
// Database credentials
String USER = "myuser";
String PASS = "password";
Connection conn = null;
Statement stmt = null;
//Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "SELECT * FROM student_data";
ResultSet rs = stmt.executeQuery(sql);
//Extract data from result set
while(rs.next()) {
// Retrieve by column name
int id = rs.getInt("id");
String name = rs.getString("name");
String branch = rs.getString("branch");
int percent = rs.getInt("percentage");
String email = rs.getString("email");
// Setting the values
Student student = new Student();
student.setID(id);
student.setName(name);
student.setBranch(branch);
student.setPercent(percent);
student.setEmail(email);
list.add(student);
}
rs.close();
return list;
}
}
An RMI server program should implement the remote interface or extend the implementation class. Here, we should create a remote object and bind it to the RMI registry.
Following is the server program of this application. Here, we will extend the above created class, create a remote object and register it to the RMI registry with the bind name hello.
import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class Server extends ImplExample {
public Server() {}
public static void main(String args[]) {
try {
// Instantiating the implementation class
ImplExample obj = new ImplExample();
// Exporting the object of implementation class (
here we are exporting the remote object to the stub)
Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);
// Binding the remote object (stub) in the registry
Registry registry = LocateRegistry.getRegistry();
registry.bind("Hello", stub);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
Following is the client program of this application. Here, we are fetching the remote object and invoking the method named getStudents(). It retrieves the records of the table from the list object and displays them.
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.*;
public class Client {
private Client() {}
public static void main(String[] args)throws Exception {
try {
// Getting the registry
Registry registry = LocateRegistry.getRegistry(null);
// Looking up the registry for the remote object
Hello stub = (Hello) registry.lookup("Hello");
// Calling the remote method using the obtained object
List<Student> list = (List)stub.getStudents();
for (Student s:list)v {
// System.out.println("bc "+s.getBranch());
System.out.println("ID: " + s.getId());
System.out.println("name: " + s.getName());
System.out.println("branch: " + s.getBranch());
System.out.println("percent: " + s.getPercent());
System.out.println("email: " + s.getEmail());
}
// System.out.println(list);
} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
}
Following are the steps to run our RMI Example.
Step 1 − Open the folder where you have stored all the programs and compile all the Java files as shown below.
Javac *.java
Step 2 − Start the rmi registry using the following command.
start rmiregistry
This will start an rmi registry on a separate window as shown below.
Step 3 − Run the server class file as shown below.
Java Server
Step 4 − Run the client class file as shown below.
java Client
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1858,
"s": 1697,
"text": "RMI stands for Remote Method Invocation. It is a mechanism that allows an object residing in one system (JVM) to access/invoke an object running on another JVM."
},
{
"code": null,
"e": 2001,
"s": 1858,
"text": "RMI is used to build distributed applications; it provides remote communication between Java programs. It is provided in the package java.rmi."
},
{
"code": null,
"e": 2134,
"s": 2001,
"text": "In an RMI application, we write two programs, a server program (resides on the server) and a client program (resides on the client)."
},
{
"code": null,
"e": 2272,
"s": 2134,
"text": "Inside the server program, a remote object is created and reference of that object is made available for the client (using the registry)."
},
{
"code": null,
"e": 2410,
"s": 2272,
"text": "Inside the server program, a remote object is created and reference of that object is made available for the client (using the registry)."
},
{
"code": null,
"e": 2504,
"s": 2410,
"text": "The client program requests the remote objects on the server and tries to invoke its methods."
},
{
"code": null,
"e": 2598,
"s": 2504,
"text": "The client program requests the remote objects on the server and tries to invoke its methods."
},
{
"code": null,
"e": 2666,
"s": 2598,
"text": "The following diagram shows the architecture of an RMI application."
},
{
"code": null,
"e": 2722,
"s": 2666,
"text": "Let us now discuss the components of this architecture."
},
{
"code": null,
"e": 2856,
"s": 2722,
"text": "Transport Layer − This layer connects the client and the server. It manages the existing connection and also sets up new connections."
},
{
"code": null,
"e": 2990,
"s": 2856,
"text": "Transport Layer − This layer connects the client and the server. It manages the existing connection and also sets up new connections."
},
{
"code": null,
"e": 3142,
"s": 2990,
"text": "Stub − A stub is a representation (proxy) of the remote object at client. It resides in the client system; it acts as a gateway for the client program."
},
{
"code": null,
"e": 3294,
"s": 3142,
"text": "Stub − A stub is a representation (proxy) of the remote object at client. It resides in the client system; it acts as a gateway for the client program."
},
{
"code": null,
"e": 3433,
"s": 3294,
"text": "Skeleton − This is the object which resides on the server side. stub communicates with this skeleton to pass request to the remote object."
},
{
"code": null,
"e": 3572,
"s": 3433,
"text": "Skeleton − This is the object which resides on the server side. stub communicates with this skeleton to pass request to the remote object."
},
{
"code": null,
"e": 3689,
"s": 3572,
"text": "RRL(Remote Reference Layer) − It is the layer which manages the references made by the client to the remote object. "
},
{
"code": null,
"e": 3806,
"s": 3689,
"text": "RRL(Remote Reference Layer) − It is the layer which manages the references made by the client to the remote object. "
},
{
"code": null,
"e": 3868,
"s": 3806,
"text": "The following points summarize how an RMI application works −"
},
{
"code": null,
"e": 3995,
"s": 3868,
"text": "When the client makes a call to the remote object, it is received by the stub which eventually passes this request to the RRL."
},
{
"code": null,
"e": 4122,
"s": 3995,
"text": "When the client makes a call to the remote object, it is received by the stub which eventually passes this request to the RRL."
},
{
"code": null,
"e": 4283,
"s": 4122,
"text": "When the client-side RRL receives the request, it invokes a method called invoke() of the object remoteRef. It passes the request to the RRL on the server side."
},
{
"code": null,
"e": 4444,
"s": 4283,
"text": "When the client-side RRL receives the request, it invokes a method called invoke() of the object remoteRef. It passes the request to the RRL on the server side."
},
{
"code": null,
"e": 4585,
"s": 4444,
"text": "The RRL on the server side passes the request to the Skeleton (proxy on the server) which finally invokes the required object on the server."
},
{
"code": null,
"e": 4726,
"s": 4585,
"text": "The RRL on the server side passes the request to the Skeleton (proxy on the server) which finally invokes the required object on the server."
},
{
"code": null,
"e": 4779,
"s": 4726,
"text": "The result is passed all the way back to the client."
},
{
"code": null,
"e": 4832,
"s": 4779,
"text": "The result is passed all the way back to the client."
},
{
"code": null,
"e": 5234,
"s": 4832,
"text": "Whenever a client invokes a method that accepts parameters on a remote object, the parameters are bundled into a message before being sent over the network. These parameters may be of primitive type or objects. In case of primitive type, the parameters are put together and a header is attached to it. In case the parameters are objects, then they are serialized. This process is known as marshalling."
},
{
"code": null,
"e": 5371,
"s": 5234,
"text": "At the server side, the packed parameters are unbundled and then the required method is invoked. This process is known as unmarshalling."
},
{
"code": null,
"e": 5622,
"s": 5371,
"text": "RMI registry is a namespace on which all server objects are placed. Each time the server creates an object, it registers this object with the RMIregistry (using bind() or reBind() methods). These are registered using a unique name known as bind name."
},
{
"code": null,
"e": 5801,
"s": 5622,
"text": "To invoke a remote object, the client needs a reference of that object. At that time, the client fetches the object from the registry using its bind name (using lookup() method)."
},
{
"code": null,
"e": 5858,
"s": 5801,
"text": "The following illustration explains the entire process −"
},
{
"code": null,
"e": 5891,
"s": 5858,
"text": "Following are the goals of RMI −"
},
{
"code": null,
"e": 5938,
"s": 5891,
"text": "To minimize the complexity of the application."
},
{
"code": null,
"e": 5963,
"s": 5938,
"text": "To preserve type safety."
},
{
"code": null,
"e": 5995,
"s": 5963,
"text": "Distributed garbage collection."
},
{
"code": null,
"e": 6066,
"s": 5995,
"text": "Minimize the difference between working with local and remote objects."
},
{
"code": null,
"e": 6149,
"s": 6066,
"text": "To write an RMI Java application, you would have to follow the steps given below −"
},
{
"code": null,
"e": 6177,
"s": 6149,
"text": "Define the remote interface"
},
{
"code": null,
"e": 6226,
"s": 6177,
"text": "Develop the implementation class (remote object)"
},
{
"code": null,
"e": 6253,
"s": 6226,
"text": "Develop the server program"
},
{
"code": null,
"e": 6280,
"s": 6253,
"text": "Develop the client program"
},
{
"code": null,
"e": 6304,
"s": 6280,
"text": "Compile the application"
},
{
"code": null,
"e": 6328,
"s": 6304,
"text": "Execute the application"
},
{
"code": null,
"e": 6474,
"s": 6328,
"text": "A remote interface provides the description of all the methods of a particular remote object. The client communicates with this remote interface."
},
{
"code": null,
"e": 6505,
"s": 6474,
"text": "To create a remote interface −"
},
{
"code": null,
"e": 6600,
"s": 6505,
"text": "Create an interface that extends the predefined interface Remote which belongs to the package."
},
{
"code": null,
"e": 6695,
"s": 6600,
"text": "Create an interface that extends the predefined interface Remote which belongs to the package."
},
{
"code": null,
"e": 6781,
"s": 6695,
"text": "Declare all the business methods that can be invoked by the client in this interface."
},
{
"code": null,
"e": 6867,
"s": 6781,
"text": "Declare all the business methods that can be invoked by the client in this interface."
},
{
"code": null,
"e": 6986,
"s": 6867,
"text": "Since there is a chance of network issues during remote calls, an exception named RemoteException may occur; throw it."
},
{
"code": null,
"e": 7105,
"s": 6986,
"text": "Since there is a chance of network issues during remote calls, an exception named RemoteException may occur; throw it."
},
{
"code": null,
"e": 7245,
"s": 7105,
"text": "Following is an example of a remote interface. Here we have defined an interface with the name Hello and it has a method called printMsg()."
},
{
"code": null,
"e": 7446,
"s": 7245,
"text": "import java.rmi.Remote; \nimport java.rmi.RemoteException; \n\n// Creating Remote interface for our application \npublic interface Hello extends Remote { \n void printMsg() throws RemoteException; \n} "
},
{
"code": null,
"e": 7636,
"s": 7446,
"text": "We need to implement the remote interface created in the earlier step. (We can write an implementation class separately or we can directly make the server program implement this interface.)"
},
{
"code": null,
"e": 7673,
"s": 7636,
"text": "To develop an implementation class −"
},
{
"code": null,
"e": 7727,
"s": 7673,
"text": "Implement the interface created in the previous step."
},
{
"code": null,
"e": 7803,
"s": 7727,
"text": "Provide implementation to all the abstract methods of the remote interface."
},
{
"code": null,
"e": 8012,
"s": 7803,
"text": "Following is an implementation class. Here, we have created a class named ImplExample and implemented the interface Hello created in the previous step and provided body for this method which prints a message."
},
{
"code": null,
"e": 8243,
"s": 8012,
"text": "// Implementing the remote interface \npublic class ImplExample implements Hello { \n \n // Implementing the interface method \n public void printMsg() { \n System.out.println(\"This is an example RMI program\"); \n } \n} "
},
{
"code": null,
"e": 8410,
"s": 8243,
"text": "An RMI server program should implement the remote interface or extend the implementation class. Here, we should create a remote object and bind it to the RMIregistry."
},
{
"code": null,
"e": 8440,
"s": 8410,
"text": "To develop a server program −"
},
{
"code": null,
"e": 8508,
"s": 8440,
"text": "Create a client class from where you want invoke the remote object."
},
{
"code": null,
"e": 8576,
"s": 8508,
"text": "Create a client class from where you want invoke the remote object."
},
{
"code": null,
"e": 8657,
"s": 8576,
"text": "Create a remote object by instantiating the implementation class as shown below."
},
{
"code": null,
"e": 8738,
"s": 8657,
"text": "Create a remote object by instantiating the implementation class as shown below."
},
{
"code": null,
"e": 8880,
"s": 8738,
"text": "Export the remote object using the method exportObject() of the class named UnicastRemoteObject which belongs to the package java.rmi.server."
},
{
"code": null,
"e": 9022,
"s": 8880,
"text": "Export the remote object using the method exportObject() of the class named UnicastRemoteObject which belongs to the package java.rmi.server."
},
{
"code": null,
"e": 9150,
"s": 9022,
"text": "Get the RMI registry using the getRegistry() method of the LocateRegistry class which belongs to the package java.rmi.registry."
},
{
"code": null,
"e": 9278,
"s": 9150,
"text": "Get the RMI registry using the getRegistry() method of the LocateRegistry class which belongs to the package java.rmi.registry."
},
{
"code": null,
"e": 9475,
"s": 9278,
"text": "Bind the remote object created to the registry using the bind() method of the class named Registry. To this method, pass a string representing the bind name and the object exported, as parameters."
},
{
"code": null,
"e": 9672,
"s": 9475,
"text": "Bind the remote object created to the registry using the bind() method of the class named Registry. To this method, pass a string representing the bind name and the object exported, as parameters."
},
{
"code": null,
"e": 9722,
"s": 9672,
"text": "Following is an example of an RMI server program."
},
{
"code": null,
"e": 10684,
"s": 9722,
"text": "import java.rmi.registry.Registry; \nimport java.rmi.registry.LocateRegistry; \nimport java.rmi.RemoteException; \nimport java.rmi.server.UnicastRemoteObject; \n\npublic class Server extends ImplExample { \n public Server() {} \n public static void main(String args[]) { \n try { \n // Instantiating the implementation class \n ImplExample obj = new ImplExample(); \n \n // Exporting the object of implementation class \n // (here we are exporting the remote object to the stub) \n Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0); \n \n // Binding the remote object (stub) in the registry \n Registry registry = LocateRegistry.getRegistry(); \n \n registry.bind(\"Hello\", stub); \n System.err.println(\"Server ready\"); \n } catch (Exception e) { \n System.err.println(\"Server exception: \" + e.toString()); \n e.printStackTrace(); \n } \n } \n} "
},
{
"code": null,
"e": 10788,
"s": 10684,
"text": "Write a client program in it, fetch the remote object and invoke the required method using this object."
},
{
"code": null,
"e": 10818,
"s": 10788,
"text": "To develop a client program −"
},
{
"code": null,
"e": 10894,
"s": 10818,
"text": "Create a client class from where your intended to invoke the remote object."
},
{
"code": null,
"e": 10970,
"s": 10894,
"text": "Create a client class from where your intended to invoke the remote object."
},
{
"code": null,
"e": 11098,
"s": 10970,
"text": "Get the RMI registry using the getRegistry() method of the LocateRegistry class which belongs to the package java.rmi.registry."
},
{
"code": null,
"e": 11226,
"s": 11098,
"text": "Get the RMI registry using the getRegistry() method of the LocateRegistry class which belongs to the package java.rmi.registry."
},
{
"code": null,
"e": 11488,
"s": 11226,
"text": "Fetch the object from the registry using the method lookup() of the class Registry which belongs to the package java.rmi.registry.\nTo this method, you need to pass a string value representing the bind name as a parameter. This will return you the remote object."
},
{
"code": null,
"e": 11619,
"s": 11488,
"text": "Fetch the object from the registry using the method lookup() of the class Registry which belongs to the package java.rmi.registry."
},
{
"code": null,
"e": 11750,
"s": 11619,
"text": "To this method, you need to pass a string value representing the bind name as a parameter. This will return you the remote object."
},
{
"code": null,
"e": 11829,
"s": 11750,
"text": "The lookup() returns an object of type remote, down cast it to the type Hello."
},
{
"code": null,
"e": 11908,
"s": 11829,
"text": "The lookup() returns an object of type remote, down cast it to the type Hello."
},
{
"code": null,
"e": 11977,
"s": 11908,
"text": "Finally invoke the required method using the obtained remote object."
},
{
"code": null,
"e": 12046,
"s": 11977,
"text": "Finally invoke the required method using the obtained remote object."
},
{
"code": null,
"e": 12096,
"s": 12046,
"text": "Following is an example of an RMI client program."
},
{
"code": null,
"e": 12814,
"s": 12096,
"text": "import java.rmi.registry.LocateRegistry; \nimport java.rmi.registry.Registry; \n\npublic class Client { \n private Client() {} \n public static void main(String[] args) { \n try { \n // Getting the registry \n Registry registry = LocateRegistry.getRegistry(null); \n \n // Looking up the registry for the remote object \n Hello stub = (Hello) registry.lookup(\"Hello\"); \n \n // Calling the remote method using the obtained object \n stub.printMsg(); \n \n // System.out.println(\"Remote method invoked\"); \n } catch (Exception e) {\n System.err.println(\"Client exception: \" + e.toString()); \n e.printStackTrace(); \n } \n } \n}"
},
{
"code": null,
"e": 12843,
"s": 12814,
"text": "To compile the application −"
},
{
"code": null,
"e": 12873,
"s": 12843,
"text": "Compile the Remote interface."
},
{
"code": null,
"e": 12907,
"s": 12873,
"text": "Compile the implementation class."
},
{
"code": null,
"e": 12935,
"s": 12907,
"text": "Compile the server program."
},
{
"code": null,
"e": 12963,
"s": 12935,
"text": "Compile the client program."
},
{
"code": null,
"e": 12967,
"s": 12963,
"text": "Or,"
},
{
"code": null,
"e": 13069,
"s": 12967,
"text": "Open the folder where you have stored all the programs and compile all the Java files as shown below."
},
{
"code": null,
"e": 13083,
"s": 13069,
"text": "Javac *.java\n"
},
{
"code": null,
"e": 13144,
"s": 13083,
"text": "Step 1 − Start the rmi registry using the following command."
},
{
"code": null,
"e": 13163,
"s": 13144,
"text": "start rmiregistry\n"
},
{
"code": null,
"e": 13232,
"s": 13163,
"text": "This will start an rmi registry on a separate window as shown below."
},
{
"code": null,
"e": 13283,
"s": 13232,
"text": "Step 2 − Run the server class file as shown below."
},
{
"code": null,
"e": 13296,
"s": 13283,
"text": "Java Server\n"
},
{
"code": null,
"e": 13347,
"s": 13296,
"text": "Step 3 − Run the client class file as shown below."
},
{
"code": null,
"e": 13361,
"s": 13347,
"text": "java Client \n"
},
{
"code": null,
"e": 13456,
"s": 13361,
"text": "Verification − As soon you start the client, you would see the following output in the server."
},
{
"code": null,
"e": 13654,
"s": 13456,
"text": "In the previous chapter, we created a sample RMI application. In this chapter, we will explain how to create an RMI application where a client invokes a method which displays a GUI window (JavaFX)."
},
{
"code": null,
"e": 13746,
"s": 13654,
"text": "Here, we are defining a remote interface named Hello with a method named animation() in it."
},
{
"code": null,
"e": 13945,
"s": 13746,
"text": "import java.rmi.Remote; \nimport java.rmi.RemoteException; \n\n// Creating Remote interface for our application \npublic interface Hello extends Remote { \n void animation() throws RemoteException; \n}"
},
{
"code": null,
"e": 14085,
"s": 13945,
"text": "In the Implementation class (Remote Object) of this application, we are trying to create a window which displays GUI content, using JavaFX."
},
{
"code": null,
"e": 18447,
"s": 14085,
"text": "import javafx.animation.RotateTransition; \nimport javafx.application.Application; \nimport javafx.event.EventHandler; \n\nimport javafx.scene.Group; \nimport javafx.scene.PerspectiveCamera; \nimport javafx.scene.Scene; \nimport javafx.scene.control.TextField; \nimport javafx.scene.input.KeyEvent; \nimport javafx.scene.paint.Color; \nimport javafx.scene.paint.PhongMaterial; \n \nimport javafx.scene.shape.Box; \nimport javafx.scene.text.Font; \nimport javafx.scene.text.FontWeight;\nimport javafx.scene.text.Text; \nimport javafx.scene.transform.Rotate; \n\nimport javafx.stage.Stage; \nimport javafx.util.Duration; \n\n// Implementing the remote interface \npublic class FxSample extends Application implements Hello { \n @Override \n public void start(Stage stage) { \n // Drawing a Box \n Box box = new Box(); \n\n // Setting the properties of the Box \n box.setWidth(150.0); \n box.setHeight(150.0); \n box.setDepth(100.0); \n\n // Setting the position of the box \n box.setTranslateX(350); \n box.setTranslateY(150); \n box.setTranslateZ(50); \n\n // Setting the text \n Text text = new Text(\n \"Type any letter to rotate the box, and click on the box to stop the rotation\");\n\n // Setting the font of the text \n text.setFont(Font.font(null, FontWeight.BOLD, 15)); \n\n // Setting the color of the text \n text.setFill(Color.CRIMSON); \n\n // Setting the position of the text \n text.setX(20); \n text.setY(50); \n\n // Setting the material of the box \n PhongMaterial material = new PhongMaterial(); \n material.setDiffuseColor(Color.DARKSLATEBLUE); \n\n // Setting the diffuse color material to box \n box.setMaterial(material); \n\n // Setting the rotation animation to the box \n RotateTransition rotateTransition = new RotateTransition(); \n\n // Setting the duration for the transition \n rotateTransition.setDuration(Duration.millis(1000)); \n\n // Setting the node for the transition \n rotateTransition.setNode(box); \n\n // Setting the axis of the rotation \n rotateTransition.setAxis(Rotate.Y_AXIS); \n\n // Setting the angle of the rotation \n rotateTransition.setByAngle(360); \n\n // Setting the cycle count for the transition \n rotateTransition.setCycleCount(50); \n\n // Setting auto reverse value to false \n rotateTransition.setAutoReverse(false); \n\n // Creating a text filed \n TextField textField = new TextField(); \n\n // Setting the position of the text field \n textField.setLayoutX(50); \n textField.setLayoutY(100); \n\n // Handling the key typed event \n EventHandler<KeyEvent> eventHandlerTextField = new EventHandler<KeyEvent>() { \n @Override \n public void handle(KeyEvent event) { \n // Playing the animation \n rotateTransition.play(); \n } \n }; \n \n // Adding an event handler to the text feld \n textField.addEventHandler(KeyEvent.KEY_TYPED, eventHandlerTextField); \n\n // Handling the mouse clicked event(on box) \n EventHandler<javafx.scene.input.MouseEvent> eventHandlerBox = \n new EventHandler<javafx.scene.input.MouseEvent>() { \n @Override \n public void handle(javafx.scene.input.MouseEvent e) { \n rotateTransition.stop(); \n } \n }; \n \n // Adding the event handler to the box \n box.addEventHandler(javafx.scene.input.MouseEvent.MOUSE_CLICKED, eventHandlerBox); \n\n // Creating a Group object \n Group root = new Group(box, textField, text); \n\n // Creating a scene object \n Scene scene = new Scene(root, 600, 300); \n\n // Setting camera \n PerspectiveCamera camera = new PerspectiveCamera(false); \n camera.setTranslateX(0); \n camera.setTranslateY(0); \n camera.setTranslateZ(0); \n scene.setCamera(camera); \n\n // Setting title to the Stage\n stage.setTitle(\"Event Handlers Example\"); \n\n // Adding scene to the stage \n stage.setScene(scene); \n\n // Displaying the contents of the stage \n stage.show(); \n } \n\n // Implementing the interface method \n public void animation() { \n launch(); \n } \n}"
},
{
"code": null,
"e": 18614,
"s": 18447,
"text": "An RMI server program should implement the remote interface or extend the implementation class. Here, we should create a remote object and bind it to the RMIregistry."
},
{
"code": null,
"e": 18801,
"s": 18614,
"text": "Following is the server program of this application. Here, we will extend the above created class, create a remote object, and registered it to the RMI registry with the bind name hello."
},
{
"code": null,
"e": 19751,
"s": 18801,
"text": "import java.rmi.registry.Registry; \nimport java.rmi.registry.LocateRegistry; \nimport java.rmi.RemoteException; \nimport java.rmi.server.UnicastRemoteObject; \n\npublic class Server extends FxSample { \n public Server() {} \n public static void main(String args[]) { \n try { \n // Instantiating the implementation class \n FxSample obj = new FxSample();\n \n // Exporting the object of implementation class \n // (here we are exporting the remote object to the stub) \n Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0); \n \n // Binding the remote object (stub) in the registry \n Registry registry = LocateRegistry.getRegistry(); \n \n registry.bind(\"Hello\", stub); \n System.err.println(\"Server ready\"); \n } catch (Exception e) { \n System.err.println(\"Server exception: \" + e.toString()); \n e.printStackTrace(); \n } \n } \n}"
},
{
"code": null,
"e": 19887,
"s": 19751,
"text": "Following is the client program of this application. Here, we are fetching the remote object and invoking its method named animation()."
},
{
"code": null,
"e": 20605,
"s": 19887,
"text": "import java.rmi.registry.LocateRegistry; \nimport java.rmi.registry.Registry; \n\npublic class Client { \n private Client() {} \n public static void main(String[] args) { \n try { \n // Getting the registry \n Registry registry = LocateRegistry.getRegistry(null); \n \n // Looking up the registry for the remote object \n Hello stub = (Hello) registry.lookup(\"Hello\"); \n \n // Calling the remote method using the obtained object \n stub.animation(); \n \n System.out.println(\"Remote method invoked\"); \n } catch (Exception e) {\n System.err.println(\"Client exception: \" + e.toString()); \n e.printStackTrace(); \n } \n } \n}"
},
{
"code": null,
"e": 20653,
"s": 20605,
"text": "Following are the steps to run our RMI Example."
},
{
"code": null,
"e": 20764,
"s": 20653,
"text": "Step 1 − Open the folder where you have stored all the programs and compile all the Java files as shown below."
},
{
"code": null,
"e": 20778,
"s": 20764,
"text": "Javac *.java\n"
},
{
"code": null,
"e": 20839,
"s": 20778,
"text": "Step 2 − Start the rmi registry using the following command."
},
{
"code": null,
"e": 20858,
"s": 20839,
"text": "start rmiregistry\n"
},
{
"code": null,
"e": 20927,
"s": 20858,
"text": "This will start an rmi registry on a separate window as shown below."
},
{
"code": null,
"e": 20978,
"s": 20927,
"text": "Step 3 − Run the server class file as shown below."
},
{
"code": null,
"e": 20991,
"s": 20978,
"text": "Java Server\n"
},
{
"code": null,
"e": 21042,
"s": 20991,
"text": "Step 4 − Run the client class file as shown below."
},
{
"code": null,
"e": 21055,
"s": 21042,
"text": "java Client\n"
},
{
"code": null,
"e": 21150,
"s": 21055,
"text": "Verification − As soon you start the client, you would see the following output in the server."
},
{
"code": null,
"e": 21281,
"s": 21150,
"text": "In the previous chapter, we created a sample RMI application where a client invokes a method which displays a GUI window (JavaFX)."
},
{
"code": null,
"e": 21428,
"s": 21281,
"text": "In this chapter, we will take an example to see how a client program can retrieve the records of a table in MySQL database residing on the server."
},
{
"code": null,
"e": 21510,
"s": 21428,
"text": "Assume we have a table named student_data in the database details as shown below."
},
{
"code": null,
"e": 21938,
"s": 21510,
"text": "+----+--------+--------+------------+---------------------+ \n| ID | NAME | BRANCH | PERCENTAGE | EMAIL | \n+----+--------+--------+------------+---------------------+ \n| 1 | Ram | IT | 85 | ram123@gmail.com | \n| 2 | Rahim | EEE | 95 | rahim123@gmail.com | \n| 3 | Robert | ECE | 90 | robert123@gmail.com | \n+----+--------+--------+------------+---------------------+ \n"
},
{
"code": null,
"e": 22006,
"s": 21938,
"text": "Assume the name of the user is myuser and its password is password."
},
{
"code": null,
"e": 22076,
"s": 22006,
"text": "Create a Student class with setter and getter methods as shown below."
},
{
"code": null,
"e": 22855,
"s": 22076,
"text": "public class Student implements java.io.Serializable { \n private int id, percent; \n private String name, branch, email; \n \n public int getId() { \n return id; \n } \n public String getName() { \n return name; \n } \n public String getBranch() { \n return branch; \n } \n public int getPercent() { \n return percent; \n } \n public String getEmail() { \n return email; \n } \n public void setID(int id) { \n this.id = id; \n } \n public void setName(String name) { \n this.name = name; \n } \n public void setBranch(String branch) { \n this.branch = branch; \n } \n public void setPercent(int percent) { \n this.percent = percent; \n } \n public void setEmail(String email) { \n this.email = email; \n } \n}"
},
{
"code": null,
"e": 23054,
"s": 22855,
"text": "Define the remote interface. Here, we are defining a remote interface named Hello with a method named getStudents () in it. This method returns a list which contains the object of the class Student."
},
{
"code": null,
"e": 23286,
"s": 23054,
"text": "import java.rmi.Remote; \nimport java.rmi.RemoteException; \nimport java.util.*;\n\n// Creating Remote interface for our application \npublic interface Hello extends Remote { \n public List<Student> getStudents() throws Exception; \n}"
},
{
"code": null,
"e": 23344,
"s": 23286,
"text": "Create a class and implement the above created interface."
},
{
"code": null,
"e": 23617,
"s": 23344,
"text": "Here we are implementing the getStudents() method of the Remote interface. When you invoke this method, it retrieves the records of a table named student_data. Sets these values to the Student class using its setter methods, adds it to a list object and returns that list."
},
{
"code": null,
"e": 25492,
"s": 23617,
"text": "import java.sql.*; \nimport java.util.*; \n\n// Implementing the remote interface \npublic class ImplExample implements Hello { \n \n // Implementing the interface method \n public List<Student> getStudents() throws Exception { \n List<Student> list = new ArrayList<Student>(); \n \n // JDBC driver name and database URL \n String JDBC_DRIVER = \"com.mysql.jdbc.Driver\"; \n String DB_URL = \"jdbc:mysql://localhost:3306/details\"; \n \n // Database credentials \n String USER = \"myuser\"; \n String PASS = \"password\"; \n \n Connection conn = null; \n Statement stmt = null; \n \n //Register JDBC driver \n Class.forName(\"com.mysql.jdbc.Driver\"); \n \n //Open a connection\n System.out.println(\"Connecting to a selected database...\"); \n conn = DriverManager.getConnection(DB_URL, USER, PASS); \n System.out.println(\"Connected database successfully...\"); \n \n //Execute a query \n System.out.println(\"Creating statement...\"); \n \n stmt = conn.createStatement(); \n String sql = \"SELECT * FROM student_data\"; \n ResultSet rs = stmt.executeQuery(sql); \n \n //Extract data from result set \n while(rs.next()) { \n // Retrieve by column name \n int id = rs.getInt(\"id\"); \n \n String name = rs.getString(\"name\"); \n String branch = rs.getString(\"branch\"); \n \n int percent = rs.getInt(\"percentage\"); \n String email = rs.getString(\"email\"); \n \n // Setting the values \n Student student = new Student(); \n student.setID(id); \n student.setName(name); \n student.setBranch(branch); \n student.setPercent(percent); \n student.setEmail(email); \n list.add(student); \n } \n rs.close(); \n return list; \n } \n}"
},
{
"code": null,
"e": 25660,
"s": 25492,
"text": "An RMI server program should implement the remote interface or extend the implementation class. Here, we should create a remote object and bind it to the RMI registry."
},
{
"code": null,
"e": 25844,
"s": 25660,
"text": "Following is the server program of this application. Here, we will extend the above created class, create a remote object and register it to the RMI registry with the bind name hello."
},
{
"code": null,
"e": 26804,
"s": 25844,
"text": "import java.rmi.registry.Registry; \nimport java.rmi.registry.LocateRegistry; \nimport java.rmi.RemoteException; \nimport java.rmi.server.UnicastRemoteObject; \n\npublic class Server extends ImplExample { \n public Server() {} \n public static void main(String args[]) { \n try { \n // Instantiating the implementation class \n ImplExample obj = new ImplExample(); \n \n // Exporting the object of implementation class (\n here we are exporting the remote object to the stub) \n Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0); \n \n // Binding the remote object (stub) in the registry \n Registry registry = LocateRegistry.getRegistry(); \n \n registry.bind(\"Hello\", stub); \n System.err.println(\"Server ready\"); \n } catch (Exception e) { \n System.err.println(\"Server exception: \" + e.toString()); \n e.printStackTrace(); \n } \n } \n}"
},
{
"code": null,
"e": 27020,
"s": 26804,
"text": "Following is the client program of this application. Here, we are fetching the remote object and invoking the method named getStudents(). It retrieves the records of the table from the list object and displays them."
},
{
"code": null,
"e": 28183,
"s": 27020,
"text": "import java.rmi.registry.LocateRegistry; \nimport java.rmi.registry.Registry; \nimport java.util.*; \n\npublic class Client { \n private Client() {} \n public static void main(String[] args)throws Exception { \n try { \n // Getting the registry \n Registry registry = LocateRegistry.getRegistry(null); \n \n // Looking up the registry for the remote object \n Hello stub = (Hello) registry.lookup(\"Hello\"); \n \n // Calling the remote method using the obtained object \n List<Student> list = (List)stub.getStudents(); \n for (Student s:list)v { \n \n // System.out.println(\"bc \"+s.getBranch()); \n System.out.println(\"ID: \" + s.getId()); \n System.out.println(\"name: \" + s.getName()); \n System.out.println(\"branch: \" + s.getBranch()); \n System.out.println(\"percent: \" + s.getPercent()); \n System.out.println(\"email: \" + s.getEmail()); \n } \n // System.out.println(list); \n } catch (Exception e) { \n System.err.println(\"Client exception: \" + e.toString()); \n e.printStackTrace(); \n } \n } \n}"
},
{
"code": null,
"e": 28231,
"s": 28183,
"text": "Following are the steps to run our RMI Example."
},
{
"code": null,
"e": 28342,
"s": 28231,
"text": "Step 1 − Open the folder where you have stored all the programs and compile all the Java files as shown below."
},
{
"code": null,
"e": 28359,
"s": 28342,
"text": "Javac *.java \n"
},
{
"code": null,
"e": 28420,
"s": 28359,
"text": "Step 2 − Start the rmi registry using the following command."
},
{
"code": null,
"e": 28439,
"s": 28420,
"text": "start rmiregistry\n"
},
{
"code": null,
"e": 28508,
"s": 28439,
"text": "This will start an rmi registry on a separate window as shown below."
},
{
"code": null,
"e": 28559,
"s": 28508,
"text": "Step 3 − Run the server class file as shown below."
},
{
"code": null,
"e": 28572,
"s": 28559,
"text": "Java Server\n"
},
{
"code": null,
"e": 28623,
"s": 28572,
"text": "Step 4 − Run the client class file as shown below."
},
{
"code": null,
"e": 28636,
"s": 28623,
"text": "java Client\n"
},
{
"code": null,
"e": 28669,
"s": 28636,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 28685,
"s": 28669,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 28718,
"s": 28685,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 28734,
"s": 28718,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 28769,
"s": 28734,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 28783,
"s": 28769,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 28817,
"s": 28783,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 28831,
"s": 28817,
"text": " Tushar Kale"
},
{
"code": null,
"e": 28868,
"s": 28831,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 28883,
"s": 28868,
"text": " Monica Mittal"
},
{
"code": null,
"e": 28916,
"s": 28883,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 28935,
"s": 28916,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 28942,
"s": 28935,
"text": " Print"
},
{
"code": null,
"e": 28953,
"s": 28942,
"text": " Add Notes"
}
] |
How to select at the same time from two Tkinter Listbox?
|
Let us consider a situation for a particular system to keep selecting multiple files from a directory and, once copied in the clipboard, paste them into another directory. The idea of making multiple selections in ListBoxes can be implemented by using the exportselection property. The property prevents the selected options from losing while choosing an item from another ListBox. Thus, we can select multiple options from the ListBoxes. To configure a Listbox to behave like keep selection steady, we can make exportselection = False.
#Import Tkinter library
from tkinter import *
#Create an instance of Tkinter frame or window
win= Tk()
#Set the geometry of tkinter frame
win.geometry("750x350")
#Create ListBoxes
listboxA=Listbox(win, exportselection=False) #Create listboxA
listboxA.pack(padx=10,pady=10,fill=BOTH,expand=True)
listboxB=Listbox(win,exportselection=False) #Create ListboxB
listboxB.pack(padx=10,pady=10,fill=BOTH,expand=True)
listboxA.insert(1, "1.Python")
listboxA.insert(2, "2.Java")
listboxA.insert(3, "3.C++")
listboxA.insert(4, "4.Rust")
listboxA.insert(5, "5.GoLang")
listboxB.insert(1, "a.C#")
listboxB.insert(2, "b.JavaScript")
listboxB.insert(3, "c.R")
listboxB.insert(4, "d.Php")
listboxB.insert(5, "e.CoffeeScript")
listboxB.insert(6, "f.Curl")
win.mainloop()
Running the above code will display a window that contains two listboxes. While making a selection, we can select multiple items from both listboxes.
|
[
{
"code": null,
"e": 1599,
"s": 1062,
"text": "Let us consider a situation for a particular system to keep selecting multiple files from a directory and, once copied in the clipboard, paste them into another directory. The idea of making multiple selections in ListBoxes can be implemented by using the exportselection property. The property prevents the selected options from losing while choosing an item from another ListBox. Thus, we can select multiple options from the ListBoxes. To configure a Listbox to behave like keep selection steady, we can make exportselection = False."
},
{
"code": null,
"e": 2353,
"s": 1599,
"text": "#Import Tkinter library\nfrom tkinter import *\n#Create an instance of Tkinter frame or window\nwin= Tk()\n#Set the geometry of tkinter frame\nwin.geometry(\"750x350\")\n#Create ListBoxes\nlistboxA=Listbox(win, exportselection=False) #Create listboxA\nlistboxA.pack(padx=10,pady=10,fill=BOTH,expand=True)\nlistboxB=Listbox(win,exportselection=False) #Create ListboxB\nlistboxB.pack(padx=10,pady=10,fill=BOTH,expand=True)\nlistboxA.insert(1, \"1.Python\")\nlistboxA.insert(2, \"2.Java\")\nlistboxA.insert(3, \"3.C++\")\nlistboxA.insert(4, \"4.Rust\")\nlistboxA.insert(5, \"5.GoLang\")\nlistboxB.insert(1, \"a.C#\")\nlistboxB.insert(2, \"b.JavaScript\")\nlistboxB.insert(3, \"c.R\")\nlistboxB.insert(4, \"d.Php\")\nlistboxB.insert(5, \"e.CoffeeScript\")\nlistboxB.insert(6, \"f.Curl\")\nwin.mainloop()"
},
{
"code": null,
"e": 2503,
"s": 2353,
"text": "Running the above code will display a window that contains two listboxes. While making a selection, we can select multiple items from both listboxes."
}
] |
Java Examples - Find proxy settings
|
How to find proxy settings of a System ?
Following example shows how to find proxy settings & create a proxy connection on a system using put method of systemSetting & getResponse method of HttpURLConnection class.
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.URI;
public class Main{
public static void main(String s[]) throws Exception {
try {
Properties systemSettings = System.getProperties();
systemSettings.put("proxySet", "true");
systemSettings.put("http.proxyHost", "proxy.mycompany1.local");
systemSettings.put("http.proxyPort", "80");
URL u = new URL("http://www.google.com");
HttpURLConnection con = (HttpURLConnection)u.openConnection();
System.out.println(con.getResponseCode() + " : " + con.getResponseMessage());
System.out.println(con.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (Exception e) {
e.printStackTrace();
System.out.println(false);
}
System.setProperty("java.net.useSystemProxies", "true");
Proxy proxy = (Proxy) ProxySelector.getDefault().select(new URI(
"http://www.yahoo.com/")).iterator().
next();;
System.out.println("proxy hostname : " + proxy.type());
InetSocketAddress addr = (InetSocketAddress)proxy.address();
if (addr == null) {
System.out.println("No Proxy");
} else {
System.out.println("proxy hostname : " + addr.getHostName());
System.out.println("proxy port : " + addr.getPort());
}
}
}
The above code sample will produce the following result.
200 : OK
true
proxy hostname : HTTP
proxy hostname : proxy.mycompany1.local
proxy port : 80
The following is an example to find proxy settings of a System ?
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.URI;
import java.util.Iterator;
import java.util.List;
public class NewClass {
public static void main(String[] args) {
try {
System.setProperty("java.net.useSystemProxies", "true");
List<Proxy> l = ProxySelector.getDefault().select(
new URI("http://www.google.com/"));
for (Iterator<Proxy> iter = l.iterator(); iter.hasNext();) {
Proxy proxy = iter.next();
System.out.println("proxy hostname : " + proxy.type());
InetSocketAddress addr = (InetSocketAddress) proxy.address();
if (addr == null) {
System.out.println("No Proxy");
} else {
System.out.println("proxy hostname : " + addr.getHostName());
System.out.println("proxy port : " + addr.getPort());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
The above code sample will produce the following result.
proxy hostname : DIRECT
No Proxy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2109,
"s": 2068,
"text": "How to find proxy settings of a System ?"
},
{
"code": null,
"e": 2283,
"s": 2109,
"text": "Following example shows how to find proxy settings & create a proxy connection on a system using put method of systemSetting & getResponse method of HttpURLConnection class."
},
{
"code": null,
"e": 3772,
"s": 2283,
"text": "import java.net.HttpURLConnection;\nimport java.net.URL;\nimport java.util.Properties;\nimport java.net.InetSocketAddress;\nimport java.net.Proxy;\nimport java.net.ProxySelector;\nimport java.net.URI;\n\npublic class Main{\n public static void main(String s[]) throws Exception {\n try {\n Properties systemSettings = System.getProperties();\n systemSettings.put(\"proxySet\", \"true\");\n systemSettings.put(\"http.proxyHost\", \"proxy.mycompany1.local\");\n systemSettings.put(\"http.proxyPort\", \"80\");\n \n URL u = new URL(\"http://www.google.com\");\n HttpURLConnection con = (HttpURLConnection)u.openConnection();\n System.out.println(con.getResponseCode() + \" : \" + con.getResponseMessage());\n System.out.println(con.getResponseCode() == HttpURLConnection.HTTP_OK);\n } catch (Exception e) {\n e.printStackTrace();\n System.out.println(false);\n }\n System.setProperty(\"java.net.useSystemProxies\", \"true\");\n Proxy proxy = (Proxy) ProxySelector.getDefault().select(new URI(\n \"http://www.yahoo.com/\")).iterator().\n next();;\n System.out.println(\"proxy hostname : \" + proxy.type());\n InetSocketAddress addr = (InetSocketAddress)proxy.address();\n \n if (addr == null) {\n System.out.println(\"No Proxy\");\n } else {\n System.out.println(\"proxy hostname : \" + addr.getHostName());\n System.out.println(\"proxy port : \" + addr.getPort());\n }\n }\n}"
},
{
"code": null,
"e": 3829,
"s": 3772,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 3922,
"s": 3829,
"text": "200 : OK\ntrue\nproxy hostname : HTTP\nproxy hostname : proxy.mycompany1.local\nproxy port : 80\n"
},
{
"code": null,
"e": 3987,
"s": 3922,
"text": "The following is an example to find proxy settings of a System ?"
},
{
"code": null,
"e": 5023,
"s": 3987,
"text": "import java.net.InetSocketAddress;\nimport java.net.Proxy;\nimport java.net.ProxySelector;\nimport java.net.URI;\nimport java.util.Iterator;\nimport java.util.List;\n\npublic class NewClass {\n public static void main(String[] args) {\n try {\n System.setProperty(\"java.net.useSystemProxies\", \"true\");\n List<Proxy> l = ProxySelector.getDefault().select(\n new URI(\"http://www.google.com/\"));\n \n for (Iterator<Proxy> iter = l.iterator(); iter.hasNext();) {\n Proxy proxy = iter.next();\n System.out.println(\"proxy hostname : \" + proxy.type());\n InetSocketAddress addr = (InetSocketAddress) proxy.address();\n \n if (addr == null) {\n System.out.println(\"No Proxy\");\n } else {\n System.out.println(\"proxy hostname : \" + addr.getHostName());\n System.out.println(\"proxy port : \" + addr.getPort());\n } \n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n}"
},
{
"code": null,
"e": 5080,
"s": 5023,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 5114,
"s": 5080,
"text": "proxy hostname : DIRECT\nNo Proxy\n"
},
{
"code": null,
"e": 5121,
"s": 5114,
"text": " Print"
},
{
"code": null,
"e": 5132,
"s": 5121,
"text": " Add Notes"
}
] |
Building Neural Network from scratch | by Aayush Agrawal | Towards Data Science
|
In this notebook, we are going to build a neural network(multilayer perceptron) using numpy and successfully train it to recognize digits in the image. Deep learning is a vast topic, but we got to start somewhere, so let’s start with the very basics of a neural network which is Multilayer Perceptron. You can find the same blog in notebook version here or my website.
A neural network is a type of machine learning model which is inspired by our neurons in the brain where many neurons are connected with many other neurons to translate an input to an output (simple right?). Mostly we can look at any machine learning model and think of it as a function which takes an input and produces the desired output; it’s the same with a neural network.
Multi-layer perceptron is a type of network where multiple layers of a group of perceptron are stacked together to make a model. Before we jump into the concept of a layer and multiple perceptrons, let’s start with the building block of this network which is a perceptron. Think of perceptron/neuron as a linear model which takes multiple inputs and produce an output. In our case perceptron is a linear model which takes a bunch of inputs multiply them with weights and add a bias term to generate an output.
Image credit=https://commons.wikimedia.org/wiki/File:Perceptron.png/
Now, if we stack a bunch of these perceptrons together, it becomes a hidden layer which is also known as a Dense layer in modern deep learning terminology. Dense layer,
Note that bias term is now a vector and W is a weight matrix
Image credit=http://www.texample.net/tikz/examples/neural-network/
Now we understand dense layer let’s add a bunch of them, and that network becomes a multi-layer perceptron network.
Image credit=http://pubs.sciepub.com/ajmm/3/3/1/figure/2s
If you have noticed our dense layer, only have linear functions, and any combination of linear function only results in the linear output. As we want our MLP to be flexible and learn non-linear decision boundaries, we also need to introduce non-linearity into the network. We achieve the task of introducing non-linearity by adding activation function. There are various kinds of activation function which can be used, but we will be implementing Rectified Linear Units(ReLu) which is one of the popular activation function. ReLU function is a simple function which is zero for any input value below zero and the same value for values greater than zero. ReLU function
Now, we understand dense layer and also understand the purpose of activation function, the only thing left is training the network. For training a neural network we need to have a loss function and every layer should have a feed-forward loop and backpropagation loop. Feedforward loop takes an input and generates output for making a prediction and backpropagation loop helps in training the model by adjusting weights in the layer to lower the output loss. In backpropagation, the weight update is done by using backpropagated gradients using the chain rule and optimized using an optimization algorithm. In our case, we will be using SGD(stochastic gradient descent). If you don’t understand the concept of gradient weight updates and SGD, I recommend you to watch week 1 of Machine learning by Andrew NG lectures.
So, to summarize a neural network needs few building blocks
Dense layer — a fully-connected layer,
ReLU layer (or any other activation function to introduce non-linearity)
Loss function — (crossentropy in case of multi-class classification problem)
Backprop algorithm — a stochastic gradient descent with backpropageted gradients
Let’s approach them one at a time.
Let’s start by importing some libraires required for creating our neural network.
from __future__ import print_functionimport numpy as np ## For numerical pythonnp.random.seed(42)
Every layer will have a forward pass and backpass implementation. Let’s create a main class layer which can do a forward pass .forward() and Backward pass .backward().
class Layer: #A building block. Each layer is capable of performing two things: #- Process input to get output: output = layer.forward(input) #- Propagate gradients through itself: grad_input = layer.backward(input, grad_output) #Some layers also have learnable parameters which they update during layer.backward. def __init__(self): # Here we can initialize layer parameters (if any) and auxiliary stuff. # A dummy layer does nothing pass def forward(self, input): # Takes input data of shape [batch, input_units], returns output data [batch, output_units] # A dummy layer just returns whatever it gets as input. return input def backward(self, input, grad_output): # Performs a backpropagation step through the layer, with respect to the given input. # To compute loss gradients w.r.t input, we need to apply chain rule (backprop): # d loss / d x = (d loss / d layer) * (d layer / d x) # Luckily, we already receive d loss / d layer as input, so you only need to multiply it by d layer / d x. # If our layer has parameters (e.g. dense layer), we also need to update them here using d loss / d layer # The gradient of a dummy layer is precisely grad_output, but we'll write it more explicitly num_units = input.shape[1] d_layer_d_input = np.eye(num_units) return np.dot(grad_output, d_layer_d_input) # chain rule
This is the simplest layer you can get: it simply applies a nonlinearity to each element of your network.
class ReLU(Layer): def __init__(self): # ReLU layer simply applies elementwise rectified linear unit to all inputs pass def forward(self, input): # Apply elementwise ReLU to [batch, input_units] matrix relu_forward = np.maximum(0,input) return relu_forward def backward(self, input, grad_output): # Compute gradient of loss w.r.t. ReLU input relu_grad = input > 0 return grad_output*relu_grad
Now let’s build something more complicated. Unlike nonlinearity, a dense layer actually has something to learn.
A dense layer applies affine transformation. In a vectorized form, it can be described as:
Where
X is an object-feature matrix of shape [batch_size, num_features],
W is a weight matrix [num_features, num_outputs]
and b is a vector of num_outputs biases.
Both W and b are initialized during layer creation and updated each time backward is called. Note that we are using Xavier initialization which is a trick to train our model to converge faster read more. Instead of initializing our weights with small numbers which are distributed randomly we initialize our weights with mean zero and variance of 2/(number of inputs + number of outputs)
class Dense(Layer): def __init__(self, input_units, output_units, learning_rate=0.1): # A dense layer is a layer which performs a learned affine transformation: # f(x) = <W*x> + b self.learning_rate = learning_rate self.weights = np.random.normal(loc=0.0, scale = np.sqrt(2/(input_units+output_units)), size = (input_units,output_units)) self.biases = np.zeros(output_units) def forward(self,input): # Perform an affine transformation: # f(x) = <W*x> + b # input shape: [batch, input_units] # output shape: [batch, output units] return np.dot(input,self.weights) + self.biases def backward(self,input,grad_output): # compute d f / d x = d f / d dense * d dense / d x # where d dense/ d x = weights transposed grad_input = np.dot(grad_output, self.weights.T) # compute gradient w.r.t. weights and biases grad_weights = np.dot(input.T, grad_output) grad_biases = grad_output.mean(axis=0)*input.shape[0] assert grad_weights.shape == self.weights.shape and grad_biases.shape == self.biases.shape # Here we perform a stochastic gradient descent step. self.weights = self.weights - self.learning_rate * grad_weights self.biases = self.biases - self.learning_rate * grad_biases return grad_input
Since we want to predict probabilities, it would be logical for us to define softmax nonlinearity on top of our network and compute loss given predicted probabilities. However, there is a better way to do so.
If we write down the expression for crossentropy as a function of softmax logits (a), you’ll see:
If we take a closer look, we’ll see that it can be rewritten as:
It’s called Log-softmax and it’s better than naive log(softmax(a)) in all aspects:
Better numerical stability
Easier to get derivative right
Marginally faster to compute
So why not just use log-softmax throughout our computation and never actually bother to estimate probabilities.
def softmax_crossentropy_with_logits(logits,reference_answers): # Compute crossentropy from logits[batch,n_classes] and ids of correct answers logits_for_answers = logits[np.arange(len(logits)),reference_answers] xentropy = - logits_for_answers + np.log(np.sum(np.exp(logits),axis=-1)) return xentropydef grad_softmax_crossentropy_with_logits(logits,reference_answers): # Compute crossentropy gradient from logits[batch,n_classes] and ids of correct answers ones_for_answers = np.zeros_like(logits) ones_for_answers[np.arange(len(logits)),reference_answers] = 1 softmax = np.exp(logits) / np.exp(logits).sum(axis=-1,keepdims=True) return (- ones_for_answers + softmax) / logits.shape[0]
Now let’s combine what we’ve just built into a working neural network. As I have told earlier, we are going to use MNIST data of handwritten digit for our example. Fortunately, Keras already have it in the numpy array format, so let’s import it!.
import kerasimport matplotlib.pyplot as plt%matplotlib inlinedef load_dataset(flatten=False): (X_train, y_train), (X_test, y_test) = keras.datasets.mnist.load_data() # normalize x X_train = X_train.astype(float) / 255. X_test = X_test.astype(float) / 255. # we reserve the last 10000 training examples for validation X_train, X_val = X_train[:-10000], X_train[-10000:] y_train, y_val = y_train[:-10000], y_train[-10000:] if flatten: X_train = X_train.reshape([X_train.shape[0], -1]) X_val = X_val.reshape([X_val.shape[0], -1]) X_test = X_test.reshape([X_test.shape[0], -1]) return X_train, y_train, X_val, y_val, X_test, y_testX_train, y_train, X_val, y_val, X_test, y_test = load_dataset(flatten=True)## Let's look at some exampleplt.figure(figsize=[6,6])for i in range(4): plt.subplot(2,2,i+1) plt.title("Label: %i"%y_train[i]) plt.imshow(X_train[i].reshape([28,28]),cmap='gray');
We’ll define network as a list of layers, each applied on top of previous one. In this setting, computing predictions and training becomes trivial.
network = []network.append(Dense(X_train.shape[1],100))network.append(ReLU())network.append(Dense(100,200))network.append(ReLU())network.append(Dense(200,10))def forward(network, X): # Compute activations of all network layers by applying them sequentially. # Return a list of activations for each layer. activations = [] input = X # Looping through each layer for l in network: activations.append(l.forward(input)) # Updating input to last layer output input = activations[-1] assert len(activations) == len(network) return activationsdef predict(network,X): # Compute network predictions. Returning indices of largest Logit probability logits = forward(network,X)[-1] return logits.argmax(axis=-1)def train(network,X,y): # Train our network on a given batch of X and y. # We first need to run forward to get all layer activations. # Then we can run layer.backward going from last to first layer. # After we have called backward for all layers, all Dense layers have already made one gradient step. # Get the layer activations layer_activations = forward(network,X) layer_inputs = [X]+layer_activations #layer_input[i] is an input for network[i] logits = layer_activations[-1] # Compute the loss and the initial gradient loss = softmax_crossentropy_with_logits(logits,y) loss_grad = grad_softmax_crossentropy_with_logits(logits,y) # Propagate gradients through the network # Reverse propogation as this is backprop for layer_index in range(len(network))[::-1]: layer = network[layer_index] loss_grad = layer.backward(layer_inputs[layer_index],loss_grad) #grad w.r.t. input, also weight updates return np.mean(loss)
We split data into minibatches, feed each such minibatch into the network and update weights. This training method is called a mini-batch stochastic gradient descent.
from tqdm import trangedef iterate_minibatches(inputs, targets, batchsize, shuffle=False): assert len(inputs) == len(targets) if shuffle: indices = np.random.permutation(len(inputs)) for start_idx in trange(0, len(inputs) - batchsize + 1, batchsize): if shuffle: excerpt = indices[start_idx:start_idx + batchsize] else: excerpt = slice(start_idx, start_idx + batchsize) yield inputs[excerpt], targets[excerpt]from IPython.display import clear_outputtrain_log = []val_log = []for epoch in range(25): for x_batch,y_batch in iterate_minibatches(X_train,y_train,batchsize=32,shuffle=True): train(network,x_batch,y_batch) train_log.append(np.mean(predict(network,X_train)==y_train)) val_log.append(np.mean(predict(network,X_val)==y_val)) clear_output() print("Epoch",epoch) print("Train accuracy:",train_log[-1]) print("Val accuracy:",val_log[-1]) plt.plot(train_log,label='train accuracy') plt.plot(val_log,label='val accuracy') plt.legend(loc='best') plt.grid() plt.show()Epoch 24Train accuracy: 1.0Val accuracy: 0.9809
As we can see we have successfully trained a MLP which was purely written in numpy with high validation accuracy!
|
[
{
"code": null,
"e": 541,
"s": 172,
"text": "In this notebook, we are going to build a neural network(multilayer perceptron) using numpy and successfully train it to recognize digits in the image. Deep learning is a vast topic, but we got to start somewhere, so let’s start with the very basics of a neural network which is Multilayer Perceptron. You can find the same blog in notebook version here or my website."
},
{
"code": null,
"e": 919,
"s": 541,
"text": "A neural network is a type of machine learning model which is inspired by our neurons in the brain where many neurons are connected with many other neurons to translate an input to an output (simple right?). Mostly we can look at any machine learning model and think of it as a function which takes an input and produces the desired output; it’s the same with a neural network."
},
{
"code": null,
"e": 1429,
"s": 919,
"text": "Multi-layer perceptron is a type of network where multiple layers of a group of perceptron are stacked together to make a model. Before we jump into the concept of a layer and multiple perceptrons, let’s start with the building block of this network which is a perceptron. Think of perceptron/neuron as a linear model which takes multiple inputs and produce an output. In our case perceptron is a linear model which takes a bunch of inputs multiply them with weights and add a bias term to generate an output."
},
{
"code": null,
"e": 1498,
"s": 1429,
"text": "Image credit=https://commons.wikimedia.org/wiki/File:Perceptron.png/"
},
{
"code": null,
"e": 1667,
"s": 1498,
"text": "Now, if we stack a bunch of these perceptrons together, it becomes a hidden layer which is also known as a Dense layer in modern deep learning terminology. Dense layer,"
},
{
"code": null,
"e": 1728,
"s": 1667,
"text": "Note that bias term is now a vector and W is a weight matrix"
},
{
"code": null,
"e": 1795,
"s": 1728,
"text": "Image credit=http://www.texample.net/tikz/examples/neural-network/"
},
{
"code": null,
"e": 1911,
"s": 1795,
"text": "Now we understand dense layer let’s add a bunch of them, and that network becomes a multi-layer perceptron network."
},
{
"code": null,
"e": 1969,
"s": 1911,
"text": "Image credit=http://pubs.sciepub.com/ajmm/3/3/1/figure/2s"
},
{
"code": null,
"e": 2637,
"s": 1969,
"text": "If you have noticed our dense layer, only have linear functions, and any combination of linear function only results in the linear output. As we want our MLP to be flexible and learn non-linear decision boundaries, we also need to introduce non-linearity into the network. We achieve the task of introducing non-linearity by adding activation function. There are various kinds of activation function which can be used, but we will be implementing Rectified Linear Units(ReLu) which is one of the popular activation function. ReLU function is a simple function which is zero for any input value below zero and the same value for values greater than zero. ReLU function"
},
{
"code": null,
"e": 3454,
"s": 2637,
"text": "Now, we understand dense layer and also understand the purpose of activation function, the only thing left is training the network. For training a neural network we need to have a loss function and every layer should have a feed-forward loop and backpropagation loop. Feedforward loop takes an input and generates output for making a prediction and backpropagation loop helps in training the model by adjusting weights in the layer to lower the output loss. In backpropagation, the weight update is done by using backpropagated gradients using the chain rule and optimized using an optimization algorithm. In our case, we will be using SGD(stochastic gradient descent). If you don’t understand the concept of gradient weight updates and SGD, I recommend you to watch week 1 of Machine learning by Andrew NG lectures."
},
{
"code": null,
"e": 3514,
"s": 3454,
"text": "So, to summarize a neural network needs few building blocks"
},
{
"code": null,
"e": 3553,
"s": 3514,
"text": "Dense layer — a fully-connected layer,"
},
{
"code": null,
"e": 3626,
"s": 3553,
"text": "ReLU layer (or any other activation function to introduce non-linearity)"
},
{
"code": null,
"e": 3703,
"s": 3626,
"text": "Loss function — (crossentropy in case of multi-class classification problem)"
},
{
"code": null,
"e": 3784,
"s": 3703,
"text": "Backprop algorithm — a stochastic gradient descent with backpropageted gradients"
},
{
"code": null,
"e": 3819,
"s": 3784,
"text": "Let’s approach them one at a time."
},
{
"code": null,
"e": 3901,
"s": 3819,
"text": "Let’s start by importing some libraires required for creating our neural network."
},
{
"code": null,
"e": 3999,
"s": 3901,
"text": "from __future__ import print_functionimport numpy as np ## For numerical pythonnp.random.seed(42)"
},
{
"code": null,
"e": 4167,
"s": 3999,
"text": "Every layer will have a forward pass and backpass implementation. Let’s create a main class layer which can do a forward pass .forward() and Backward pass .backward()."
},
{
"code": null,
"e": 5705,
"s": 4167,
"text": "class Layer: #A building block. Each layer is capable of performing two things: #- Process input to get output: output = layer.forward(input) #- Propagate gradients through itself: grad_input = layer.backward(input, grad_output) #Some layers also have learnable parameters which they update during layer.backward. def __init__(self): # Here we can initialize layer parameters (if any) and auxiliary stuff. # A dummy layer does nothing pass def forward(self, input): # Takes input data of shape [batch, input_units], returns output data [batch, output_units] # A dummy layer just returns whatever it gets as input. return input def backward(self, input, grad_output): # Performs a backpropagation step through the layer, with respect to the given input. # To compute loss gradients w.r.t input, we need to apply chain rule (backprop): # d loss / d x = (d loss / d layer) * (d layer / d x) # Luckily, we already receive d loss / d layer as input, so you only need to multiply it by d layer / d x. # If our layer has parameters (e.g. dense layer), we also need to update them here using d loss / d layer # The gradient of a dummy layer is precisely grad_output, but we'll write it more explicitly num_units = input.shape[1] d_layer_d_input = np.eye(num_units) return np.dot(grad_output, d_layer_d_input) # chain rule"
},
{
"code": null,
"e": 5811,
"s": 5705,
"text": "This is the simplest layer you can get: it simply applies a nonlinearity to each element of your network."
},
{
"code": null,
"e": 6277,
"s": 5811,
"text": "class ReLU(Layer): def __init__(self): # ReLU layer simply applies elementwise rectified linear unit to all inputs pass def forward(self, input): # Apply elementwise ReLU to [batch, input_units] matrix relu_forward = np.maximum(0,input) return relu_forward def backward(self, input, grad_output): # Compute gradient of loss w.r.t. ReLU input relu_grad = input > 0 return grad_output*relu_grad"
},
{
"code": null,
"e": 6389,
"s": 6277,
"text": "Now let’s build something more complicated. Unlike nonlinearity, a dense layer actually has something to learn."
},
{
"code": null,
"e": 6480,
"s": 6389,
"text": "A dense layer applies affine transformation. In a vectorized form, it can be described as:"
},
{
"code": null,
"e": 6486,
"s": 6480,
"text": "Where"
},
{
"code": null,
"e": 6553,
"s": 6486,
"text": "X is an object-feature matrix of shape [batch_size, num_features],"
},
{
"code": null,
"e": 6602,
"s": 6553,
"text": "W is a weight matrix [num_features, num_outputs]"
},
{
"code": null,
"e": 6643,
"s": 6602,
"text": "and b is a vector of num_outputs biases."
},
{
"code": null,
"e": 7031,
"s": 6643,
"text": "Both W and b are initialized during layer creation and updated each time backward is called. Note that we are using Xavier initialization which is a trick to train our model to converge faster read more. Instead of initializing our weights with small numbers which are distributed randomly we initialize our weights with mean zero and variance of 2/(number of inputs + number of outputs)"
},
{
"code": null,
"e": 8525,
"s": 7031,
"text": "class Dense(Layer): def __init__(self, input_units, output_units, learning_rate=0.1): # A dense layer is a layer which performs a learned affine transformation: # f(x) = <W*x> + b self.learning_rate = learning_rate self.weights = np.random.normal(loc=0.0, scale = np.sqrt(2/(input_units+output_units)), size = (input_units,output_units)) self.biases = np.zeros(output_units) def forward(self,input): # Perform an affine transformation: # f(x) = <W*x> + b # input shape: [batch, input_units] # output shape: [batch, output units] return np.dot(input,self.weights) + self.biases def backward(self,input,grad_output): # compute d f / d x = d f / d dense * d dense / d x # where d dense/ d x = weights transposed grad_input = np.dot(grad_output, self.weights.T) # compute gradient w.r.t. weights and biases grad_weights = np.dot(input.T, grad_output) grad_biases = grad_output.mean(axis=0)*input.shape[0] assert grad_weights.shape == self.weights.shape and grad_biases.shape == self.biases.shape # Here we perform a stochastic gradient descent step. self.weights = self.weights - self.learning_rate * grad_weights self.biases = self.biases - self.learning_rate * grad_biases return grad_input"
},
{
"code": null,
"e": 8734,
"s": 8525,
"text": "Since we want to predict probabilities, it would be logical for us to define softmax nonlinearity on top of our network and compute loss given predicted probabilities. However, there is a better way to do so."
},
{
"code": null,
"e": 8832,
"s": 8734,
"text": "If we write down the expression for crossentropy as a function of softmax logits (a), you’ll see:"
},
{
"code": null,
"e": 8897,
"s": 8832,
"text": "If we take a closer look, we’ll see that it can be rewritten as:"
},
{
"code": null,
"e": 8980,
"s": 8897,
"text": "It’s called Log-softmax and it’s better than naive log(softmax(a)) in all aspects:"
},
{
"code": null,
"e": 9007,
"s": 8980,
"text": "Better numerical stability"
},
{
"code": null,
"e": 9038,
"s": 9007,
"text": "Easier to get derivative right"
},
{
"code": null,
"e": 9067,
"s": 9038,
"text": "Marginally faster to compute"
},
{
"code": null,
"e": 9179,
"s": 9067,
"text": "So why not just use log-softmax throughout our computation and never actually bother to estimate probabilities."
},
{
"code": null,
"e": 9909,
"s": 9179,
"text": "def softmax_crossentropy_with_logits(logits,reference_answers): # Compute crossentropy from logits[batch,n_classes] and ids of correct answers logits_for_answers = logits[np.arange(len(logits)),reference_answers] xentropy = - logits_for_answers + np.log(np.sum(np.exp(logits),axis=-1)) return xentropydef grad_softmax_crossentropy_with_logits(logits,reference_answers): # Compute crossentropy gradient from logits[batch,n_classes] and ids of correct answers ones_for_answers = np.zeros_like(logits) ones_for_answers[np.arange(len(logits)),reference_answers] = 1 softmax = np.exp(logits) / np.exp(logits).sum(axis=-1,keepdims=True) return (- ones_for_answers + softmax) / logits.shape[0]"
},
{
"code": null,
"e": 10156,
"s": 9909,
"text": "Now let’s combine what we’ve just built into a working neural network. As I have told earlier, we are going to use MNIST data of handwritten digit for our example. Fortunately, Keras already have it in the numpy array format, so let’s import it!."
},
{
"code": null,
"e": 11096,
"s": 10156,
"text": "import kerasimport matplotlib.pyplot as plt%matplotlib inlinedef load_dataset(flatten=False): (X_train, y_train), (X_test, y_test) = keras.datasets.mnist.load_data() # normalize x X_train = X_train.astype(float) / 255. X_test = X_test.astype(float) / 255. # we reserve the last 10000 training examples for validation X_train, X_val = X_train[:-10000], X_train[-10000:] y_train, y_val = y_train[:-10000], y_train[-10000:] if flatten: X_train = X_train.reshape([X_train.shape[0], -1]) X_val = X_val.reshape([X_val.shape[0], -1]) X_test = X_test.reshape([X_test.shape[0], -1]) return X_train, y_train, X_val, y_val, X_test, y_testX_train, y_train, X_val, y_val, X_test, y_test = load_dataset(flatten=True)## Let's look at some exampleplt.figure(figsize=[6,6])for i in range(4): plt.subplot(2,2,i+1) plt.title(\"Label: %i\"%y_train[i]) plt.imshow(X_train[i].reshape([28,28]),cmap='gray');"
},
{
"code": null,
"e": 11244,
"s": 11096,
"text": "We’ll define network as a list of layers, each applied on top of previous one. In this setting, computing predictions and training becomes trivial."
},
{
"code": null,
"e": 13015,
"s": 11244,
"text": "network = []network.append(Dense(X_train.shape[1],100))network.append(ReLU())network.append(Dense(100,200))network.append(ReLU())network.append(Dense(200,10))def forward(network, X): # Compute activations of all network layers by applying them sequentially. # Return a list of activations for each layer. activations = [] input = X # Looping through each layer for l in network: activations.append(l.forward(input)) # Updating input to last layer output input = activations[-1] assert len(activations) == len(network) return activationsdef predict(network,X): # Compute network predictions. Returning indices of largest Logit probability logits = forward(network,X)[-1] return logits.argmax(axis=-1)def train(network,X,y): # Train our network on a given batch of X and y. # We first need to run forward to get all layer activations. # Then we can run layer.backward going from last to first layer. # After we have called backward for all layers, all Dense layers have already made one gradient step. # Get the layer activations layer_activations = forward(network,X) layer_inputs = [X]+layer_activations #layer_input[i] is an input for network[i] logits = layer_activations[-1] # Compute the loss and the initial gradient loss = softmax_crossentropy_with_logits(logits,y) loss_grad = grad_softmax_crossentropy_with_logits(logits,y) # Propagate gradients through the network # Reverse propogation as this is backprop for layer_index in range(len(network))[::-1]: layer = network[layer_index] loss_grad = layer.backward(layer_inputs[layer_index],loss_grad) #grad w.r.t. input, also weight updates return np.mean(loss)"
},
{
"code": null,
"e": 13182,
"s": 13015,
"text": "We split data into minibatches, feed each such minibatch into the network and update weights. This training method is called a mini-batch stochastic gradient descent."
},
{
"code": null,
"e": 14309,
"s": 13182,
"text": "from tqdm import trangedef iterate_minibatches(inputs, targets, batchsize, shuffle=False): assert len(inputs) == len(targets) if shuffle: indices = np.random.permutation(len(inputs)) for start_idx in trange(0, len(inputs) - batchsize + 1, batchsize): if shuffle: excerpt = indices[start_idx:start_idx + batchsize] else: excerpt = slice(start_idx, start_idx + batchsize) yield inputs[excerpt], targets[excerpt]from IPython.display import clear_outputtrain_log = []val_log = []for epoch in range(25): for x_batch,y_batch in iterate_minibatches(X_train,y_train,batchsize=32,shuffle=True): train(network,x_batch,y_batch) train_log.append(np.mean(predict(network,X_train)==y_train)) val_log.append(np.mean(predict(network,X_val)==y_val)) clear_output() print(\"Epoch\",epoch) print(\"Train accuracy:\",train_log[-1]) print(\"Val accuracy:\",val_log[-1]) plt.plot(train_log,label='train accuracy') plt.plot(val_log,label='val accuracy') plt.legend(loc='best') plt.grid() plt.show()Epoch 24Train accuracy: 1.0Val accuracy: 0.9809"
}
] |
Java program to print the Armstrong numbers between two numbers
|
An Armstrong number is a number which equals to the sum of the cubes of its individual digits. For example, 153 is an Armstrong number as −
153 = (1)3 + (5)3 + (3)3
153 1 + 125 + 27
154 153
1. Take integer variable Arms.
2. Assign a value to the variable.
3. Split all digits of Arms.
4. Find cube-value of each digit.
5. Add all cube-values together.
6. Save the output to Sum variable.
7. If Sum equals to Arms print Armstrong Number.
8. If Sum does not equal to Arms print Not Armstrong Number.
import java.util.Scanner;
public class ArmstrongBetweenTwoNumbers {
public static void main(String args[]){
int num1, num2;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the first number ::");
num1 = sc.nextInt();
System.out.println("Enter the second number ::");
num2 = sc.nextInt();
for (int i = num1; i<num2; i++){
int check, rem, sum = 0;
check = i;
while(check != 0) {
rem = check % 10;
sum = sum + (rem * rem * rem);
check = check / 10;
}
if(sum == i){
System.out.println(""+i+" is an Armstrong number.");
}
}
}
}
Enter the first number::
1
Enter the second number::
500
1 is an Armstrong number.
153 is an Armstrong number.
370 is an Armstrong number.
371 is an Armstrong number.
407 is an Armstrong number.
|
[
{
"code": null,
"e": 1202,
"s": 1062,
"text": "An Armstrong number is a number which equals to the sum of the cubes of its individual digits. For example, 153 is an Armstrong number as −"
},
{
"code": null,
"e": 1252,
"s": 1202,
"text": "153 = (1)3 + (5)3 + (3)3\n153 1 + 125 + 27\n154 153"
},
{
"code": null,
"e": 1560,
"s": 1252,
"text": "1. Take integer variable Arms.\n2. Assign a value to the variable.\n3. Split all digits of Arms.\n4. Find cube-value of each digit.\n5. Add all cube-values together.\n6. Save the output to Sum variable.\n7. If Sum equals to Arms print Armstrong Number.\n8. If Sum does not equal to Arms print Not Armstrong Number."
},
{
"code": null,
"e": 2254,
"s": 1560,
"text": "import java.util.Scanner;\npublic class ArmstrongBetweenTwoNumbers {\n public static void main(String args[]){\n int num1, num2;\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the first number ::\");\n num1 = sc.nextInt();\n System.out.println(\"Enter the second number ::\");\n num2 = sc.nextInt();\n\n for (int i = num1; i<num2; i++){\n int check, rem, sum = 0;\n check = i;\n while(check != 0) {\n rem = check % 10;\n sum = sum + (rem * rem * rem);\n check = check / 10;\n }\n if(sum == i){\n System.out.println(\"\"+i+\" is an Armstrong number.\");\n }\n }\n }\n}"
},
{
"code": null,
"e": 2449,
"s": 2254,
"text": "Enter the first number::\n1\nEnter the second number::\n500\n1 is an Armstrong number.\n153 is an Armstrong number.\n370 is an Armstrong number.\n371 is an Armstrong number.\n407 is an Armstrong number."
}
] |
Machine learning made easier with PyCaret | by Phani Rohith | Towards Data Science
|
We are often stuck in scenarios where we have a time crunch to finish our tasks. In Machine Learning, a library that is very useful in such scenarios is PyCaret.
PyCaret is an open-source library in Python that is extremely useful for several machine learning activities. It can help you right from data preprocessing to the deployment of the model. The reason why PyCaret is so useful and convenient is that anything can be achieved in very few lines of code and the code is very simple to understand. We can concentrate more on performing experiments on the data rather than writing several lines of code. Apart from being helpful for Data Preprocessing, encoding Categorical features, PyCaret also gives an understanding of which model is better by taking as few performance metrics into consideration such as Accuracy, F1 score, Recall, etc.
Let’s dive into the working of PyCaret.
The installation of PyCaret is very easy. It is just like any other python library. It can be installed by running the following command in your command line:
pip install pycaret
If you are using Google Collab then PyCaret can be installed by using :
!pip install pycaret
Installing PyCaret will automatically install all the following dependencies for you.
You don’t have to worry if you’re unaware of these dependencies as PyCaret deals with those.
Once you have installed PyCaret, you can import it into your jupyter notebook by using: import pycaret
import pycaret
Once PyCaret is imported, we must get the data ready for building our models. We can load the data in the following two ways:
1. Pandas Dataframe
2. Data from PyCaret’s Repository
Let us first discuss how the data can be loaded using the Pandas dataframe. Pycaret supports pandas dataframe and data can be loaded easily by using “read_csv” with the path of the file.
import pandas as pddata = pd.read_csv("data/train.csv")data.head()
In a similar way, we can load all other types of data that pandas support.
The other way to load the data is by using PyCaret’s repository. It consists of datasets that can be imported very easily. If you want to know the datasets present in the PyCaret repository click here.
from pycaret.datasets import get_datanba = get_data('nba')
Before setting up the environment, we must import the appropriate module for our dataset. PyCaret supports 6 modules and any of these modules can be imported using a single line.
PyCaret supports the following 6 modules.
The core setup of the Pycaret environment lies in a function named setup().
setup() function starts the environment and pipeline to handle the data for modeling and deployment. This function must be initiated before executing other functions in PyCaret.
There are around 50 parameters that are to be fed into setup() function but we don’t have to worry since most of the parameters are set to default and are optional. There are only two mandatory parameters to be fed and they are dataframe {array-like, sparse matrix} and the target column.
setup() function automatically does data pre-processing and data sampling in the background. It operates on default parameters but these paraments can be changed according to one’s requirement.
In our example, we take a dataset named “nba”, where the target variable is “TARGET_5Yrs” and it is a binary classification problem. Hence we import the classification module using :
from pycaret.classification import *pycar = setup(nba, target = 'TARGET_5Yrs')
Once you run the above command your dataset is set up as a classification model and you can see the output message stating “setup successfully completed!” and you’ll see a set of parameters along with their Description and Value corresponding to it.
The setup( ) function performs the data preprocessing on the input dataframe. In any ml model, data preprocessing plays a vital role in building the ml model. So in setup( ) function, PyCaret prepares the data with over 20 features for machine learning. The machine learning pipeline is built based on the parameters defined in the setup() function. Now, I will explain in detail the preprocessing steps involved in the setup( ) function. Don’t panic if you are not aware of these as our friend PyCaret does it for us.
The preprocessing features which PyCaret handles for you are:
— Sampling and Split
— Scale and Transform
— Data Preparation
— Feature Engineering
— Unsupervised
Let me elaborate in detail about the pre-processing steps that PyCaret is capable of doing.
Sampling and Split
(i) Train Test Split:
Any dataset in machine learning is split into a train and test dataset. This is done because it is important to know the working of the machine learning model when an unseen data is given. In PyCaret, 70% of the data belongs to the training dataset and 30% of the data belongs to the testing dataset by default.
from pycaret.classification import *reg1 = setup(data = nba, target = 'TARGET_5Yrs')
Output:
However, these dataset sizes can be varied by just passing the train_size parameter in the function.
Parameter: train_size
from pycaret.classification import *reg1 = setup(data = nba, target = 'TARGET_5Yrs', train_size = 0.6)
Data after splitting (with split = 60%):
Output:
(ii) Sampling:
If the samples/datapoints of the dataset are large i.e. if it exceeds 25,000 samples then sampling is done automatically by PyCaret. A base estimator with various sample sizes is built and a plot is obtained showing the performance metrics for each sample. Then the desired sample size can be entered in the text box. Sampling is a Boolean parameter and the default value is True.
Sampling example:
from pycaret.datasets import get_dataincome = get_data('income')from pycaret.classification import *model = setup(data = income, target = 'income >50K')
This functionality is only available in pycaret.classification and pycaret.regression modules.
Data Preparation
Having the right data is very important while performing machine learning pipeline. Many times, the data can be corrupted, there might be some missing values or the data should be categorized. All these play a vital role in building the model and need to be addressed before using the data itself.
(i) Missing value Imputation:
It is very common to have missing records in the data and this problem cannot be handled by machine learning algorithms by default. PyCaret does missing value imputation automatically. The default imputation technique used for numerical features is “mean” and the default value used for categorical features is “Constant”. The name of the parameters in the setup() function are
Parameters:
numeric_imputation: string, default = ‘mean’
categorical_imputation: string, default = ‘constant’
These parameters can be changed according to the problem by just giving the parameter in the setup() function.
#import the hepatitis dataset from PyCaret repositoryfrom pycaret.datasets import get_datanba = get_data('hepatitis')
Before initiating setup( ):
After initiating setup( ):
(ii) Changing data types:
PyCaret automatically detects the data type of the features present in the dataset. These values might be wrong at times. So this problem can be solved by giving a parameter such as
Parameters:
numeric_features = [‘column_name’]
categorical_features = [‘column_name’] or date_features = ‘date_column_name
ignore_features = [‘column_name’]
These parameters can be used to overwrite the data type that was detected by PyCaret. Another parameter called ignore_features can be used when we do not want to take any feature into consideration.
Example: If the feature “GP” is categorical but PyCaret interprets it as numerical, then this can be overwritten.
Code Snippet ( From Numerical to Categorical):
from pycaret.classification import *pycar = setup(nba, target = 'TARGET_5Yrs', categorical_features = ['GP'])
Output:
Example for ignore_features:
Here we will ignore the MIN column of the data frame.
Code Snippet (Ignoring ‘MIN’ column from the dataset):
from pycaret.classification import *pycar = setup(nba, target = 'TARGET_5Yrs', ignore_features = ['MIN'])
Output (‘MIN’ column has been ignored):
(iii) One hot encoding:
Categorical features cannot be used directly in machine learning algorithms. They have to be categorized using one-hot encoding. PyCaret automatically encodes the categorical features using one-hot encoding.
Example:
Here, name is a categorical feature. Hence PyCaret encodes it.
Output (‘Name’ column has been one-hot encoded):
(iv) Ordinal Encoding:
Categorical features that follow orders such as “Bad, Good, Excellent” should be encoded differently when compared to other Categorical features. This is done by PyCaret by sending a parameter as
Parameters: ordinal_features: dictionary
The default value is none.
Code:
from pycaret.datasets import get_dataemp = get_data('employee')
from pycaret.classification import *model = setup(data = emp, target = 'left', ordinal_features = {'salary' : ['low', 'medium', 'high']})
Output:
model[0]
(v) Cardinal Encoding:
By using one-hot encoding, it is possible to get very large sparse vectors for features such as Zipcodes or Countries. Hence we can use Cardinal encoding to get around this problem. Pycaret has a parameter in the setup() which does cardinal encoding for you. The parameter is
Parameter: high_cardinality_features: string, default = None
Code:
from pycaret.datasets import get_datainc = get_data('income')
from pycaret.classification import *model = setup(data = inc, target = 'income >50K', high_cardinality_features = ['native-country'])
Output:
(vi) Handle unknown levels:
We run into a situation many times where the test data has new levels that were not present in the trained data. This is handled by PyCaret automatically by giving a value of ‘most frequent’ or ‘least frequent’. The parameters in the setup() function are
Parameters:
handle_unknown_categorical: bool, default = True
unknown_categorical_method: string, default = ‘least_frequent’
Scale and Transform
Scale and Transform are very important because sometimes the data might be in a wide range of variance or on different scales.
(i) Normalize:
Normalizing is a very essential preprocessing step that will make sure the numerical values are not that widely spread. PyCaret does normalization when the parameter normalize is set to true. There are several ways to normalize data. The default value for the parameter normalize_method is the z- score where the mean of the values is 0 and the standard deviation is 1. Other values are min-max(range of the value is 0 to 1), maxabs(makes sure that maximum absolute value of each feature is 1), robust(normalizes according to the interquartile range and it is better when there are outliers).
Parameters: normalize, normalize_method
Example for normalize (Using default normalize_method: Z-score):
Code:
from pycaret.classification import *pycar = setup(nba, target = 'TARGET_5Yrs', normalize = True)
Output:
Example for normalize_method:
Code (Using ‘minmax’ method for normalization):
from pycaret.classification import *pycar = setup(nba, target = 'TARGET_5Yrs', normalize = True, normalize_method = 'minmax')
Output:
pycar[0]
(ii) Transformation:
Transformation is used to transform the data into a gaussian or an approximate Gaussian distribution. PyCaret does normalization when the parameter transformation is set to true. There are several ways to transform data. The default value for the parameter transformation_method is the yeo-johnson. Another value for transformation_method is quantile.
Parameters: transformation, transformation_method
Example:
from pycaret.classification import *pycar = setup(nba, target = 'TARGET_5Yrs', transformation = True)pycar[0]
Output:
Feature Engineering
Feature engineering is the creative side of machine learning. Feature Engineering is used to transform the data into another space by using the combination of features such as multiplication, trigonometric functions, logarithmic functions, etc.
(i) Feature Interaction:
PyCaret allows the creations of new features by using the existing features. Two features can be multiplied or divided with each other to form new features. The parameters used are feature_interaction(multiplication), feature_ratio(division). Both these parameters are set to false by default. These parameters can be changed in the setup() function in order to obtain feature interaction.
Parameters:
feature_interaction: bool, default = False
feature_ratio: bool, default = False
interaction_threshold: bool, default = 0.01
Example:
Importing ‘blood’ Dataset from PyCaret repository
Code:
from pycaret.classification import *model = setup(data, target = 'Class',feature_interaction = True, feature_ratio = True)model[0]
Output:
(ii) Polynomial Features:
Just like in feature interaction, the new features are created by using the polynomial degree(a2). The parameter used are polynomial_features which is set to false by default, polynomial_degree is an integer whose value is set to 2 by default. These parameters can be changed in the setup() function in order to obtain polynomial features.
Parameters:
polynomial_features: bool, default = False
polynomial_degree: int, default = 2
polynomial_threshold: float, default = 0.1
Example:
Importing ‘blood’ Dataset from PyCaret repository
Code:
from pycaret.classification import *model = setup(data, target = 'Class', polynomial_features = True)model[0]
Output:
(iii) Trigonometry features:
This is very similar to Polynomial Features. The parameter used is trigonometry_features which is set to false by default. The parameter can be changed in setup() function to obtain trigonometric features.
Parameter: trigonometry_features: bool, default = False
(iv) Group features:
When features are related to each other, these features can be grouped by using the group_features parameter in the setup() function. Information such as mean, the median is obtained by using this parameter. A list of features is passed in the parameter group_features.
Parameters:
group_features: list or list of list, default = None
group_names: list, default = None
(v) Bin Numeric Features:
Sometimes continuous features can have a wide range of values. In such cases we use feature binning. The parameter used in the setup() function is bin_numeric_features which is used to bin the numeric features.
Parameter: bin_numeric_features: list, default = None
(vi) Combine Rare levels:
Earlier we have seen one hot encoding where features like countries when encoded into numerical values generate a sparse matrix. In scenarios like this, the computational time of the model increases as the number of features increase. In such a case, the rare levels in the features are combined which have high cardinality.
Parameters:
combine_rare_levels: bool, default = False
rare_level_threshold: float, default = 0.1
Feature Selection
It is very important to select good and useful features because it can be helpful for the interpretation of the models.
(i) Feature Importance:
It is used to determine the features which are most important in predicting the target variable. The parameter which is used in setup() function is feature_selection which is false by default. Another parameter called feature_selection_threshold is present and needs to be used especially when polynomial or feature interaction is used. The default value is 0.8.
Parameters:
feature_selection: bool, default = False
feature_selection_threshold: float, default = 0.8
(ii) Remove multicollinearity:
Multicollinearity exists when one feature is highly correlated with another feature. This will lead to unstable models. Hence this has can be removed by using the parameter remove_multicollinearity which is set to false by default in the setup() function. A threshold can be set for dropping the number of the feature using the parameter multicollinearity_threshold which is set to 0.9 by default.
Parameters:
remove_multicollinearity: bool, default = False
multicollinearity_threshold: float, default = 0.9
(iii) Principle component analysis:
This is mainly used for dimensionality reduction. It is used when the dataset consists of a lot of dimensions. But there is a loss of information when PCA is used. The parameters used here are pca_method whose default value is linear. Other methods that can be used are RBF and incremental. The next parameter is pca_components which can take both int and float value. If an integer value is given then it means the number of features to be present and if the float value is present then it means that the percentage of the information that is to be retained.
Parameters:
pca: bool, default = False
pca_method: string, default = ‘linear’
pca_components: int/float, default = 0.99
(iv) Ignore low variance:
In scenarios where a multi categorical feature with skewed distribution and domination of one or two features over other features is seen, the obtained variance of the model will be very low. In such cases, we can ignore that feature.
Before ignoring a feature the below criteria should be met (Reference) :
— Count of unique values in a feature / sample size < 10%
— Count of most common value / Count of second most common value > 20 times.
Parameters: ignore_low_variance: bool, default = False
Unsupervised
(i) Create clusters:
Clusters are very important for unsupervised learning. By giving the create_cluster value as true, each point in the dataset is assigned to a particular cluster and each cluster is used as a new feature. Cluster_iter parameter is used to control the number of iterations used to form one cluster.
Parameters:
create_clusters: bool, default = False
cluster_iter: int, default = 20
(ii) Remove outliers:
Outliers can affect the performance of a model and hence needs to be removed. PyCaret removes outliers using PCA using SVD. Outliers can be removed by setting the parameter remove_outliers as true. The percentage of outliers can be controlled by the parameter outlier_threshold whose default value is 0.5.
Parameters:
remove_outliers: bool, default = False
outliers_threshold: float, default = 0.05
Set up uses all the belowinput parameters but remember that only two mandatory parameters are to be fed i.e. the data and the target, rest all the values are set to the default/optional.
setup(data, target, train_size = 0.7, sampling = True, sample_estimator = None, categorical_features = None, categorical_imputation = ‘constant’, ordinal_features = None, high_cardinality_features = None, high_cardinality_method = ‘frequency’, numeric_features = None, numeric_imputation = ‘mean’, date_features = None, ignore_features = None, normalize = False, normalize_method = ‘zscore’, transformation = False, transformation_method = ‘yeo-johnson’, handle_unknown_categorical = True, unknown_categorical_method = ‘least_frequent’, pca = False, pca_method = ‘linear’, pca_components = None, ignore_low_variance = False, combine_rare_levels = False, rare_level_threshold = 0.10, bin_numeric_features = None, remove_outliers = False, outliers_threshold = 0.05, remove_multicollinearity = False, multicollinearity_threshold = 0.9, create_clusters = False, cluster_iter = 20, polynomial_features = False, polynomial_degree = 2, trigonometry_features = False, polynomial_threshold = 0.1, group_features = None, group_names = None, feature_selection = False, feature_selection_threshold = 0.8, feature_interaction = False, feature_ratio = False, interaction_threshold = 0.01, session_id = None, silent=False, profile = False)
In short, you can just use the below code instead of giving all those parameters.
setup(data,target)
One of the main usages of PyCaret is that it can be used to compare several machine learning models based on performance metrics. The best model can thus be determined. These models are computed by using a 10 fold cross-validation. This is very useful to get an understanding of how the models are behaving and which model is better suited. The code to compare the models is very simple.
compare_models()
compare_models()
Result: The function returns a score grid that specifies the best models for each of the performance metrics.
The performance metrics used for classification are Accuracy, AUC, Recall, Precision, F1, Kappa.
The performance metrics used for regression are MAE, MSE, RMSE, R2, RMSLE, MAPE
The table is sorted by accuracy but it can be modified by giving a different value in the sort parameter. The fold value is 10 by default. This can be changed according to the problem that we are solving.
Once we get an understanding of which model is better, it is time to create a model. The code for creating a model is extremely simple.
create_model(‘model name’)
The output is a knn model and a score grid that illustrates Accuracy, AUC, Recall, Precision, F1 and kappa values.
knn_model = create_model('knn')
Result:
I have built a K-NN model using the representation ‘knn’ in the create_model (‘knn’)function. In a similar way, you can build other models by using any one of the below representations in the create_model(‘model name’).
By default, the model is created using a 10 fold CV. Instead, we can change it by using the fold parameter.
Create Model (using 7 fold CV):
knn_model = create_model(‘knn’, fold = 7)
knn_model = create_model('knn',fold = 7)
Output: The resultant knn_model obtained will be trained on 7 fold cross-validation.
Create Model (Round to 2 decimal points):
We can round off the performance metrics using a round parameter in create model function.
knn_model = create_model(‘knn’, round = 2)
knn_model = create_model('knn',round = 2)
Result: The metrics in the score grid will be rounded off to 2 digits.
As the name says we can tune the model using tune_model( ) function, in the create_model( ) function the model is created using the default hyperparameters. The functionality of the tune_mode( ) function is it will tune the hyperparameters of a model on its own and produces a score grid as output.
Before Tuning:
knn_model = create_model('knn')
After Tuning:
tuned_knn = tune_model('knn')
Tuning_model( Using Optimization):
The default optimization method used is accuracy, but we can change this by using the optimization parameter of the tuned_model( ) function.
tuned_knn = tune_model(‘knn’,optimize=’AUC’)
tuned_knn = tune_model('knn',optimize='AUC')
In a similar way, we can use other optimization measures like ‘Recall’, ‘Precision’, ‘F1’.
Result: The performance measures value has an improvement in their scores.
PyCaret also performs ensembling of the models. As ensembling increases the performance of the models (in most cases) we can ensemble our model using bagging, boosting, blending, and stacking in PyCaret.
ensemble_model(model_name)
Example: For this example, we will build a simple decision tree and perform ensembling on it.
Creating a simple decision tree:
Code:
dt = create_model('dt')
After Ensembling:
code:
bag_dt = ensemble_model(dt)
We can see a significant difference after ensembling. Bagging is the default technique.
In a similar way, we can perform Boosting, Blending, and Stacking. Click here for more info about them.
After a model is created, it is very easy to plot the performance metrics of the model and analyze it. Different types of visualizations can be done using plot_model such as AUC, precision-recall curve, decision boundary, etc.
plot_model(model_name, plot = “type”)
Code for Plotting:
logreg = create_model('lr')plot_model(logreg, plot = 'boundary')
We have used plot = “boundary” in our code, which indicates Decision Boundary. In a similar way, we can use other plots using their string type. The below table is the plot types supported by PyCaret.
Also, for the model which includes probabilities, we can predict the true probability of the results using the model calibration with the help of Calibrated Classifiers. Providing the probability values increase the interpretability and reduce uncertainty.
Calibrated_model(model_name)
Code:
#Create a simple decision treedt = create_model('dt')#Calibrate the modelcalib_dt = calibrate_model(dt)
Apart from this, there is an extremely useful function evaluate_model(model) which is used to display all the visualizations. This works only in the jupyter notebook interface. It provides an interactive user interface wherein we can select the type of visualization we need.
Code:
evaluate_model(logreg)
Here is a video representation of how evaluate_model works.
These visualizations are different for different machine learning modules. Click here to know more about visualizations.
Interpretation of the model is also possible in PyCaret. The feature importance is done using shap values. The graph in the shap values consists of x and y-axis. The x-axis consists of shap values that show the impact of the feature in a positive or negative way. The y-axis consists of feature values.
model = create_model('xgboost')interpret_model(model)
The shap value is mainly used to determine how important a feature is for predicting the class label. The red color on the right side shows that the feature is contributing positively.
All the results till now are based on the k fold cross-validation(train dataset). Now, we will predict the performance of the model on the test dataset.
code:
rf_holdout_pred = predict_model(rf)
Output after creating the model:
Output after predicting the model on the test dataset:
PyCaret enables us to save the entire model pipeline into a binary pickle file using the save_model(name, model_name = ‘’). Once the model is saved, we can load it whenever needed using load_model(). We will save our xgboost model that was created in step 9 with the name ‘pycaret_model’.
Code:
save_model(model, 'pycaret_model')
We can simply load this saved model by using the load_model() function.
Code:
load_saved_model = load_model('pycaret_model')#Now our previous model is loaded into saved_model and is ready to predict/classify.
Instead of saving only the model, the entire experiment can also be saved in a similar way to saving the model by using save_experiment(experiment_name = ‘pycaret_experiment’). By doing this you can save all the models and their outputs.
load_experiment(experiment_name='pycaret_experiment'
And also the loading of the experiment can be achieved.
load_saved_exp = load_experiment(‘pycaret_experiment’)
There it is, your final trained model/experiment can be called and used using a single line of code. There’s also a feature for us to deploy the built model in AWS. Thus, we can build a whole pipeline model using very few lines of code.
To sum up, PyCaret is a very useful library that can help you save an ample amount of time taking into account that you have a basic understanding of the concepts in machine learning such as how an algorithm works, performance metrics, data pre-processing, etc. PyCaret produces remarkable results in very little time. I would definitely suggest exploring PyCaret because it is going to be worth it!
I would like to thank Moez Ali and the team of PyCaret for this library.
Thank you for reading until the end. If there are any mistakes or suggestions please feel free to comment.
If you would like to get in touch, reach out to me on LinkedIn.
|
[
{
"code": null,
"e": 334,
"s": 172,
"text": "We are often stuck in scenarios where we have a time crunch to finish our tasks. In Machine Learning, a library that is very useful in such scenarios is PyCaret."
},
{
"code": null,
"e": 1018,
"s": 334,
"text": "PyCaret is an open-source library in Python that is extremely useful for several machine learning activities. It can help you right from data preprocessing to the deployment of the model. The reason why PyCaret is so useful and convenient is that anything can be achieved in very few lines of code and the code is very simple to understand. We can concentrate more on performing experiments on the data rather than writing several lines of code. Apart from being helpful for Data Preprocessing, encoding Categorical features, PyCaret also gives an understanding of which model is better by taking as few performance metrics into consideration such as Accuracy, F1 score, Recall, etc."
},
{
"code": null,
"e": 1058,
"s": 1018,
"text": "Let’s dive into the working of PyCaret."
},
{
"code": null,
"e": 1217,
"s": 1058,
"text": "The installation of PyCaret is very easy. It is just like any other python library. It can be installed by running the following command in your command line:"
},
{
"code": null,
"e": 1237,
"s": 1217,
"text": "pip install pycaret"
},
{
"code": null,
"e": 1309,
"s": 1237,
"text": "If you are using Google Collab then PyCaret can be installed by using :"
},
{
"code": null,
"e": 1330,
"s": 1309,
"text": "!pip install pycaret"
},
{
"code": null,
"e": 1416,
"s": 1330,
"text": "Installing PyCaret will automatically install all the following dependencies for you."
},
{
"code": null,
"e": 1509,
"s": 1416,
"text": "You don’t have to worry if you’re unaware of these dependencies as PyCaret deals with those."
},
{
"code": null,
"e": 1612,
"s": 1509,
"text": "Once you have installed PyCaret, you can import it into your jupyter notebook by using: import pycaret"
},
{
"code": null,
"e": 1627,
"s": 1612,
"text": "import pycaret"
},
{
"code": null,
"e": 1753,
"s": 1627,
"text": "Once PyCaret is imported, we must get the data ready for building our models. We can load the data in the following two ways:"
},
{
"code": null,
"e": 1773,
"s": 1753,
"text": "1. Pandas Dataframe"
},
{
"code": null,
"e": 1807,
"s": 1773,
"text": "2. Data from PyCaret’s Repository"
},
{
"code": null,
"e": 1994,
"s": 1807,
"text": "Let us first discuss how the data can be loaded using the Pandas dataframe. Pycaret supports pandas dataframe and data can be loaded easily by using “read_csv” with the path of the file."
},
{
"code": null,
"e": 2061,
"s": 1994,
"text": "import pandas as pddata = pd.read_csv(\"data/train.csv\")data.head()"
},
{
"code": null,
"e": 2136,
"s": 2061,
"text": "In a similar way, we can load all other types of data that pandas support."
},
{
"code": null,
"e": 2338,
"s": 2136,
"text": "The other way to load the data is by using PyCaret’s repository. It consists of datasets that can be imported very easily. If you want to know the datasets present in the PyCaret repository click here."
},
{
"code": null,
"e": 2397,
"s": 2338,
"text": "from pycaret.datasets import get_datanba = get_data('nba')"
},
{
"code": null,
"e": 2576,
"s": 2397,
"text": "Before setting up the environment, we must import the appropriate module for our dataset. PyCaret supports 6 modules and any of these modules can be imported using a single line."
},
{
"code": null,
"e": 2618,
"s": 2576,
"text": "PyCaret supports the following 6 modules."
},
{
"code": null,
"e": 2694,
"s": 2618,
"text": "The core setup of the Pycaret environment lies in a function named setup()."
},
{
"code": null,
"e": 2872,
"s": 2694,
"text": "setup() function starts the environment and pipeline to handle the data for modeling and deployment. This function must be initiated before executing other functions in PyCaret."
},
{
"code": null,
"e": 3161,
"s": 2872,
"text": "There are around 50 parameters that are to be fed into setup() function but we don’t have to worry since most of the parameters are set to default and are optional. There are only two mandatory parameters to be fed and they are dataframe {array-like, sparse matrix} and the target column."
},
{
"code": null,
"e": 3355,
"s": 3161,
"text": "setup() function automatically does data pre-processing and data sampling in the background. It operates on default parameters but these paraments can be changed according to one’s requirement."
},
{
"code": null,
"e": 3538,
"s": 3355,
"text": "In our example, we take a dataset named “nba”, where the target variable is “TARGET_5Yrs” and it is a binary classification problem. Hence we import the classification module using :"
},
{
"code": null,
"e": 3617,
"s": 3538,
"text": "from pycaret.classification import *pycar = setup(nba, target = 'TARGET_5Yrs')"
},
{
"code": null,
"e": 3867,
"s": 3617,
"text": "Once you run the above command your dataset is set up as a classification model and you can see the output message stating “setup successfully completed!” and you’ll see a set of parameters along with their Description and Value corresponding to it."
},
{
"code": null,
"e": 4386,
"s": 3867,
"text": "The setup( ) function performs the data preprocessing on the input dataframe. In any ml model, data preprocessing plays a vital role in building the ml model. So in setup( ) function, PyCaret prepares the data with over 20 features for machine learning. The machine learning pipeline is built based on the parameters defined in the setup() function. Now, I will explain in detail the preprocessing steps involved in the setup( ) function. Don’t panic if you are not aware of these as our friend PyCaret does it for us."
},
{
"code": null,
"e": 4448,
"s": 4386,
"text": "The preprocessing features which PyCaret handles for you are:"
},
{
"code": null,
"e": 4469,
"s": 4448,
"text": "— Sampling and Split"
},
{
"code": null,
"e": 4491,
"s": 4469,
"text": "— Scale and Transform"
},
{
"code": null,
"e": 4510,
"s": 4491,
"text": "— Data Preparation"
},
{
"code": null,
"e": 4532,
"s": 4510,
"text": "— Feature Engineering"
},
{
"code": null,
"e": 4547,
"s": 4532,
"text": "— Unsupervised"
},
{
"code": null,
"e": 4639,
"s": 4547,
"text": "Let me elaborate in detail about the pre-processing steps that PyCaret is capable of doing."
},
{
"code": null,
"e": 4658,
"s": 4639,
"text": "Sampling and Split"
},
{
"code": null,
"e": 4680,
"s": 4658,
"text": "(i) Train Test Split:"
},
{
"code": null,
"e": 4992,
"s": 4680,
"text": "Any dataset in machine learning is split into a train and test dataset. This is done because it is important to know the working of the machine learning model when an unseen data is given. In PyCaret, 70% of the data belongs to the training dataset and 30% of the data belongs to the testing dataset by default."
},
{
"code": null,
"e": 5077,
"s": 4992,
"text": "from pycaret.classification import *reg1 = setup(data = nba, target = 'TARGET_5Yrs')"
},
{
"code": null,
"e": 5085,
"s": 5077,
"text": "Output:"
},
{
"code": null,
"e": 5186,
"s": 5085,
"text": "However, these dataset sizes can be varied by just passing the train_size parameter in the function."
},
{
"code": null,
"e": 5208,
"s": 5186,
"text": "Parameter: train_size"
},
{
"code": null,
"e": 5311,
"s": 5208,
"text": "from pycaret.classification import *reg1 = setup(data = nba, target = 'TARGET_5Yrs', train_size = 0.6)"
},
{
"code": null,
"e": 5352,
"s": 5311,
"text": "Data after splitting (with split = 60%):"
},
{
"code": null,
"e": 5360,
"s": 5352,
"text": "Output:"
},
{
"code": null,
"e": 5375,
"s": 5360,
"text": "(ii) Sampling:"
},
{
"code": null,
"e": 5756,
"s": 5375,
"text": "If the samples/datapoints of the dataset are large i.e. if it exceeds 25,000 samples then sampling is done automatically by PyCaret. A base estimator with various sample sizes is built and a plot is obtained showing the performance metrics for each sample. Then the desired sample size can be entered in the text box. Sampling is a Boolean parameter and the default value is True."
},
{
"code": null,
"e": 5774,
"s": 5756,
"text": "Sampling example:"
},
{
"code": null,
"e": 5927,
"s": 5774,
"text": "from pycaret.datasets import get_dataincome = get_data('income')from pycaret.classification import *model = setup(data = income, target = 'income >50K')"
},
{
"code": null,
"e": 6022,
"s": 5927,
"text": "This functionality is only available in pycaret.classification and pycaret.regression modules."
},
{
"code": null,
"e": 6039,
"s": 6022,
"text": "Data Preparation"
},
{
"code": null,
"e": 6337,
"s": 6039,
"text": "Having the right data is very important while performing machine learning pipeline. Many times, the data can be corrupted, there might be some missing values or the data should be categorized. All these play a vital role in building the model and need to be addressed before using the data itself."
},
{
"code": null,
"e": 6367,
"s": 6337,
"text": "(i) Missing value Imputation:"
},
{
"code": null,
"e": 6745,
"s": 6367,
"text": "It is very common to have missing records in the data and this problem cannot be handled by machine learning algorithms by default. PyCaret does missing value imputation automatically. The default imputation technique used for numerical features is “mean” and the default value used for categorical features is “Constant”. The name of the parameters in the setup() function are"
},
{
"code": null,
"e": 6757,
"s": 6745,
"text": "Parameters:"
},
{
"code": null,
"e": 6802,
"s": 6757,
"text": "numeric_imputation: string, default = ‘mean’"
},
{
"code": null,
"e": 6855,
"s": 6802,
"text": "categorical_imputation: string, default = ‘constant’"
},
{
"code": null,
"e": 6966,
"s": 6855,
"text": "These parameters can be changed according to the problem by just giving the parameter in the setup() function."
},
{
"code": null,
"e": 7084,
"s": 6966,
"text": "#import the hepatitis dataset from PyCaret repositoryfrom pycaret.datasets import get_datanba = get_data('hepatitis')"
},
{
"code": null,
"e": 7112,
"s": 7084,
"text": "Before initiating setup( ):"
},
{
"code": null,
"e": 7139,
"s": 7112,
"text": "After initiating setup( ):"
},
{
"code": null,
"e": 7165,
"s": 7139,
"text": "(ii) Changing data types:"
},
{
"code": null,
"e": 7347,
"s": 7165,
"text": "PyCaret automatically detects the data type of the features present in the dataset. These values might be wrong at times. So this problem can be solved by giving a parameter such as"
},
{
"code": null,
"e": 7359,
"s": 7347,
"text": "Parameters:"
},
{
"code": null,
"e": 7394,
"s": 7359,
"text": "numeric_features = [‘column_name’]"
},
{
"code": null,
"e": 7470,
"s": 7394,
"text": "categorical_features = [‘column_name’] or date_features = ‘date_column_name"
},
{
"code": null,
"e": 7504,
"s": 7470,
"text": "ignore_features = [‘column_name’]"
},
{
"code": null,
"e": 7703,
"s": 7504,
"text": "These parameters can be used to overwrite the data type that was detected by PyCaret. Another parameter called ignore_features can be used when we do not want to take any feature into consideration."
},
{
"code": null,
"e": 7817,
"s": 7703,
"text": "Example: If the feature “GP” is categorical but PyCaret interprets it as numerical, then this can be overwritten."
},
{
"code": null,
"e": 7864,
"s": 7817,
"text": "Code Snippet ( From Numerical to Categorical):"
},
{
"code": null,
"e": 7974,
"s": 7864,
"text": "from pycaret.classification import *pycar = setup(nba, target = 'TARGET_5Yrs', categorical_features = ['GP'])"
},
{
"code": null,
"e": 7982,
"s": 7974,
"text": "Output:"
},
{
"code": null,
"e": 8011,
"s": 7982,
"text": "Example for ignore_features:"
},
{
"code": null,
"e": 8065,
"s": 8011,
"text": "Here we will ignore the MIN column of the data frame."
},
{
"code": null,
"e": 8120,
"s": 8065,
"text": "Code Snippet (Ignoring ‘MIN’ column from the dataset):"
},
{
"code": null,
"e": 8226,
"s": 8120,
"text": "from pycaret.classification import *pycar = setup(nba, target = 'TARGET_5Yrs', ignore_features = ['MIN'])"
},
{
"code": null,
"e": 8266,
"s": 8226,
"text": "Output (‘MIN’ column has been ignored):"
},
{
"code": null,
"e": 8290,
"s": 8266,
"text": "(iii) One hot encoding:"
},
{
"code": null,
"e": 8498,
"s": 8290,
"text": "Categorical features cannot be used directly in machine learning algorithms. They have to be categorized using one-hot encoding. PyCaret automatically encodes the categorical features using one-hot encoding."
},
{
"code": null,
"e": 8507,
"s": 8498,
"text": "Example:"
},
{
"code": null,
"e": 8570,
"s": 8507,
"text": "Here, name is a categorical feature. Hence PyCaret encodes it."
},
{
"code": null,
"e": 8619,
"s": 8570,
"text": "Output (‘Name’ column has been one-hot encoded):"
},
{
"code": null,
"e": 8642,
"s": 8619,
"text": "(iv) Ordinal Encoding:"
},
{
"code": null,
"e": 8838,
"s": 8642,
"text": "Categorical features that follow orders such as “Bad, Good, Excellent” should be encoded differently when compared to other Categorical features. This is done by PyCaret by sending a parameter as"
},
{
"code": null,
"e": 8879,
"s": 8838,
"text": "Parameters: ordinal_features: dictionary"
},
{
"code": null,
"e": 8906,
"s": 8879,
"text": "The default value is none."
},
{
"code": null,
"e": 8912,
"s": 8906,
"text": "Code:"
},
{
"code": null,
"e": 8976,
"s": 8912,
"text": "from pycaret.datasets import get_dataemp = get_data('employee')"
},
{
"code": null,
"e": 9114,
"s": 8976,
"text": "from pycaret.classification import *model = setup(data = emp, target = 'left', ordinal_features = {'salary' : ['low', 'medium', 'high']})"
},
{
"code": null,
"e": 9122,
"s": 9114,
"text": "Output:"
},
{
"code": null,
"e": 9131,
"s": 9122,
"text": "model[0]"
},
{
"code": null,
"e": 9154,
"s": 9131,
"text": "(v) Cardinal Encoding:"
},
{
"code": null,
"e": 9430,
"s": 9154,
"text": "By using one-hot encoding, it is possible to get very large sparse vectors for features such as Zipcodes or Countries. Hence we can use Cardinal encoding to get around this problem. Pycaret has a parameter in the setup() which does cardinal encoding for you. The parameter is"
},
{
"code": null,
"e": 9491,
"s": 9430,
"text": "Parameter: high_cardinality_features: string, default = None"
},
{
"code": null,
"e": 9497,
"s": 9491,
"text": "Code:"
},
{
"code": null,
"e": 9559,
"s": 9497,
"text": "from pycaret.datasets import get_datainc = get_data('income')"
},
{
"code": null,
"e": 9693,
"s": 9559,
"text": "from pycaret.classification import *model = setup(data = inc, target = 'income >50K', high_cardinality_features = ['native-country'])"
},
{
"code": null,
"e": 9701,
"s": 9693,
"text": "Output:"
},
{
"code": null,
"e": 9729,
"s": 9701,
"text": "(vi) Handle unknown levels:"
},
{
"code": null,
"e": 9984,
"s": 9729,
"text": "We run into a situation many times where the test data has new levels that were not present in the trained data. This is handled by PyCaret automatically by giving a value of ‘most frequent’ or ‘least frequent’. The parameters in the setup() function are"
},
{
"code": null,
"e": 9996,
"s": 9984,
"text": "Parameters:"
},
{
"code": null,
"e": 10045,
"s": 9996,
"text": "handle_unknown_categorical: bool, default = True"
},
{
"code": null,
"e": 10108,
"s": 10045,
"text": "unknown_categorical_method: string, default = ‘least_frequent’"
},
{
"code": null,
"e": 10128,
"s": 10108,
"text": "Scale and Transform"
},
{
"code": null,
"e": 10255,
"s": 10128,
"text": "Scale and Transform are very important because sometimes the data might be in a wide range of variance or on different scales."
},
{
"code": null,
"e": 10270,
"s": 10255,
"text": "(i) Normalize:"
},
{
"code": null,
"e": 10863,
"s": 10270,
"text": "Normalizing is a very essential preprocessing step that will make sure the numerical values are not that widely spread. PyCaret does normalization when the parameter normalize is set to true. There are several ways to normalize data. The default value for the parameter normalize_method is the z- score where the mean of the values is 0 and the standard deviation is 1. Other values are min-max(range of the value is 0 to 1), maxabs(makes sure that maximum absolute value of each feature is 1), robust(normalizes according to the interquartile range and it is better when there are outliers)."
},
{
"code": null,
"e": 10903,
"s": 10863,
"text": "Parameters: normalize, normalize_method"
},
{
"code": null,
"e": 10968,
"s": 10903,
"text": "Example for normalize (Using default normalize_method: Z-score):"
},
{
"code": null,
"e": 10974,
"s": 10968,
"text": "Code:"
},
{
"code": null,
"e": 11071,
"s": 10974,
"text": "from pycaret.classification import *pycar = setup(nba, target = 'TARGET_5Yrs', normalize = True)"
},
{
"code": null,
"e": 11079,
"s": 11071,
"text": "Output:"
},
{
"code": null,
"e": 11109,
"s": 11079,
"text": "Example for normalize_method:"
},
{
"code": null,
"e": 11157,
"s": 11109,
"text": "Code (Using ‘minmax’ method for normalization):"
},
{
"code": null,
"e": 11283,
"s": 11157,
"text": "from pycaret.classification import *pycar = setup(nba, target = 'TARGET_5Yrs', normalize = True, normalize_method = 'minmax')"
},
{
"code": null,
"e": 11291,
"s": 11283,
"text": "Output:"
},
{
"code": null,
"e": 11300,
"s": 11291,
"text": "pycar[0]"
},
{
"code": null,
"e": 11321,
"s": 11300,
"text": "(ii) Transformation:"
},
{
"code": null,
"e": 11673,
"s": 11321,
"text": "Transformation is used to transform the data into a gaussian or an approximate Gaussian distribution. PyCaret does normalization when the parameter transformation is set to true. There are several ways to transform data. The default value for the parameter transformation_method is the yeo-johnson. Another value for transformation_method is quantile."
},
{
"code": null,
"e": 11723,
"s": 11673,
"text": "Parameters: transformation, transformation_method"
},
{
"code": null,
"e": 11732,
"s": 11723,
"text": "Example:"
},
{
"code": null,
"e": 11842,
"s": 11732,
"text": "from pycaret.classification import *pycar = setup(nba, target = 'TARGET_5Yrs', transformation = True)pycar[0]"
},
{
"code": null,
"e": 11850,
"s": 11842,
"text": "Output:"
},
{
"code": null,
"e": 11870,
"s": 11850,
"text": "Feature Engineering"
},
{
"code": null,
"e": 12115,
"s": 11870,
"text": "Feature engineering is the creative side of machine learning. Feature Engineering is used to transform the data into another space by using the combination of features such as multiplication, trigonometric functions, logarithmic functions, etc."
},
{
"code": null,
"e": 12140,
"s": 12115,
"text": "(i) Feature Interaction:"
},
{
"code": null,
"e": 12530,
"s": 12140,
"text": "PyCaret allows the creations of new features by using the existing features. Two features can be multiplied or divided with each other to form new features. The parameters used are feature_interaction(multiplication), feature_ratio(division). Both these parameters are set to false by default. These parameters can be changed in the setup() function in order to obtain feature interaction."
},
{
"code": null,
"e": 12542,
"s": 12530,
"text": "Parameters:"
},
{
"code": null,
"e": 12585,
"s": 12542,
"text": "feature_interaction: bool, default = False"
},
{
"code": null,
"e": 12622,
"s": 12585,
"text": "feature_ratio: bool, default = False"
},
{
"code": null,
"e": 12666,
"s": 12622,
"text": "interaction_threshold: bool, default = 0.01"
},
{
"code": null,
"e": 12675,
"s": 12666,
"text": "Example:"
},
{
"code": null,
"e": 12725,
"s": 12675,
"text": "Importing ‘blood’ Dataset from PyCaret repository"
},
{
"code": null,
"e": 12731,
"s": 12725,
"text": "Code:"
},
{
"code": null,
"e": 12862,
"s": 12731,
"text": "from pycaret.classification import *model = setup(data, target = 'Class',feature_interaction = True, feature_ratio = True)model[0]"
},
{
"code": null,
"e": 12870,
"s": 12862,
"text": "Output:"
},
{
"code": null,
"e": 12896,
"s": 12870,
"text": "(ii) Polynomial Features:"
},
{
"code": null,
"e": 13236,
"s": 12896,
"text": "Just like in feature interaction, the new features are created by using the polynomial degree(a2). The parameter used are polynomial_features which is set to false by default, polynomial_degree is an integer whose value is set to 2 by default. These parameters can be changed in the setup() function in order to obtain polynomial features."
},
{
"code": null,
"e": 13248,
"s": 13236,
"text": "Parameters:"
},
{
"code": null,
"e": 13291,
"s": 13248,
"text": "polynomial_features: bool, default = False"
},
{
"code": null,
"e": 13327,
"s": 13291,
"text": "polynomial_degree: int, default = 2"
},
{
"code": null,
"e": 13370,
"s": 13327,
"text": "polynomial_threshold: float, default = 0.1"
},
{
"code": null,
"e": 13379,
"s": 13370,
"text": "Example:"
},
{
"code": null,
"e": 13429,
"s": 13379,
"text": "Importing ‘blood’ Dataset from PyCaret repository"
},
{
"code": null,
"e": 13435,
"s": 13429,
"text": "Code:"
},
{
"code": null,
"e": 13545,
"s": 13435,
"text": "from pycaret.classification import *model = setup(data, target = 'Class', polynomial_features = True)model[0]"
},
{
"code": null,
"e": 13553,
"s": 13545,
"text": "Output:"
},
{
"code": null,
"e": 13582,
"s": 13553,
"text": "(iii) Trigonometry features:"
},
{
"code": null,
"e": 13788,
"s": 13582,
"text": "This is very similar to Polynomial Features. The parameter used is trigonometry_features which is set to false by default. The parameter can be changed in setup() function to obtain trigonometric features."
},
{
"code": null,
"e": 13844,
"s": 13788,
"text": "Parameter: trigonometry_features: bool, default = False"
},
{
"code": null,
"e": 13865,
"s": 13844,
"text": "(iv) Group features:"
},
{
"code": null,
"e": 14135,
"s": 13865,
"text": "When features are related to each other, these features can be grouped by using the group_features parameter in the setup() function. Information such as mean, the median is obtained by using this parameter. A list of features is passed in the parameter group_features."
},
{
"code": null,
"e": 14147,
"s": 14135,
"text": "Parameters:"
},
{
"code": null,
"e": 14200,
"s": 14147,
"text": "group_features: list or list of list, default = None"
},
{
"code": null,
"e": 14234,
"s": 14200,
"text": "group_names: list, default = None"
},
{
"code": null,
"e": 14260,
"s": 14234,
"text": "(v) Bin Numeric Features:"
},
{
"code": null,
"e": 14471,
"s": 14260,
"text": "Sometimes continuous features can have a wide range of values. In such cases we use feature binning. The parameter used in the setup() function is bin_numeric_features which is used to bin the numeric features."
},
{
"code": null,
"e": 14525,
"s": 14471,
"text": "Parameter: bin_numeric_features: list, default = None"
},
{
"code": null,
"e": 14551,
"s": 14525,
"text": "(vi) Combine Rare levels:"
},
{
"code": null,
"e": 14876,
"s": 14551,
"text": "Earlier we have seen one hot encoding where features like countries when encoded into numerical values generate a sparse matrix. In scenarios like this, the computational time of the model increases as the number of features increase. In such a case, the rare levels in the features are combined which have high cardinality."
},
{
"code": null,
"e": 14888,
"s": 14876,
"text": "Parameters:"
},
{
"code": null,
"e": 14931,
"s": 14888,
"text": "combine_rare_levels: bool, default = False"
},
{
"code": null,
"e": 14974,
"s": 14931,
"text": "rare_level_threshold: float, default = 0.1"
},
{
"code": null,
"e": 14992,
"s": 14974,
"text": "Feature Selection"
},
{
"code": null,
"e": 15112,
"s": 14992,
"text": "It is very important to select good and useful features because it can be helpful for the interpretation of the models."
},
{
"code": null,
"e": 15136,
"s": 15112,
"text": "(i) Feature Importance:"
},
{
"code": null,
"e": 15499,
"s": 15136,
"text": "It is used to determine the features which are most important in predicting the target variable. The parameter which is used in setup() function is feature_selection which is false by default. Another parameter called feature_selection_threshold is present and needs to be used especially when polynomial or feature interaction is used. The default value is 0.8."
},
{
"code": null,
"e": 15511,
"s": 15499,
"text": "Parameters:"
},
{
"code": null,
"e": 15552,
"s": 15511,
"text": "feature_selection: bool, default = False"
},
{
"code": null,
"e": 15602,
"s": 15552,
"text": "feature_selection_threshold: float, default = 0.8"
},
{
"code": null,
"e": 15633,
"s": 15602,
"text": "(ii) Remove multicollinearity:"
},
{
"code": null,
"e": 16031,
"s": 15633,
"text": "Multicollinearity exists when one feature is highly correlated with another feature. This will lead to unstable models. Hence this has can be removed by using the parameter remove_multicollinearity which is set to false by default in the setup() function. A threshold can be set for dropping the number of the feature using the parameter multicollinearity_threshold which is set to 0.9 by default."
},
{
"code": null,
"e": 16043,
"s": 16031,
"text": "Parameters:"
},
{
"code": null,
"e": 16091,
"s": 16043,
"text": "remove_multicollinearity: bool, default = False"
},
{
"code": null,
"e": 16141,
"s": 16091,
"text": "multicollinearity_threshold: float, default = 0.9"
},
{
"code": null,
"e": 16177,
"s": 16141,
"text": "(iii) Principle component analysis:"
},
{
"code": null,
"e": 16737,
"s": 16177,
"text": "This is mainly used for dimensionality reduction. It is used when the dataset consists of a lot of dimensions. But there is a loss of information when PCA is used. The parameters used here are pca_method whose default value is linear. Other methods that can be used are RBF and incremental. The next parameter is pca_components which can take both int and float value. If an integer value is given then it means the number of features to be present and if the float value is present then it means that the percentage of the information that is to be retained."
},
{
"code": null,
"e": 16749,
"s": 16737,
"text": "Parameters:"
},
{
"code": null,
"e": 16776,
"s": 16749,
"text": "pca: bool, default = False"
},
{
"code": null,
"e": 16815,
"s": 16776,
"text": "pca_method: string, default = ‘linear’"
},
{
"code": null,
"e": 16857,
"s": 16815,
"text": "pca_components: int/float, default = 0.99"
},
{
"code": null,
"e": 16883,
"s": 16857,
"text": "(iv) Ignore low variance:"
},
{
"code": null,
"e": 17118,
"s": 16883,
"text": "In scenarios where a multi categorical feature with skewed distribution and domination of one or two features over other features is seen, the obtained variance of the model will be very low. In such cases, we can ignore that feature."
},
{
"code": null,
"e": 17191,
"s": 17118,
"text": "Before ignoring a feature the below criteria should be met (Reference) :"
},
{
"code": null,
"e": 17249,
"s": 17191,
"text": "— Count of unique values in a feature / sample size < 10%"
},
{
"code": null,
"e": 17326,
"s": 17249,
"text": "— Count of most common value / Count of second most common value > 20 times."
},
{
"code": null,
"e": 17381,
"s": 17326,
"text": "Parameters: ignore_low_variance: bool, default = False"
},
{
"code": null,
"e": 17394,
"s": 17381,
"text": "Unsupervised"
},
{
"code": null,
"e": 17415,
"s": 17394,
"text": "(i) Create clusters:"
},
{
"code": null,
"e": 17712,
"s": 17415,
"text": "Clusters are very important for unsupervised learning. By giving the create_cluster value as true, each point in the dataset is assigned to a particular cluster and each cluster is used as a new feature. Cluster_iter parameter is used to control the number of iterations used to form one cluster."
},
{
"code": null,
"e": 17724,
"s": 17712,
"text": "Parameters:"
},
{
"code": null,
"e": 17763,
"s": 17724,
"text": "create_clusters: bool, default = False"
},
{
"code": null,
"e": 17795,
"s": 17763,
"text": "cluster_iter: int, default = 20"
},
{
"code": null,
"e": 17817,
"s": 17795,
"text": "(ii) Remove outliers:"
},
{
"code": null,
"e": 18123,
"s": 17817,
"text": "Outliers can affect the performance of a model and hence needs to be removed. PyCaret removes outliers using PCA using SVD. Outliers can be removed by setting the parameter remove_outliers as true. The percentage of outliers can be controlled by the parameter outlier_threshold whose default value is 0.5."
},
{
"code": null,
"e": 18135,
"s": 18123,
"text": "Parameters:"
},
{
"code": null,
"e": 18174,
"s": 18135,
"text": "remove_outliers: bool, default = False"
},
{
"code": null,
"e": 18216,
"s": 18174,
"text": "outliers_threshold: float, default = 0.05"
},
{
"code": null,
"e": 18403,
"s": 18216,
"text": "Set up uses all the belowinput parameters but remember that only two mandatory parameters are to be fed i.e. the data and the target, rest all the values are set to the default/optional."
},
{
"code": null,
"e": 19628,
"s": 18403,
"text": "setup(data, target, train_size = 0.7, sampling = True, sample_estimator = None, categorical_features = None, categorical_imputation = ‘constant’, ordinal_features = None, high_cardinality_features = None, high_cardinality_method = ‘frequency’, numeric_features = None, numeric_imputation = ‘mean’, date_features = None, ignore_features = None, normalize = False, normalize_method = ‘zscore’, transformation = False, transformation_method = ‘yeo-johnson’, handle_unknown_categorical = True, unknown_categorical_method = ‘least_frequent’, pca = False, pca_method = ‘linear’, pca_components = None, ignore_low_variance = False, combine_rare_levels = False, rare_level_threshold = 0.10, bin_numeric_features = None, remove_outliers = False, outliers_threshold = 0.05, remove_multicollinearity = False, multicollinearity_threshold = 0.9, create_clusters = False, cluster_iter = 20, polynomial_features = False, polynomial_degree = 2, trigonometry_features = False, polynomial_threshold = 0.1, group_features = None, group_names = None, feature_selection = False, feature_selection_threshold = 0.8, feature_interaction = False, feature_ratio = False, interaction_threshold = 0.01, session_id = None, silent=False, profile = False)"
},
{
"code": null,
"e": 19710,
"s": 19628,
"text": "In short, you can just use the below code instead of giving all those parameters."
},
{
"code": null,
"e": 19729,
"s": 19710,
"text": "setup(data,target)"
},
{
"code": null,
"e": 20117,
"s": 19729,
"text": "One of the main usages of PyCaret is that it can be used to compare several machine learning models based on performance metrics. The best model can thus be determined. These models are computed by using a 10 fold cross-validation. This is very useful to get an understanding of how the models are behaving and which model is better suited. The code to compare the models is very simple."
},
{
"code": null,
"e": 20134,
"s": 20117,
"text": "compare_models()"
},
{
"code": null,
"e": 20151,
"s": 20134,
"text": "compare_models()"
},
{
"code": null,
"e": 20261,
"s": 20151,
"text": "Result: The function returns a score grid that specifies the best models for each of the performance metrics."
},
{
"code": null,
"e": 20358,
"s": 20261,
"text": "The performance metrics used for classification are Accuracy, AUC, Recall, Precision, F1, Kappa."
},
{
"code": null,
"e": 20438,
"s": 20358,
"text": "The performance metrics used for regression are MAE, MSE, RMSE, R2, RMSLE, MAPE"
},
{
"code": null,
"e": 20643,
"s": 20438,
"text": "The table is sorted by accuracy but it can be modified by giving a different value in the sort parameter. The fold value is 10 by default. This can be changed according to the problem that we are solving."
},
{
"code": null,
"e": 20779,
"s": 20643,
"text": "Once we get an understanding of which model is better, it is time to create a model. The code for creating a model is extremely simple."
},
{
"code": null,
"e": 20806,
"s": 20779,
"text": "create_model(‘model name’)"
},
{
"code": null,
"e": 20921,
"s": 20806,
"text": "The output is a knn model and a score grid that illustrates Accuracy, AUC, Recall, Precision, F1 and kappa values."
},
{
"code": null,
"e": 20953,
"s": 20921,
"text": "knn_model = create_model('knn')"
},
{
"code": null,
"e": 20961,
"s": 20953,
"text": "Result:"
},
{
"code": null,
"e": 21181,
"s": 20961,
"text": "I have built a K-NN model using the representation ‘knn’ in the create_model (‘knn’)function. In a similar way, you can build other models by using any one of the below representations in the create_model(‘model name’)."
},
{
"code": null,
"e": 21289,
"s": 21181,
"text": "By default, the model is created using a 10 fold CV. Instead, we can change it by using the fold parameter."
},
{
"code": null,
"e": 21321,
"s": 21289,
"text": "Create Model (using 7 fold CV):"
},
{
"code": null,
"e": 21363,
"s": 21321,
"text": "knn_model = create_model(‘knn’, fold = 7)"
},
{
"code": null,
"e": 21404,
"s": 21363,
"text": "knn_model = create_model('knn',fold = 7)"
},
{
"code": null,
"e": 21489,
"s": 21404,
"text": "Output: The resultant knn_model obtained will be trained on 7 fold cross-validation."
},
{
"code": null,
"e": 21531,
"s": 21489,
"text": "Create Model (Round to 2 decimal points):"
},
{
"code": null,
"e": 21622,
"s": 21531,
"text": "We can round off the performance metrics using a round parameter in create model function."
},
{
"code": null,
"e": 21665,
"s": 21622,
"text": "knn_model = create_model(‘knn’, round = 2)"
},
{
"code": null,
"e": 21707,
"s": 21665,
"text": "knn_model = create_model('knn',round = 2)"
},
{
"code": null,
"e": 21778,
"s": 21707,
"text": "Result: The metrics in the score grid will be rounded off to 2 digits."
},
{
"code": null,
"e": 22077,
"s": 21778,
"text": "As the name says we can tune the model using tune_model( ) function, in the create_model( ) function the model is created using the default hyperparameters. The functionality of the tune_mode( ) function is it will tune the hyperparameters of a model on its own and produces a score grid as output."
},
{
"code": null,
"e": 22092,
"s": 22077,
"text": "Before Tuning:"
},
{
"code": null,
"e": 22124,
"s": 22092,
"text": "knn_model = create_model('knn')"
},
{
"code": null,
"e": 22138,
"s": 22124,
"text": "After Tuning:"
},
{
"code": null,
"e": 22168,
"s": 22138,
"text": "tuned_knn = tune_model('knn')"
},
{
"code": null,
"e": 22203,
"s": 22168,
"text": "Tuning_model( Using Optimization):"
},
{
"code": null,
"e": 22344,
"s": 22203,
"text": "The default optimization method used is accuracy, but we can change this by using the optimization parameter of the tuned_model( ) function."
},
{
"code": null,
"e": 22389,
"s": 22344,
"text": "tuned_knn = tune_model(‘knn’,optimize=’AUC’)"
},
{
"code": null,
"e": 22434,
"s": 22389,
"text": "tuned_knn = tune_model('knn',optimize='AUC')"
},
{
"code": null,
"e": 22525,
"s": 22434,
"text": "In a similar way, we can use other optimization measures like ‘Recall’, ‘Precision’, ‘F1’."
},
{
"code": null,
"e": 22600,
"s": 22525,
"text": "Result: The performance measures value has an improvement in their scores."
},
{
"code": null,
"e": 22804,
"s": 22600,
"text": "PyCaret also performs ensembling of the models. As ensembling increases the performance of the models (in most cases) we can ensemble our model using bagging, boosting, blending, and stacking in PyCaret."
},
{
"code": null,
"e": 22831,
"s": 22804,
"text": "ensemble_model(model_name)"
},
{
"code": null,
"e": 22925,
"s": 22831,
"text": "Example: For this example, we will build a simple decision tree and perform ensembling on it."
},
{
"code": null,
"e": 22958,
"s": 22925,
"text": "Creating a simple decision tree:"
},
{
"code": null,
"e": 22964,
"s": 22958,
"text": "Code:"
},
{
"code": null,
"e": 22988,
"s": 22964,
"text": "dt = create_model('dt')"
},
{
"code": null,
"e": 23006,
"s": 22988,
"text": "After Ensembling:"
},
{
"code": null,
"e": 23012,
"s": 23006,
"text": "code:"
},
{
"code": null,
"e": 23040,
"s": 23012,
"text": "bag_dt = ensemble_model(dt)"
},
{
"code": null,
"e": 23128,
"s": 23040,
"text": "We can see a significant difference after ensembling. Bagging is the default technique."
},
{
"code": null,
"e": 23232,
"s": 23128,
"text": "In a similar way, we can perform Boosting, Blending, and Stacking. Click here for more info about them."
},
{
"code": null,
"e": 23459,
"s": 23232,
"text": "After a model is created, it is very easy to plot the performance metrics of the model and analyze it. Different types of visualizations can be done using plot_model such as AUC, precision-recall curve, decision boundary, etc."
},
{
"code": null,
"e": 23497,
"s": 23459,
"text": "plot_model(model_name, plot = “type”)"
},
{
"code": null,
"e": 23516,
"s": 23497,
"text": "Code for Plotting:"
},
{
"code": null,
"e": 23581,
"s": 23516,
"text": "logreg = create_model('lr')plot_model(logreg, plot = 'boundary')"
},
{
"code": null,
"e": 23782,
"s": 23581,
"text": "We have used plot = “boundary” in our code, which indicates Decision Boundary. In a similar way, we can use other plots using their string type. The below table is the plot types supported by PyCaret."
},
{
"code": null,
"e": 24039,
"s": 23782,
"text": "Also, for the model which includes probabilities, we can predict the true probability of the results using the model calibration with the help of Calibrated Classifiers. Providing the probability values increase the interpretability and reduce uncertainty."
},
{
"code": null,
"e": 24068,
"s": 24039,
"text": "Calibrated_model(model_name)"
},
{
"code": null,
"e": 24074,
"s": 24068,
"text": "Code:"
},
{
"code": null,
"e": 24178,
"s": 24074,
"text": "#Create a simple decision treedt = create_model('dt')#Calibrate the modelcalib_dt = calibrate_model(dt)"
},
{
"code": null,
"e": 24454,
"s": 24178,
"text": "Apart from this, there is an extremely useful function evaluate_model(model) which is used to display all the visualizations. This works only in the jupyter notebook interface. It provides an interactive user interface wherein we can select the type of visualization we need."
},
{
"code": null,
"e": 24460,
"s": 24454,
"text": "Code:"
},
{
"code": null,
"e": 24483,
"s": 24460,
"text": "evaluate_model(logreg)"
},
{
"code": null,
"e": 24543,
"s": 24483,
"text": "Here is a video representation of how evaluate_model works."
},
{
"code": null,
"e": 24664,
"s": 24543,
"text": "These visualizations are different for different machine learning modules. Click here to know more about visualizations."
},
{
"code": null,
"e": 24967,
"s": 24664,
"text": "Interpretation of the model is also possible in PyCaret. The feature importance is done using shap values. The graph in the shap values consists of x and y-axis. The x-axis consists of shap values that show the impact of the feature in a positive or negative way. The y-axis consists of feature values."
},
{
"code": null,
"e": 25021,
"s": 24967,
"text": "model = create_model('xgboost')interpret_model(model)"
},
{
"code": null,
"e": 25206,
"s": 25021,
"text": "The shap value is mainly used to determine how important a feature is for predicting the class label. The red color on the right side shows that the feature is contributing positively."
},
{
"code": null,
"e": 25359,
"s": 25206,
"text": "All the results till now are based on the k fold cross-validation(train dataset). Now, we will predict the performance of the model on the test dataset."
},
{
"code": null,
"e": 25365,
"s": 25359,
"text": "code:"
},
{
"code": null,
"e": 25401,
"s": 25365,
"text": "rf_holdout_pred = predict_model(rf)"
},
{
"code": null,
"e": 25434,
"s": 25401,
"text": "Output after creating the model:"
},
{
"code": null,
"e": 25489,
"s": 25434,
"text": "Output after predicting the model on the test dataset:"
},
{
"code": null,
"e": 25778,
"s": 25489,
"text": "PyCaret enables us to save the entire model pipeline into a binary pickle file using the save_model(name, model_name = ‘’). Once the model is saved, we can load it whenever needed using load_model(). We will save our xgboost model that was created in step 9 with the name ‘pycaret_model’."
},
{
"code": null,
"e": 25784,
"s": 25778,
"text": "Code:"
},
{
"code": null,
"e": 25819,
"s": 25784,
"text": "save_model(model, 'pycaret_model')"
},
{
"code": null,
"e": 25891,
"s": 25819,
"text": "We can simply load this saved model by using the load_model() function."
},
{
"code": null,
"e": 25897,
"s": 25891,
"text": "Code:"
},
{
"code": null,
"e": 26029,
"s": 25897,
"text": "load_saved_model = load_model('pycaret_model')#Now our previous model is loaded into saved_model and is ready to predict/classify. "
},
{
"code": null,
"e": 26267,
"s": 26029,
"text": "Instead of saving only the model, the entire experiment can also be saved in a similar way to saving the model by using save_experiment(experiment_name = ‘pycaret_experiment’). By doing this you can save all the models and their outputs."
},
{
"code": null,
"e": 26320,
"s": 26267,
"text": "load_experiment(experiment_name='pycaret_experiment'"
},
{
"code": null,
"e": 26376,
"s": 26320,
"text": "And also the loading of the experiment can be achieved."
},
{
"code": null,
"e": 26431,
"s": 26376,
"text": "load_saved_exp = load_experiment(‘pycaret_experiment’)"
},
{
"code": null,
"e": 26668,
"s": 26431,
"text": "There it is, your final trained model/experiment can be called and used using a single line of code. There’s also a feature for us to deploy the built model in AWS. Thus, we can build a whole pipeline model using very few lines of code."
},
{
"code": null,
"e": 27068,
"s": 26668,
"text": "To sum up, PyCaret is a very useful library that can help you save an ample amount of time taking into account that you have a basic understanding of the concepts in machine learning such as how an algorithm works, performance metrics, data pre-processing, etc. PyCaret produces remarkable results in very little time. I would definitely suggest exploring PyCaret because it is going to be worth it!"
},
{
"code": null,
"e": 27141,
"s": 27068,
"text": "I would like to thank Moez Ali and the team of PyCaret for this library."
},
{
"code": null,
"e": 27248,
"s": 27141,
"text": "Thank you for reading until the end. If there are any mistakes or suggestions please feel free to comment."
}
] |
How to perform Bitwise And operation on two images using Java OpenCV?
|
You can compute bitwise conjunction between two images using the bitwise_and() method of the org.opencv.core.Core class.
This method accepts three Mat objects representing the source, destination and result matrices, calculates the bitwise conjunction of each every element in the source matrices and stores the result in the destination matrix.
In the following Java example we are converting an image into binary and gray scale and calculating the bitwise conjunction of the results.
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class BitwiseAndExample {
public static void main(String args[]) throws Exception {
//Loading the OpenCV core library
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
//Reading the Image
String file ="D://images//elephant.jpg";
Mat src = Imgcodecs.imread(file, Imgcodecs.IMREAD_GRAYSCALE );
HighGui.imshow("Grayscale Image", src);
//Creating an empty matrix to store the results
Mat dst = new Mat(src.rows(), src.cols(), src.type());
Mat threshold = new Mat(src.rows(), src.cols(), src.type());
Mat gray = new Mat(src.rows(), src.cols(), src.type());
//Converting the gray scale image to binary image
Imgproc.threshold(src, threshold, 100, 255, Imgproc.THRESH_BINARY_INV);
HighGui.imshow("Binary Image", threshold);
//Applying bitwise and operation
Core.bitwise_and(src, threshold, dst);
HighGui.imshow("Bitwise And operation", dst);
HighGui.waitKey();
}
}
On executing, the above program generates the following windows −
Gray Scale Image −
Binary Image −
Bitwise And −
|
[
{
"code": null,
"e": 1183,
"s": 1062,
"text": "You can compute bitwise conjunction between two images using the bitwise_and() method of the org.opencv.core.Core class."
},
{
"code": null,
"e": 1408,
"s": 1183,
"text": "This method accepts three Mat objects representing the source, destination and result matrices, calculates the bitwise conjunction of each every element in the source matrices and stores the result in the destination matrix."
},
{
"code": null,
"e": 1548,
"s": 1408,
"text": "In the following Java example we are converting an image into binary and gray scale and calculating the bitwise conjunction of the results."
},
{
"code": null,
"e": 2685,
"s": 1548,
"text": "import org.opencv.core.Core;\nimport org.opencv.core.Mat;\nimport org.opencv.highgui.HighGui;\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\npublic class BitwiseAndExample {\n public static void main(String args[]) throws Exception {\n //Loading the OpenCV core library\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n //Reading the Image\n String file =\"D://images//elephant.jpg\";\n Mat src = Imgcodecs.imread(file, Imgcodecs.IMREAD_GRAYSCALE );\n HighGui.imshow(\"Grayscale Image\", src);\n //Creating an empty matrix to store the results\n Mat dst = new Mat(src.rows(), src.cols(), src.type());\n Mat threshold = new Mat(src.rows(), src.cols(), src.type());\n Mat gray = new Mat(src.rows(), src.cols(), src.type());\n //Converting the gray scale image to binary image\n Imgproc.threshold(src, threshold, 100, 255, Imgproc.THRESH_BINARY_INV);\n HighGui.imshow(\"Binary Image\", threshold);\n //Applying bitwise and operation\n Core.bitwise_and(src, threshold, dst);\n HighGui.imshow(\"Bitwise And operation\", dst);\n HighGui.waitKey();\n }\n}"
},
{
"code": null,
"e": 2751,
"s": 2685,
"text": "On executing, the above program generates the following windows −"
},
{
"code": null,
"e": 2770,
"s": 2751,
"text": "Gray Scale Image −"
},
{
"code": null,
"e": 2785,
"s": 2770,
"text": "Binary Image −"
},
{
"code": null,
"e": 2799,
"s": 2785,
"text": "Bitwise And −"
}
] |
Matrix Autoregressive Model for Multidimensional Time Series Forecasting | by Xinyu Chen (陈新宇) | Towards Data Science
|
Autoregressive (AR) process is a representative and classical model in time series analysis and it has broad applications in nature, science, and economics. AR can describe certain time-varying processes with a linear relationship in univariate time series. Another important counterpart of AR is vector autoregressive (VAR) model, which can describe the coevolution patterns of multivariate time series. In this blog post, we will
introduce a matrix autoregressive (MAR) model for modeling multidimensional time series data,
discuss the optimization scheme and reproduce the MAR model with Numpy in Python.
For multivariate time series, if the variables are dependent, then VAR can explore the coevolution patterns of these variables.
To estimate the coefficient matrix, we can build a least squares problem by using L2 norm.
It would be not difficult to write the Python code for reproducing a VAR model.
import numpy as npdef var(X, pred_step): N, T = X.shape temp1 = np.zeros((N, N)) temp2 = np.zeros((N, N)) for t in range(1, T): temp1 += np.outer(X[:, t], X[:, t - 1]) temp2 += np.outer(X[:, t - 1], X[:, t - 1]) A = temp1 @ np.linalg.inv(temp2) mat = np.append(X, np.zeros((N, pred_step)), axis = 1) for s in range(pred_step): mat[:, T + s] = A @ mat[:, T + s - 1] return mat[:, - pred_step :]
We can evaluate the VAR code by a toy example.
Write Python code here:
import numpy as npX = np.zeros((2, 10))X[0, :] = np.arange(1, 11)X[1, :] = np.arange(2, 12)pred_step = 2mat_hat = var(X, pred_step)print(mat_hat)
Run the code, and the expected output is
[[11. 12.] [12. 13.]]
As can be seen, these forecasts are completely same as the ground truth data.
In real world, multidimensional time series data are very common. For example, in finance, we can summarize seasonal economic indexes for some countries as a matrix, just like this:
In this matrix, if we take into account time information, then we would get a “tensor”:
Intuitively, the tensor is given as follows,
Instead of vector-form observations in each time t, we have matrix-form observations. Very recently, Chen et al. (2021) proposed a new matrix autoregressive (MAR) framework for building this multidimensional time series data. They took into account a bilinear structure like this:
where the matrix A is of size m-by-m, as the matrix B is of size n-by-n. Both two matrices are played as coefficients in MAR.
This framework has many advantages for building multidimensional time series data:
The framework can maintain the original data representation in the form of matrix.
The framework can reduce the amount of parameters in autoregressive models. For example, if we use VAR to explore such data, we would have (mn)2 parameters in the coefficient matrix. But using MAR, we only have m2+n2. This can avoid the over-parameterization issue in VAR for handling high-dimensional data.
As mentioned above, we can use a bilinear structure to build a MAR model. One question is that how to estimate coefficient matrices. The first impulse is write the optimization problem as a loss function:
where we use Frobenius norm.
If we define the objective as a function here:
Then, we have
It is not hard to obtain the closed-form solution to A by letting the derivative as 0. The closed-form solution to A is given by
If we rewrite the objective as:
Then, we have
Let the derivative as 0. The closed-form solution to B is given by
As mentioned above, we have two closed-form solutions. Since the solution to A involves B, and the solution to B involves A. We can use a classical algorithm for solving such problem, that is Alternating Least Squares (ALS) algorithm. The fundamental idea of this algorithm is updating the least squares solution of each variable in an iterative manner. For example, our case becomes
where l denotes the count of iteration.
By these equations, we can define a Python function here with ALS algorithm:
import numpy as npdef mar(X, pred_step, maxiter = 100): m, n, T = X.shape B = np.random.randn(n, n) for it in range(maxiter): temp0 = B.T @ B temp1 = np.zeros((m, m)) temp2 = np.zeros((m, m)) for t in range(1, T): temp1 += X[:, :, t] @ B @ X[:, :, t - 1].T temp2 += X[:, :, t - 1] @ temp0 @ X[:, :, t - 1].T A = temp1 @ np.linalg.inv(temp2) temp0 = A.T @ A temp1 = np.zeros((n, n)) temp2 = np.zeros((n, n)) for t in range(1, T): temp1 += X[:, :, t].T @ A @ X[:, :, t - 1] temp2 += X[:, :, t - 1].T @ temp0 @ X[:, :, t - 1] B = temp1 @ np.linalg.inv(temp2) tensor = np.append(X, np.zeros((m, n, pred_step)), axis = 2) for s in range(pred_step): tensor[:, :, T + s] = A @ tensor[:, :, T + s - 1] @ B.T return tensor[:, :, - pred_step :]
We set up a simple example to test the algorithm. The forecasting task is given as follows,
Write Python code here:
import numpy as npX = np.zeros((2, 2, 10))X[0, 0, :] = np.arange(1, 11)X[0, 1, :] = np.arange(2, 12)X[1, 0, :] = np.arange(3, 13)X[1, 1, :] = np.arange(4, 14)pred_step = 2tensor_hat = mar(X, pred_step)print(tensor_hat[:, :, 0])print()print(tensor_hat[:, :, 1])
Run the code, and the expected output is
[[11. 12.] [13. 14.]][[12. 13.] [14. 15.]]
As can be seen, these forecasts are completely same as the ground truth data.
Rong Chen, Han Xiao, Dan Yang. Autoregressive models for matrix-valued time series. Journal of Econometrics, 2021.
This is a simple story about MAR model. If you are interested in this blog post, we highly recommend you to reproduce these codes and it would be not hard to follow.
|
[
{
"code": null,
"e": 603,
"s": 171,
"text": "Autoregressive (AR) process is a representative and classical model in time series analysis and it has broad applications in nature, science, and economics. AR can describe certain time-varying processes with a linear relationship in univariate time series. Another important counterpart of AR is vector autoregressive (VAR) model, which can describe the coevolution patterns of multivariate time series. In this blog post, we will"
},
{
"code": null,
"e": 697,
"s": 603,
"text": "introduce a matrix autoregressive (MAR) model for modeling multidimensional time series data,"
},
{
"code": null,
"e": 779,
"s": 697,
"text": "discuss the optimization scheme and reproduce the MAR model with Numpy in Python."
},
{
"code": null,
"e": 907,
"s": 779,
"text": "For multivariate time series, if the variables are dependent, then VAR can explore the coevolution patterns of these variables."
},
{
"code": null,
"e": 998,
"s": 907,
"text": "To estimate the coefficient matrix, we can build a least squares problem by using L2 norm."
},
{
"code": null,
"e": 1078,
"s": 998,
"text": "It would be not difficult to write the Python code for reproducing a VAR model."
},
{
"code": null,
"e": 1517,
"s": 1078,
"text": "import numpy as npdef var(X, pred_step): N, T = X.shape temp1 = np.zeros((N, N)) temp2 = np.zeros((N, N)) for t in range(1, T): temp1 += np.outer(X[:, t], X[:, t - 1]) temp2 += np.outer(X[:, t - 1], X[:, t - 1]) A = temp1 @ np.linalg.inv(temp2) mat = np.append(X, np.zeros((N, pred_step)), axis = 1) for s in range(pred_step): mat[:, T + s] = A @ mat[:, T + s - 1] return mat[:, - pred_step :]"
},
{
"code": null,
"e": 1564,
"s": 1517,
"text": "We can evaluate the VAR code by a toy example."
},
{
"code": null,
"e": 1588,
"s": 1564,
"text": "Write Python code here:"
},
{
"code": null,
"e": 1734,
"s": 1588,
"text": "import numpy as npX = np.zeros((2, 10))X[0, :] = np.arange(1, 11)X[1, :] = np.arange(2, 12)pred_step = 2mat_hat = var(X, pred_step)print(mat_hat)"
},
{
"code": null,
"e": 1775,
"s": 1734,
"text": "Run the code, and the expected output is"
},
{
"code": null,
"e": 1797,
"s": 1775,
"text": "[[11. 12.] [12. 13.]]"
},
{
"code": null,
"e": 1875,
"s": 1797,
"text": "As can be seen, these forecasts are completely same as the ground truth data."
},
{
"code": null,
"e": 2057,
"s": 1875,
"text": "In real world, multidimensional time series data are very common. For example, in finance, we can summarize seasonal economic indexes for some countries as a matrix, just like this:"
},
{
"code": null,
"e": 2145,
"s": 2057,
"text": "In this matrix, if we take into account time information, then we would get a “tensor”:"
},
{
"code": null,
"e": 2190,
"s": 2145,
"text": "Intuitively, the tensor is given as follows,"
},
{
"code": null,
"e": 2471,
"s": 2190,
"text": "Instead of vector-form observations in each time t, we have matrix-form observations. Very recently, Chen et al. (2021) proposed a new matrix autoregressive (MAR) framework for building this multidimensional time series data. They took into account a bilinear structure like this:"
},
{
"code": null,
"e": 2597,
"s": 2471,
"text": "where the matrix A is of size m-by-m, as the matrix B is of size n-by-n. Both two matrices are played as coefficients in MAR."
},
{
"code": null,
"e": 2680,
"s": 2597,
"text": "This framework has many advantages for building multidimensional time series data:"
},
{
"code": null,
"e": 2763,
"s": 2680,
"text": "The framework can maintain the original data representation in the form of matrix."
},
{
"code": null,
"e": 3071,
"s": 2763,
"text": "The framework can reduce the amount of parameters in autoregressive models. For example, if we use VAR to explore such data, we would have (mn)2 parameters in the coefficient matrix. But using MAR, we only have m2+n2. This can avoid the over-parameterization issue in VAR for handling high-dimensional data."
},
{
"code": null,
"e": 3276,
"s": 3071,
"text": "As mentioned above, we can use a bilinear structure to build a MAR model. One question is that how to estimate coefficient matrices. The first impulse is write the optimization problem as a loss function:"
},
{
"code": null,
"e": 3305,
"s": 3276,
"text": "where we use Frobenius norm."
},
{
"code": null,
"e": 3352,
"s": 3305,
"text": "If we define the objective as a function here:"
},
{
"code": null,
"e": 3366,
"s": 3352,
"text": "Then, we have"
},
{
"code": null,
"e": 3495,
"s": 3366,
"text": "It is not hard to obtain the closed-form solution to A by letting the derivative as 0. The closed-form solution to A is given by"
},
{
"code": null,
"e": 3527,
"s": 3495,
"text": "If we rewrite the objective as:"
},
{
"code": null,
"e": 3541,
"s": 3527,
"text": "Then, we have"
},
{
"code": null,
"e": 3608,
"s": 3541,
"text": "Let the derivative as 0. The closed-form solution to B is given by"
},
{
"code": null,
"e": 3992,
"s": 3608,
"text": "As mentioned above, we have two closed-form solutions. Since the solution to A involves B, and the solution to B involves A. We can use a classical algorithm for solving such problem, that is Alternating Least Squares (ALS) algorithm. The fundamental idea of this algorithm is updating the least squares solution of each variable in an iterative manner. For example, our case becomes"
},
{
"code": null,
"e": 4032,
"s": 3992,
"text": "where l denotes the count of iteration."
},
{
"code": null,
"e": 4109,
"s": 4032,
"text": "By these equations, we can define a Python function here with ALS algorithm:"
},
{
"code": null,
"e": 4983,
"s": 4109,
"text": "import numpy as npdef mar(X, pred_step, maxiter = 100): m, n, T = X.shape B = np.random.randn(n, n) for it in range(maxiter): temp0 = B.T @ B temp1 = np.zeros((m, m)) temp2 = np.zeros((m, m)) for t in range(1, T): temp1 += X[:, :, t] @ B @ X[:, :, t - 1].T temp2 += X[:, :, t - 1] @ temp0 @ X[:, :, t - 1].T A = temp1 @ np.linalg.inv(temp2) temp0 = A.T @ A temp1 = np.zeros((n, n)) temp2 = np.zeros((n, n)) for t in range(1, T): temp1 += X[:, :, t].T @ A @ X[:, :, t - 1] temp2 += X[:, :, t - 1].T @ temp0 @ X[:, :, t - 1] B = temp1 @ np.linalg.inv(temp2) tensor = np.append(X, np.zeros((m, n, pred_step)), axis = 2) for s in range(pred_step): tensor[:, :, T + s] = A @ tensor[:, :, T + s - 1] @ B.T return tensor[:, :, - pred_step :]"
},
{
"code": null,
"e": 5075,
"s": 4983,
"text": "We set up a simple example to test the algorithm. The forecasting task is given as follows,"
},
{
"code": null,
"e": 5099,
"s": 5075,
"text": "Write Python code here:"
},
{
"code": null,
"e": 5360,
"s": 5099,
"text": "import numpy as npX = np.zeros((2, 2, 10))X[0, 0, :] = np.arange(1, 11)X[0, 1, :] = np.arange(2, 12)X[1, 0, :] = np.arange(3, 13)X[1, 1, :] = np.arange(4, 14)pred_step = 2tensor_hat = mar(X, pred_step)print(tensor_hat[:, :, 0])print()print(tensor_hat[:, :, 1])"
},
{
"code": null,
"e": 5401,
"s": 5360,
"text": "Run the code, and the expected output is"
},
{
"code": null,
"e": 5444,
"s": 5401,
"text": "[[11. 12.] [13. 14.]][[12. 13.] [14. 15.]]"
},
{
"code": null,
"e": 5522,
"s": 5444,
"text": "As can be seen, these forecasts are completely same as the ground truth data."
},
{
"code": null,
"e": 5637,
"s": 5522,
"text": "Rong Chen, Han Xiao, Dan Yang. Autoregressive models for matrix-valued time series. Journal of Econometrics, 2021."
}
] |
Functional Programming - Pure Function
|
A function is considered as Pure Function if it fulfils the following two conditions −
It always returns the same result for the given inputs and its results purely depends upon the inputs passed.
It always returns the same result for the given inputs and its results purely depends upon the inputs passed.
It has no side effects means it is not modifying any state of the caller entity.
It has no side effects means it is not modifying any state of the caller entity.
public class FunctionTester {
public static void main(String[] args) {
int result = sum(2,3);
System.out.println(result);
result = sum(2,3);
System.out.println(result);
}
static int sum(int a, int b){
return a + b;
}
}
5
5
Here sum() is a pure function as it always return 5 when passed 2 and 3 as parameters at different times and has no side effects.
public class FunctionTester {
private static double valueUsed = 0.0;
public static void main(String[] args) {
double result = randomSum(2.0,3.0);
System.out.println(result);
result = randomSum(2.0,3.0);
System.out.println(result);
}
static double randomSum(double a, double b){
valueUsed = Math.random();
return valueUsed + a + b;
}
}
5.919716721877799
5.4830887819586795
Here randomSum() is an impure function as it return different results when passed 2 and 3 as parameters at different times and modifies state of instance variable as well.
32 Lectures
3.5 hours
Pavan Lalwani
11 Lectures
1 hours
Prof. Paul Cline, Ed.D
72 Lectures
10.5 hours
Arun Ammasai
51 Lectures
2 hours
Skillbakerystudios
43 Lectures
4 hours
Mohammad Nauman
8 Lectures
1 hours
Santharam Sivalenka
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2176,
"s": 2089,
"text": "A function is considered as Pure Function if it fulfils the following two conditions −"
},
{
"code": null,
"e": 2286,
"s": 2176,
"text": "It always returns the same result for the given inputs and its results purely depends upon the inputs passed."
},
{
"code": null,
"e": 2396,
"s": 2286,
"text": "It always returns the same result for the given inputs and its results purely depends upon the inputs passed."
},
{
"code": null,
"e": 2477,
"s": 2396,
"text": "It has no side effects means it is not modifying any state of the caller entity."
},
{
"code": null,
"e": 2558,
"s": 2477,
"text": "It has no side effects means it is not modifying any state of the caller entity."
},
{
"code": null,
"e": 2826,
"s": 2558,
"text": "public class FunctionTester { \n public static void main(String[] args) {\n int result = sum(2,3);\n System.out.println(result);\n \n result = sum(2,3);\n System.out.println(result);\n }\n static int sum(int a, int b){\n return a + b;\n }\n}"
},
{
"code": null,
"e": 2831,
"s": 2826,
"text": "5\n5\n"
},
{
"code": null,
"e": 2961,
"s": 2831,
"text": "Here sum() is a pure function as it always return 5 when passed 2 and 3 as parameters at different times and has no side effects."
},
{
"code": null,
"e": 3359,
"s": 2961,
"text": "public class FunctionTester {\n private static double valueUsed = 0.0; \n public static void main(String[] args) {\n double result = randomSum(2.0,3.0);\n System.out.println(result);\n result = randomSum(2.0,3.0);\n System.out.println(result);\n }\n \n static double randomSum(double a, double b){\n valueUsed = Math.random(); \n return valueUsed + a + b;\n }\n}"
},
{
"code": null,
"e": 3397,
"s": 3359,
"text": "5.919716721877799\n5.4830887819586795\n"
},
{
"code": null,
"e": 3569,
"s": 3397,
"text": "Here randomSum() is an impure function as it return different results when passed 2 and 3 as parameters at different times and modifies state of instance variable as well."
},
{
"code": null,
"e": 3604,
"s": 3569,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3619,
"s": 3604,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 3652,
"s": 3619,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3676,
"s": 3652,
"text": " Prof. Paul Cline, Ed.D"
},
{
"code": null,
"e": 3712,
"s": 3676,
"text": "\n 72 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 3726,
"s": 3712,
"text": " Arun Ammasai"
},
{
"code": null,
"e": 3759,
"s": 3726,
"text": "\n 51 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3779,
"s": 3759,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 3812,
"s": 3779,
"text": "\n 43 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3829,
"s": 3812,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 3861,
"s": 3829,
"text": "\n 8 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3882,
"s": 3861,
"text": " Santharam Sivalenka"
},
{
"code": null,
"e": 3889,
"s": 3882,
"text": " Print"
},
{
"code": null,
"e": 3900,
"s": 3889,
"text": " Add Notes"
}
] |
React Components
|
Components are like functions that return HTML elements.
Components are independent and reusable bits of code.
They serve the same purpose as JavaScript functions,
but work in isolation and return HTML.
Components come in two types, Class components and Function components, in
this tutorial we will concentrate on Function components.
In older React code bases, you may find Class components primarily used.
It is now suggested to use Function components along with Hooks,
which were added in React 16.8. There is an optional section on Class components for your reference.
When creating a React component, the component's name MUST start with an
upper case letter.
A class component must include the extends React.Component statement.
This statement creates an inheritance to React.Component, and gives your component access to React.Component's functions.
The component also requires a render() method,
this method returns HTML.
Create a Class component called Car
class Car extends React.Component {
render() {
return <h2>Hi, I am a Car!</h2>;
}
}
Here is the same example as above, but created using a Function component instead.
A Function component also returns HTML, and behaves much the same way as a Class component,
but Function components can be written using much less code,
are easier to understand, and will be preferred in this tutorial.
Create a Function component called Car
function Car() {
return <h2>Hi, I am a Car!</h2>;
}
Now your React application has a component called Car, which returns an
<h2> element.
To use this component in your application, use similar syntax as normal HTML:
<Car />
Display the Car component in the "root" element:
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Car />);
Run
Example »
Components can be passed as props, which stands for properties.
Props are like function arguments, and you send them into the component as attributes.
You will learn more about props in the next chapter.
Use an attribute to pass a color to the Car component, and use it in the
render() function:
function Car(props) {
return <h2>I am a {props.color} Car!</h2>;
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Car color="red"/>);
Run
Example »
We can refer to components inside other components:
Use the Car component inside the Garage component:
function Car() {
return <h2>I am a Car!</h2>;
}
function Garage() {
return (
<>
<h1>Who lives in my Garage?</h1>
<Car />
</>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage />);
Run
Example »
React is all about re-using code, and it is recommended to split your components into separate files.
To do that, create a new file with a .js
file extension and put the code inside it:
Note that the filename must start with an uppercase character.
This is the new file, we named it "Car.js":
function Car() {
return <h2>Hi, I am a Car!</h2>;
}
export default Car;
To be able to use the Car component, you have to import the file in your
application.
Now we import the "Car.js" file in the application, and we can use the
Car
component as if it was created here.
import React from 'react';
import ReactDOM from 'react-dom/client';
import Car from './Car.js';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Car />);
Run
Example »
Name the following React component "person".
function (props) {
return <h2>Hi, I'm {props.name}</h2>;
}
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 57,
"s": 0,
"text": "Components are like functions that return HTML elements."
},
{
"code": null,
"e": 203,
"s": 57,
"text": "Components are independent and reusable bits of code.\nThey serve the same purpose as JavaScript functions,\nbut work in isolation and return HTML."
},
{
"code": null,
"e": 337,
"s": 203,
"text": "Components come in two types, Class components and Function components, in \nthis tutorial we will concentrate on Function components."
},
{
"code": null,
"e": 576,
"s": 337,
"text": "In older React code bases, you may find Class components primarily used.\nIt is now suggested to use Function components along with Hooks,\nwhich were added in React 16.8. There is an optional section on Class components for your reference."
},
{
"code": null,
"e": 669,
"s": 576,
"text": "When creating a React component, the component's name MUST start with an \nupper case letter."
},
{
"code": null,
"e": 862,
"s": 669,
"text": "A class component must include the extends React.Component statement. \nThis statement creates an inheritance to React.Component, and gives your component access to React.Component's functions."
},
{
"code": null,
"e": 936,
"s": 862,
"text": "The component also requires a render() method, \nthis method returns HTML."
},
{
"code": null,
"e": 972,
"s": 936,
"text": "Create a Class component called Car"
},
{
"code": null,
"e": 1065,
"s": 972,
"text": "class Car extends React.Component {\n render() {\n return <h2>Hi, I am a Car!</h2>;\n }\n}\n"
},
{
"code": null,
"e": 1148,
"s": 1065,
"text": "Here is the same example as above, but created using a Function component instead."
},
{
"code": null,
"e": 1367,
"s": 1148,
"text": "A Function component also returns HTML, and behaves much the same way as a Class component,\nbut Function components can be written using much less code,\nare easier to understand, and will be preferred in this tutorial."
},
{
"code": null,
"e": 1406,
"s": 1367,
"text": "Create a Function component called Car"
},
{
"code": null,
"e": 1461,
"s": 1406,
"text": "function Car() {\n return <h2>Hi, I am a Car!</h2>;\n}\n"
},
{
"code": null,
"e": 1548,
"s": 1461,
"text": "Now your React application has a component called Car, which returns an \n<h2> element."
},
{
"code": null,
"e": 1634,
"s": 1548,
"text": "To use this component in your application, use similar syntax as normal HTML:\n<Car />"
},
{
"code": null,
"e": 1683,
"s": 1634,
"text": "Display the Car component in the \"root\" element:"
},
{
"code": null,
"e": 1772,
"s": 1683,
"text": "const root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Car />);"
},
{
"code": null,
"e": 1789,
"s": 1772,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 1853,
"s": 1789,
"text": "Components can be passed as props, which stands for properties."
},
{
"code": null,
"e": 1940,
"s": 1853,
"text": "Props are like function arguments, and you send them into the component as attributes."
},
{
"code": null,
"e": 1993,
"s": 1940,
"text": "You will learn more about props in the next chapter."
},
{
"code": null,
"e": 2086,
"s": 1993,
"text": "Use an attribute to pass a color to the Car component, and use it in the \nrender() function:"
},
{
"code": null,
"e": 2257,
"s": 2086,
"text": "function Car(props) {\n return <h2>I am a {props.color} Car!</h2>;\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Car color=\"red\"/>);\n"
},
{
"code": null,
"e": 2274,
"s": 2257,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 2326,
"s": 2274,
"text": "We can refer to components inside other components:"
},
{
"code": null,
"e": 2377,
"s": 2326,
"text": "Use the Car component inside the Garage component:"
},
{
"code": null,
"e": 2628,
"s": 2377,
"text": "function Car() {\n return <h2>I am a Car!</h2>;\n}\n\nfunction Garage() {\n return (\n <>\n <h1>Who lives in my Garage?</h1>\n <Car />\n </>\n );\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Garage />);\n"
},
{
"code": null,
"e": 2645,
"s": 2628,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 2747,
"s": 2645,
"text": "React is all about re-using code, and it is recommended to split your components into separate files."
},
{
"code": null,
"e": 2832,
"s": 2747,
"text": "To do that, create a new file with a .js \nfile extension and put the code inside it:"
},
{
"code": null,
"e": 2895,
"s": 2832,
"text": "Note that the filename must start with an uppercase character."
},
{
"code": null,
"e": 2939,
"s": 2895,
"text": "This is the new file, we named it \"Car.js\":"
},
{
"code": null,
"e": 3015,
"s": 2939,
"text": "function Car() {\n return <h2>Hi, I am a Car!</h2>;\n}\n\nexport default Car;\n"
},
{
"code": null,
"e": 3102,
"s": 3015,
"text": "To be able to use the Car component, you have to import the file in your \napplication."
},
{
"code": null,
"e": 3216,
"s": 3102,
"text": "Now we import the \"Car.js\" file in the application, and we can use the \nCar \ncomponent as if it was created here."
},
{
"code": null,
"e": 3403,
"s": 3216,
"text": "import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport Car from './Car.js';\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<Car />);\n"
},
{
"code": null,
"e": 3420,
"s": 3403,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 3465,
"s": 3420,
"text": "Name the following React component \"person\"."
},
{
"code": null,
"e": 3527,
"s": 3465,
"text": "function (props) {\n return <h2>Hi, I'm {props.name}</h2>;\n}\n"
},
{
"code": null,
"e": 3546,
"s": 3527,
"text": "Start the Exercise"
},
{
"code": null,
"e": 3579,
"s": 3546,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 3621,
"s": 3579,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 3728,
"s": 3621,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 3747,
"s": 3728,
"text": "help@w3schools.com"
}
] |
How to load CSS files using JavaScript? - GeeksforGeeks
|
30 Jul, 2021
The CSS file is used to describe how HTML elements will be displayed. There are various ways to add CSS file in the HTML document. JavaScript can also be used to load a CSS file in the HTML document.
Approach:
Use document.getElementsByTagName() method to get HTML head element.
Create new link element using createElement(‘link’) method.
Initialize the attributes of link element.
Append link element to the head.
Example 1: This example uses JavaScript to add CSS file in HTML document.
Create CSS file using name style.css:.GFG { color:green;}
.GFG { color:green;}
Use JavaScript to add CSS file:<!DOCTYPE html><html> <head> <title> Load CSS file using JavaScript </title> <script> // Get HTML head element var head = document.getElementsByTagName('HEAD')[0]; // Create new link Element var link = document.createElement('link'); // set the attributes for link element link.rel = 'stylesheet'; link.type = 'text/css'; link.href = 'style.css'; // Append link element to HTML head head.appendChild(link); </script> </head> <body> <h2 class="GFG">GeeksForGeeks</h2></body> </html>
<!DOCTYPE html><html> <head> <title> Load CSS file using JavaScript </title> <script> // Get HTML head element var head = document.getElementsByTagName('HEAD')[0]; // Create new link Element var link = document.createElement('link'); // set the attributes for link element link.rel = 'stylesheet'; link.type = 'text/css'; link.href = 'style.css'; // Append link element to HTML head head.appendChild(link); </script> </head> <body> <h2 class="GFG">GeeksForGeeks</h2></body> </html>
Output:
Example 2: This example uses JavaScript to add CSS file in HTML document.
Create CSS file using name style.css:.GFG { font-size:24px; font-weight:bold; color:white; background-color:green; padding:10px; text-align:center;}
.GFG { font-size:24px; font-weight:bold; color:white; background-color:green; padding:10px; text-align:center;}
Use JavaScript to add CSS file:<!DOCTYPE html><html> <head> <title> Load CSS file using JavaScript </title> <script> // Create new link Element var link = document.createElement('link'); // set the attributes for link element link.rel = 'stylesheet'; link.type = 'text/css'; link.href = 'style.css'; // Get HTML head element to append // link element to it document.getElementsByTagName('HEAD')[0].appendChild(link); </script> </head> <body> <div class="GFG">GeeksforGeeks</div></body> </html>
<!DOCTYPE html><html> <head> <title> Load CSS file using JavaScript </title> <script> // Create new link Element var link = document.createElement('link'); // set the attributes for link element link.rel = 'stylesheet'; link.type = 'text/css'; link.href = 'style.css'; // Get HTML head element to append // link element to it document.getElementsByTagName('HEAD')[0].appendChild(link); </script> </head> <body> <div class="GFG">GeeksforGeeks</div></body> </html>
Output:
HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.
CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
Picked
CSS
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to apply style to parent if it has child with CSS?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
How to set space between the flexbox ?
Design a web page using HTML and CSS
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
|
[
{
"code": null,
"e": 26495,
"s": 26467,
"text": "\n30 Jul, 2021"
},
{
"code": null,
"e": 26695,
"s": 26495,
"text": "The CSS file is used to describe how HTML elements will be displayed. There are various ways to add CSS file in the HTML document. JavaScript can also be used to load a CSS file in the HTML document."
},
{
"code": null,
"e": 26705,
"s": 26695,
"text": "Approach:"
},
{
"code": null,
"e": 26774,
"s": 26705,
"text": "Use document.getElementsByTagName() method to get HTML head element."
},
{
"code": null,
"e": 26834,
"s": 26774,
"text": "Create new link element using createElement(‘link’) method."
},
{
"code": null,
"e": 26877,
"s": 26834,
"text": "Initialize the attributes of link element."
},
{
"code": null,
"e": 26910,
"s": 26877,
"text": "Append link element to the head."
},
{
"code": null,
"e": 26984,
"s": 26910,
"text": "Example 1: This example uses JavaScript to add CSS file in HTML document."
},
{
"code": null,
"e": 27045,
"s": 26984,
"text": "Create CSS file using name style.css:.GFG { color:green;}"
},
{
"code": ".GFG { color:green;}",
"e": 27069,
"s": 27045,
"text": null
},
{
"code": null,
"e": 27732,
"s": 27069,
"text": "Use JavaScript to add CSS file:<!DOCTYPE html><html> <head> <title> Load CSS file using JavaScript </title> <script> // Get HTML head element var head = document.getElementsByTagName('HEAD')[0]; // Create new link Element var link = document.createElement('link'); // set the attributes for link element link.rel = 'stylesheet'; link.type = 'text/css'; link.href = 'style.css'; // Append link element to HTML head head.appendChild(link); </script> </head> <body> <h2 class=\"GFG\">GeeksForGeeks</h2></body> </html> "
},
{
"code": "<!DOCTYPE html><html> <head> <title> Load CSS file using JavaScript </title> <script> // Get HTML head element var head = document.getElementsByTagName('HEAD')[0]; // Create new link Element var link = document.createElement('link'); // set the attributes for link element link.rel = 'stylesheet'; link.type = 'text/css'; link.href = 'style.css'; // Append link element to HTML head head.appendChild(link); </script> </head> <body> <h2 class=\"GFG\">GeeksForGeeks</h2></body> </html> ",
"e": 28364,
"s": 27732,
"text": null
},
{
"code": null,
"e": 28372,
"s": 28364,
"text": "Output:"
},
{
"code": null,
"e": 28446,
"s": 28372,
"text": "Example 2: This example uses JavaScript to add CSS file in HTML document."
},
{
"code": null,
"e": 28613,
"s": 28446,
"text": "Create CSS file using name style.css:.GFG { font-size:24px; font-weight:bold; color:white; background-color:green; padding:10px; text-align:center;}"
},
{
"code": ".GFG { font-size:24px; font-weight:bold; color:white; background-color:green; padding:10px; text-align:center;}",
"e": 28743,
"s": 28613,
"text": null
},
{
"code": null,
"e": 29380,
"s": 28743,
"text": "Use JavaScript to add CSS file:<!DOCTYPE html><html> <head> <title> Load CSS file using JavaScript </title> <script> // Create new link Element var link = document.createElement('link'); // set the attributes for link element link.rel = 'stylesheet'; link.type = 'text/css'; link.href = 'style.css'; // Get HTML head element to append // link element to it document.getElementsByTagName('HEAD')[0].appendChild(link); </script> </head> <body> <div class=\"GFG\">GeeksforGeeks</div></body> </html> "
},
{
"code": "<!DOCTYPE html><html> <head> <title> Load CSS file using JavaScript </title> <script> // Create new link Element var link = document.createElement('link'); // set the attributes for link element link.rel = 'stylesheet'; link.type = 'text/css'; link.href = 'style.css'; // Get HTML head element to append // link element to it document.getElementsByTagName('HEAD')[0].appendChild(link); </script> </head> <body> <div class=\"GFG\">GeeksforGeeks</div></body> </html> ",
"e": 29986,
"s": 29380,
"text": null
},
{
"code": null,
"e": 29994,
"s": 29986,
"text": "Output:"
},
{
"code": null,
"e": 30188,
"s": 29994,
"text": "HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples."
},
{
"code": null,
"e": 30374,
"s": 30188,
"text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples."
},
{
"code": null,
"e": 30381,
"s": 30374,
"text": "Picked"
},
{
"code": null,
"e": 30385,
"s": 30381,
"text": "CSS"
},
{
"code": null,
"e": 30390,
"s": 30385,
"text": "HTML"
},
{
"code": null,
"e": 30401,
"s": 30390,
"text": "JavaScript"
},
{
"code": null,
"e": 30418,
"s": 30401,
"text": "Web Technologies"
},
{
"code": null,
"e": 30423,
"s": 30418,
"text": "HTML"
},
{
"code": null,
"e": 30521,
"s": 30423,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30576,
"s": 30521,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 30613,
"s": 30576,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 30677,
"s": 30613,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 30716,
"s": 30677,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 30753,
"s": 30716,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 30813,
"s": 30753,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 30866,
"s": 30813,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 30927,
"s": 30866,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 30951,
"s": 30927,
"text": "REST API (Introduction)"
}
] |
DataTables orderCellsTop Option - GeeksforGeeks
|
21 Jul, 2021
DataTables is jQuery plugin that can be used for adding interactive and advanced controls to HTML tables for the webpage. This also allows the data in the table to be searched, sorted, and filtered according to the needs of the user. The DataTable also exposes a powerful API that can be further used to modify how the data is displayed.
The orderCellsTop option is used to specify in which cell the order event handler will be applied to in the table. This can be used in cases when multiple complex headers are used. Setting the option to true will attach the order event handler to the top unique cell of the table, while setting the option to false will attach it to the bottom cell of the table, which is the default behaviour.
{ orderCellsTop: value }
Parameters: This option has a single value as mentioned above and described below:
value: This is a boolean value that is used to specify in which cell of the header the order event handler will be attached. The default value is false.
The examples below illustrate the use of this option.
Example 1: In this example, the order event handler will be applied to the top cell of the header.
HTML
<!DOCTYPE html><html> <head> <!-- jQuery --> <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"> </script> <!-- DataTables CSS --> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css"> <!-- DataTables JS --> <script src= "https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"> </script></head> <body> <h1 style="color: green;"> GeeksForGeeks </h1> <h3>DataTables orderCellsTop Option</h3> <!-- HTML table with random data --> <table id="tableID" class="display nowrap"> <thead> <tr> <th>Day</th> <th>Name</th> <th>Age</th> </tr> <tr> <th>Day Selector</th> <th>Name Selector</th> <th>Age Selector</th> </tr> </thead> <tbody> <tr> <td>2</td> <td>Patricia</td> <td>22</td> </tr> <tr> <td>2</td> <td>Caleb</td> <td>47</td> </tr> <tr> <td>1</td> <td>Abigail</td> <td>48</td> </tr> <tr> <td>5</td> <td>Rahim</td> <td>44</td> </tr> <tr> <td>5</td> <td>Sheila</td> <td>22</td> </tr> <tr> <td>2</td> <td>Lance</td> <td>48</td> </tr> <tr> <td>5</td> <td>Erin</td> <td>48</td> </tr> <tr> <td>1</td> <td>Christopher</td> <td>28</td> </tr> <tr> <td>2</td> <td>Roary</td> <td>35</td> </tr> <tr> <td>4</td> <td>Mikasa</td> <td>48</td> </tr> <tr> <td>2</td> <td>Astra</td> <td>37</td> </tr> <tr> <td>5</td> <td>Eren</td> <td>48</td> </tr> </tbody> </table> <script> // Initialize the DataTable $(document).ready(function () { $('#tableID').DataTable({ // Use the bottom cell for // the order listener orderCellsTop: false, }); }); </script></body> </html>
Output:
Example 2: In this example, the order event handler will be applied to the bottom cell of the header.
HTML
<!DOCTYPE html><html> <head> <!-- jQuery --> <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"> </script> <!-- DataTables CSS --> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css"> <!-- DataTables JS --> <script src= "https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"> </script></head> <body> <h1 style="color: green;"> GeeksForGeeks </h1> <h3>DataTables orderCellsTop Option</h3> <!-- HTML table with random data --> <table id="tableID" class="display nowrap"> <thead> <tr> <th>Day</th> <th>Name</th> <th>Age</th> </tr> <tr> <th>Day Selector</th> <th>Name Selector</th> <th>Age Selector</th> </tr> </thead> <tbody> <tr> <td>2</td> <td>Patricia</td> <td>22</td> </tr> <tr> <td>2</td> <td>Caleb</td> <td>47</td> </tr> <tr> <td>1</td> <td>Abigail</td> <td>48</td> </tr> <tr> <td>5</td> <td>Rahim</td> <td>44</td> </tr> <tr> <td>5</td> <td>Sheila</td> <td>22</td> </tr> <tr> <td>2</td> <td>Lance</td> <td>48</td> </tr> <tr> <td>5</td> <td>Erin</td> <td>48</td> </tr> <tr> <td>1</td> <td>Christopher</td> <td>28</td> </tr> <tr> <td>2</td> <td>Roary</td> <td>35</td> </tr> <tr> <td>4</td> <td>Mikasa</td> <td>48</td> </tr> <tr> <td>2</td> <td>Astra</td> <td>37</td> </tr> <tr> <td>5</td> <td>Eren</td> <td>48</td> </tr> </tbody> </table> <script> // Initialize the DataTable $(document).ready(function () { $('#tableID').DataTable({ // Use the top unique cell for // the order listener orderCellsTop: true, }); }); </script></body> </html>
Output:
Reference: https://datatables.net/reference/option/orderCellsTop
jQuery-DataTables
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show and Hide div elements using radio buttons?
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
jQuery | removeAttr() with Examples
How to get the value in an input text box using jQuery ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 26954,
"s": 26926,
"text": "\n21 Jul, 2021"
},
{
"code": null,
"e": 27292,
"s": 26954,
"text": "DataTables is jQuery plugin that can be used for adding interactive and advanced controls to HTML tables for the webpage. This also allows the data in the table to be searched, sorted, and filtered according to the needs of the user. The DataTable also exposes a powerful API that can be further used to modify how the data is displayed."
},
{
"code": null,
"e": 27687,
"s": 27292,
"text": "The orderCellsTop option is used to specify in which cell the order event handler will be applied to in the table. This can be used in cases when multiple complex headers are used. Setting the option to true will attach the order event handler to the top unique cell of the table, while setting the option to false will attach it to the bottom cell of the table, which is the default behaviour."
},
{
"code": null,
"e": 27712,
"s": 27687,
"text": "{ orderCellsTop: value }"
},
{
"code": null,
"e": 27795,
"s": 27712,
"text": "Parameters: This option has a single value as mentioned above and described below:"
},
{
"code": null,
"e": 27948,
"s": 27795,
"text": "value: This is a boolean value that is used to specify in which cell of the header the order event handler will be attached. The default value is false."
},
{
"code": null,
"e": 28002,
"s": 27948,
"text": "The examples below illustrate the use of this option."
},
{
"code": null,
"e": 28103,
"s": 28004,
"text": "Example 1: In this example, the order event handler will be applied to the top cell of the header."
},
{
"code": null,
"e": 28108,
"s": 28103,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- jQuery --> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-3.5.1.js\"> </script> <!-- DataTables CSS --> <link rel=\"stylesheet\" href=\"https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css\"> <!-- DataTables JS --> <script src= \"https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js\"> </script></head> <body> <h1 style=\"color: green;\"> GeeksForGeeks </h1> <h3>DataTables orderCellsTop Option</h3> <!-- HTML table with random data --> <table id=\"tableID\" class=\"display nowrap\"> <thead> <tr> <th>Day</th> <th>Name</th> <th>Age</th> </tr> <tr> <th>Day Selector</th> <th>Name Selector</th> <th>Age Selector</th> </tr> </thead> <tbody> <tr> <td>2</td> <td>Patricia</td> <td>22</td> </tr> <tr> <td>2</td> <td>Caleb</td> <td>47</td> </tr> <tr> <td>1</td> <td>Abigail</td> <td>48</td> </tr> <tr> <td>5</td> <td>Rahim</td> <td>44</td> </tr> <tr> <td>5</td> <td>Sheila</td> <td>22</td> </tr> <tr> <td>2</td> <td>Lance</td> <td>48</td> </tr> <tr> <td>5</td> <td>Erin</td> <td>48</td> </tr> <tr> <td>1</td> <td>Christopher</td> <td>28</td> </tr> <tr> <td>2</td> <td>Roary</td> <td>35</td> </tr> <tr> <td>4</td> <td>Mikasa</td> <td>48</td> </tr> <tr> <td>2</td> <td>Astra</td> <td>37</td> </tr> <tr> <td>5</td> <td>Eren</td> <td>48</td> </tr> </tbody> </table> <script> // Initialize the DataTable $(document).ready(function () { $('#tableID').DataTable({ // Use the bottom cell for // the order listener orderCellsTop: false, }); }); </script></body> </html>",
"e": 30173,
"s": 28108,
"text": null
},
{
"code": null,
"e": 30181,
"s": 30173,
"text": "Output:"
},
{
"code": null,
"e": 30283,
"s": 30181,
"text": "Example 2: In this example, the order event handler will be applied to the bottom cell of the header."
},
{
"code": null,
"e": 30288,
"s": 30283,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- jQuery --> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-3.5.1.js\"> </script> <!-- DataTables CSS --> <link rel=\"stylesheet\" href=\"https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css\"> <!-- DataTables JS --> <script src= \"https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js\"> </script></head> <body> <h1 style=\"color: green;\"> GeeksForGeeks </h1> <h3>DataTables orderCellsTop Option</h3> <!-- HTML table with random data --> <table id=\"tableID\" class=\"display nowrap\"> <thead> <tr> <th>Day</th> <th>Name</th> <th>Age</th> </tr> <tr> <th>Day Selector</th> <th>Name Selector</th> <th>Age Selector</th> </tr> </thead> <tbody> <tr> <td>2</td> <td>Patricia</td> <td>22</td> </tr> <tr> <td>2</td> <td>Caleb</td> <td>47</td> </tr> <tr> <td>1</td> <td>Abigail</td> <td>48</td> </tr> <tr> <td>5</td> <td>Rahim</td> <td>44</td> </tr> <tr> <td>5</td> <td>Sheila</td> <td>22</td> </tr> <tr> <td>2</td> <td>Lance</td> <td>48</td> </tr> <tr> <td>5</td> <td>Erin</td> <td>48</td> </tr> <tr> <td>1</td> <td>Christopher</td> <td>28</td> </tr> <tr> <td>2</td> <td>Roary</td> <td>35</td> </tr> <tr> <td>4</td> <td>Mikasa</td> <td>48</td> </tr> <tr> <td>2</td> <td>Astra</td> <td>37</td> </tr> <tr> <td>5</td> <td>Eren</td> <td>48</td> </tr> </tbody> </table> <script> // Initialize the DataTable $(document).ready(function () { $('#tableID').DataTable({ // Use the top unique cell for // the order listener orderCellsTop: true, }); }); </script></body> </html>",
"e": 32356,
"s": 30288,
"text": null
},
{
"code": null,
"e": 32364,
"s": 32356,
"text": "Output:"
},
{
"code": null,
"e": 32429,
"s": 32364,
"text": "Reference: https://datatables.net/reference/option/orderCellsTop"
},
{
"code": null,
"e": 32447,
"s": 32429,
"text": "jQuery-DataTables"
},
{
"code": null,
"e": 32454,
"s": 32447,
"text": "JQuery"
},
{
"code": null,
"e": 32471,
"s": 32454,
"text": "Web Technologies"
},
{
"code": null,
"e": 32569,
"s": 32471,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32624,
"s": 32569,
"text": "How to Show and Hide div elements using radio buttons?"
},
{
"code": null,
"e": 32697,
"s": 32624,
"text": "How to prevent Body from scrolling when a modal is opened using jQuery ?"
},
{
"code": null,
"e": 32720,
"s": 32697,
"text": "jQuery | ajax() Method"
},
{
"code": null,
"e": 32756,
"s": 32720,
"text": "jQuery | removeAttr() with Examples"
},
{
"code": null,
"e": 32813,
"s": 32756,
"text": "How to get the value in an input text box using jQuery ?"
},
{
"code": null,
"e": 32853,
"s": 32813,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 32886,
"s": 32853,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 32931,
"s": 32886,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 32974,
"s": 32931,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Get and Post method using Fetch API - GeeksforGeeks
|
17 Sep, 2021
The fetch() method is used to send the requests to the server without refreshing the page. It is an alternative to the XMLHttpRequest object.The basic syntax of a fetch() request is as follows:
javascript
fetch(url, {options}).then(data => { // Do some stuff here}).catch(err => { // Catch and display errors})
The difference between XMLHttpRequest and fetch is that fetch uses Promises which are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code.However there are still some browsers that do not support fetch() method, so for those, we have to stick with the XMLHttpRequest object.A fetch() method can be used with many type of requests such as POST, GET, PUT and DELETE.GET method using fetch API: In this example, we are going to use JSONPlaceholder which provides REST API get and post random data such as posts, users, etc.First of all, create an HTML file with the following code:
html
<!DOCTYPE html><html lang="en"> <head> <title>Fetch API</title> </head> <body> <div> <h1>Fetch API GET REQUEST</h1> <h3>Fetching Users</h3> <!-- Table to display fetched user data --> <table id="users"></table> </div> <!-- Link JavaScript file --> <script src="main.js"></script> </body></html>
In JavaScript, file contains the following code
javascript
// main.js // GET request using fetch()fetch("https://jsonplaceholder.typicode.com/users") // Converting received data to JSON .then(response => response.json()) .then(json => { // Create a variable to store HTML let li = `<tr><th>Name</th><th>Email</th></tr>`; // Loop through each data and add a table row json.forEach(user => { li += `<tr> <td>${user.name} </td> <td>${user.email}</td> </tr>`; }); // Display result document.getElementById("users").innerHTML = li;});
Now, when you open the HTML file you’ll see the result as follows:
When you open DevTools in Chrome (Press F12) you’ll see that a fetch request has been made to the route users.
You can get more data from the request, refer to the documentation.POST request using fetch API: The post request is widely used to submit forms to the server. Fetch also supports the POST method call. To do a POST request we need to specify additional parameters with the request such as method, headers, etc. In this example, we’ll do a POST request on the same JSONPlaceholder and add a post in the posts. It’ll then return the same post content with an ID.In the same JavaScript file add the following content:
javascript
// main.js // POST request using fetch()fetch("https://jsonplaceholder.typicode.com/posts", { // Adding method type method: "POST", // Adding body or contents to send body: JSON.stringify({ title: "foo", body: "bar", userId: 1 }), // Adding headers to the request headers: { "Content-type": "application/json; charset=UTF-8" }}) // Converting to JSON.then(response => response.json()) // Displaying results to console.then(json => console.log(json));
Now if you open your javascript console and refresh the page you’ll see a result like below –
The API returns a status of 201 which is a HTTP status code for Created.
abhishek0719kadiyan
Picked
Web-API
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to create footer to stay at the bottom of a Web page?
Differences between Functional Components and Class Components in React
Node.js fs.readFileSync() Method
|
[
{
"code": null,
"e": 25675,
"s": 25647,
"text": "\n17 Sep, 2021"
},
{
"code": null,
"e": 25871,
"s": 25675,
"text": "The fetch() method is used to send the requests to the server without refreshing the page. It is an alternative to the XMLHttpRequest object.The basic syntax of a fetch() request is as follows: "
},
{
"code": null,
"e": 25882,
"s": 25871,
"text": "javascript"
},
{
"code": "fetch(url, {options}).then(data => { // Do some stuff here}).catch(err => { // Catch and display errors})",
"e": 25994,
"s": 25882,
"text": null
},
{
"code": null,
"e": 26659,
"s": 25994,
"text": "The difference between XMLHttpRequest and fetch is that fetch uses Promises which are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code.However there are still some browsers that do not support fetch() method, so for those, we have to stick with the XMLHttpRequest object.A fetch() method can be used with many type of requests such as POST, GET, PUT and DELETE.GET method using fetch API: In this example, we are going to use JSONPlaceholder which provides REST API get and post random data such as posts, users, etc.First of all, create an HTML file with the following code: "
},
{
"code": null,
"e": 26664,
"s": 26659,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Fetch API</title> </head> <body> <div> <h1>Fetch API GET REQUEST</h1> <h3>Fetching Users</h3> <!-- Table to display fetched user data --> <table id=\"users\"></table> </div> <!-- Link JavaScript file --> <script src=\"main.js\"></script> </body></html>",
"e": 27005,
"s": 26664,
"text": null
},
{
"code": null,
"e": 27055,
"s": 27005,
"text": "In JavaScript, file contains the following code "
},
{
"code": null,
"e": 27066,
"s": 27055,
"text": "javascript"
},
{
"code": "// main.js // GET request using fetch()fetch(\"https://jsonplaceholder.typicode.com/users\") // Converting received data to JSON .then(response => response.json()) .then(json => { // Create a variable to store HTML let li = `<tr><th>Name</th><th>Email</th></tr>`; // Loop through each data and add a table row json.forEach(user => { li += `<tr> <td>${user.name} </td> <td>${user.email}</td> </tr>`; }); // Display result document.getElementById(\"users\").innerHTML = li;});",
"e": 27664,
"s": 27066,
"text": null
},
{
"code": null,
"e": 27733,
"s": 27664,
"text": "Now, when you open the HTML file you’ll see the result as follows: "
},
{
"code": null,
"e": 27846,
"s": 27733,
"text": "When you open DevTools in Chrome (Press F12) you’ll see that a fetch request has been made to the route users. "
},
{
"code": null,
"e": 28363,
"s": 27846,
"text": "You can get more data from the request, refer to the documentation.POST request using fetch API: The post request is widely used to submit forms to the server. Fetch also supports the POST method call. To do a POST request we need to specify additional parameters with the request such as method, headers, etc. In this example, we’ll do a POST request on the same JSONPlaceholder and add a post in the posts. It’ll then return the same post content with an ID.In the same JavaScript file add the following content: "
},
{
"code": null,
"e": 28374,
"s": 28363,
"text": "javascript"
},
{
"code": "// main.js // POST request using fetch()fetch(\"https://jsonplaceholder.typicode.com/posts\", { // Adding method type method: \"POST\", // Adding body or contents to send body: JSON.stringify({ title: \"foo\", body: \"bar\", userId: 1 }), // Adding headers to the request headers: { \"Content-type\": \"application/json; charset=UTF-8\" }}) // Converting to JSON.then(response => response.json()) // Displaying results to console.then(json => console.log(json));",
"e": 28894,
"s": 28374,
"text": null
},
{
"code": null,
"e": 28990,
"s": 28894,
"text": "Now if you open your javascript console and refresh the page you’ll see a result like below – "
},
{
"code": null,
"e": 29064,
"s": 28990,
"text": "The API returns a status of 201 which is a HTTP status code for Created. "
},
{
"code": null,
"e": 29084,
"s": 29064,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 29091,
"s": 29084,
"text": "Picked"
},
{
"code": null,
"e": 29099,
"s": 29091,
"text": "Web-API"
},
{
"code": null,
"e": 29118,
"s": 29099,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29135,
"s": 29118,
"text": "Web Technologies"
},
{
"code": null,
"e": 29233,
"s": 29135,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29273,
"s": 29233,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29306,
"s": 29273,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29351,
"s": 29306,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29394,
"s": 29351,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29444,
"s": 29394,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 29505,
"s": 29444,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29567,
"s": 29505,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 29625,
"s": 29567,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 29697,
"s": 29625,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Ruby | Hash each_key() function - GeeksforGeeks
|
07 Jan, 2020
Hash#each_key() is a Hash class method which finds the nested value which calls block once for each_key key in hash by passing the key pair as parameters.
Syntax: Hash.each_key()
Parameter: Hash values
Return: calls block once for each_key key in hash with key as parameter otherwise Enumerator if no argument is passed.
Example #1 :
# Ruby code for Hash.each_key() method # declaring Hash valuea = {a:100, b:200} # declaring Hash valueb = {a:100, c:300, b:200} # declaring Hash valuec = {a:100} # each Valueputs "Hash a each_key form : #{a.each_key()}\n\n" puts "Hash b each_key form : #{b.each_key {|key| puts "#{key}"}}\n\n" puts "Hash c each_key form : #{c.each_key {|value| puts "#{value}"}}\n\n"
Output :
Hash a each_key form : #
a
c
b
Hash b each_key form : {:a=>100, :c=>300, :b=>200}
a
Hash c each_key form : {:a=>100}
Example #2 :
# Ruby code for Hash.each_key() method # declaring Hash valuea = { "a" => 100, "b" => 200 } # declaring Hash valueb = {"a" => 100} # declaring Hash valuec = {"a" => 100, "c" => 300, "b" => 200} # each Valueputs "Hash a each_key form : #{a.each_key()}\n\n" puts "Hash b each_key form : #{b.each_key {|key| puts "#{key}"}}\n\n" puts "Hash c each_key form : #{c.each_key {|value| puts "#{value}"}}\n\n"
Output :
Hash a each_key form : #
a
Hash b each_key form : {"a"=>100}
a
c
b
Hash c each_key form : {"a"=>100, "c"=>300, "b"=>200}
Ruby Hash-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | Array count() operation
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Hash delete() function
Ruby | Types of Variables
Ruby | Enumerator each_with_index function
Ruby | Case Statement
Ruby | Array select() function
Ruby | Numeric round() function
Ruby | Data Types
|
[
{
"code": null,
"e": 24995,
"s": 24967,
"text": "\n07 Jan, 2020"
},
{
"code": null,
"e": 25150,
"s": 24995,
"text": "Hash#each_key() is a Hash class method which finds the nested value which calls block once for each_key key in hash by passing the key pair as parameters."
},
{
"code": null,
"e": 25174,
"s": 25150,
"text": "Syntax: Hash.each_key()"
},
{
"code": null,
"e": 25197,
"s": 25174,
"text": "Parameter: Hash values"
},
{
"code": null,
"e": 25316,
"s": 25197,
"text": "Return: calls block once for each_key key in hash with key as parameter otherwise Enumerator if no argument is passed."
},
{
"code": null,
"e": 25329,
"s": 25316,
"text": "Example #1 :"
},
{
"code": "# Ruby code for Hash.each_key() method # declaring Hash valuea = {a:100, b:200} # declaring Hash valueb = {a:100, c:300, b:200} # declaring Hash valuec = {a:100} # each Valueputs \"Hash a each_key form : #{a.each_key()}\\n\\n\" puts \"Hash b each_key form : #{b.each_key {|key| puts \"#{key}\"}}\\n\\n\" puts \"Hash c each_key form : #{c.each_key {|value| puts \"#{value}\"}}\\n\\n\"",
"e": 25705,
"s": 25329,
"text": null
},
{
"code": null,
"e": 25714,
"s": 25705,
"text": "Output :"
},
{
"code": null,
"e": 25835,
"s": 25714,
"text": "Hash a each_key form : #\n\na\nc\nb\nHash b each_key form : {:a=>100, :c=>300, :b=>200}\n\na\nHash c each_key form : {:a=>100}\n\n"
},
{
"code": null,
"e": 25848,
"s": 25835,
"text": "Example #2 :"
},
{
"code": "# Ruby code for Hash.each_key() method # declaring Hash valuea = { \"a\" => 100, \"b\" => 200 } # declaring Hash valueb = {\"a\" => 100} # declaring Hash valuec = {\"a\" => 100, \"c\" => 300, \"b\" => 200} # each Valueputs \"Hash a each_key form : #{a.each_key()}\\n\\n\" puts \"Hash b each_key form : #{b.each_key {|key| puts \"#{key}\"}}\\n\\n\" puts \"Hash c each_key form : #{c.each_key {|value| puts \"#{value}\"}}\\n\\n\"",
"e": 26256,
"s": 25848,
"text": null
},
{
"code": null,
"e": 26265,
"s": 26256,
"text": "Output :"
},
{
"code": null,
"e": 26390,
"s": 26265,
"text": "Hash a each_key form : #\n\na\nHash b each_key form : {\"a\"=>100}\n\na\nc\nb\nHash c each_key form : {\"a\"=>100, \"c\"=>300, \"b\"=>200}\n\n"
},
{
"code": null,
"e": 26406,
"s": 26390,
"text": "Ruby Hash-class"
},
{
"code": null,
"e": 26419,
"s": 26406,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 26424,
"s": 26419,
"text": "Ruby"
},
{
"code": null,
"e": 26522,
"s": 26424,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26553,
"s": 26522,
"text": "Ruby | Array count() operation"
},
{
"code": null,
"e": 26580,
"s": 26553,
"text": "Include v/s Extend in Ruby"
},
{
"code": null,
"e": 26604,
"s": 26580,
"text": "Global Variable in Ruby"
},
{
"code": null,
"e": 26634,
"s": 26604,
"text": "Ruby | Hash delete() function"
},
{
"code": null,
"e": 26660,
"s": 26634,
"text": "Ruby | Types of Variables"
},
{
"code": null,
"e": 26703,
"s": 26660,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 26725,
"s": 26703,
"text": "Ruby | Case Statement"
},
{
"code": null,
"e": 26756,
"s": 26725,
"text": "Ruby | Array select() function"
},
{
"code": null,
"e": 26788,
"s": 26756,
"text": "Ruby | Numeric round() function"
}
] |
Mean and Median of a matrix - GeeksforGeeks
|
19 Apr, 2021
Given a sorted matrix of size n*n. Calculate the mean and median of the matrix .Examples:
Input : 1 2 3
4 5 6
7 8 9
Output :Mean: 5
Median: 5
Input : 1 1 1
2 2 2
4 4 4
Output :Mean: 2
Median: 2
Mean of matrix is =
(sum of all elements of matrix)/
(total elements of matrix)
Note that this definition doesn't require
matrix to be sorted and works for all
matrices.
Median of a sorted matrix is calculated as:
1. When n is odd
median is mat[n/2][n/2]
2. When n is even, median is average
of middle two elements.
Middle two elements can be found at indexes
a[(n-2)/2][n-1] and a[n/2][0]
If given matrix is unsorted, we can find its median by first sorting the matrix.
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find mean and median// of sorted square matrix.#include <bits/stdc++.h>using namespace std; const int N = 4; // Returns mean of a given matrix of// size n x n.double findMean(int a[][N]){ int sum = 0; // total sum calculation of matrix for (int i=0; i<N; i++) for (int j=0; j<N; j++) sum += a[i][j]; return (double)sum/(N*N);} // Function for calculating mediandouble findMedian(int a[][N]){ if (N % 2 != 0) return a[N/2][N/2]; if (N%2 == 0) return (a[(N-2)/2][N-1] + a[N/2][0])/2.0;} // Driver programint main(){ int a[N][N]= {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; cout << "Mean : " << findMean(a) << endl << "Median : "<< findMedian(a) << endl; return 0;}
// Java program to find mean and median// of sorted square matrix.import java.io.*; class GFG{ // Returns mean of a given// matrix of size n x n.static double findMean(int a[][], int n){ int sum = 0; int N=n; // total sum calculation of matrix for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) sum += a[i][j]; return (double)sum / (N * N);} // Function for calculating medianstatic double findMedian(int a[][], int n){ int N = n; if (N % 2 != 0) return a[N / 2][N / 2]; if (N % 2 == 0) return (a[(N - 2) / 2][ N - 1] + a[ N / 2][0]) / (2.0); return 0;} // Driver Code public static void main (String[] args) { int a[][]= {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; int n = a.length; System.out.println("Mean : " + findMean(a, n)); System.out.println("Median : " + findMedian(a, n)); } } // This code is contributed by KRV.
# Python3 program to find mean and median# of sorted square matrix.N = 4 # Returns mean of a given matrix of# size n x n.def findMean(a): summ = 0 # total sum calculation of matrix for i in range(N): for j in range(N): summ += a[i][j] return summ/(N*N) # Function for calculating mediandef findMedian(a): if (N % 2 != 0): return a[N//2][N//2] if (N % 2 == 0): return (a[(N - 2)//2][N - 1] + a[N//2][0])/2 # Driver programa = [[1, 2, 3, 4],[5, 6, 7, 8], [9, 10, 11, 12],[13, 14, 15, 16]]print("Mean :", findMean(a))print("Median :",findMedian(a)) # This code is contributed by shubhamsingh10
// C# program to find mean and median// of sorted square matrix.using System; class GFG { // Returns mean of a given // matrix of size n x n. static double findMean(int [,]a, int n) { int sum = 0; int N = n; // total sum calculation of matrix for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) sum += a[i,j]; return (double)sum / (N * N); } // Function for calculating median static double findMedian(int [,]a, int n) { int N = n; if (N % 2 != 0) return a[N / 2,N / 2]; if (N % 2 == 0) return ( a[(N - 2) / 2, (N - 1)] + a[ N / 2, 0] ) / (2.0); return 0; } // Driver Code public static void Main () { int [,]a= { { 1, 2, 3, 4}, { 5, 6, 7, 8}, { 9, 10, 11, 12}, {13, 14, 15, 16} }; int n = a.GetLength(0); Console.WriteLine("Mean : " + findMean(a, n)); Console.WriteLine("Median : " + findMedian(a, n)); } } // This code is contributed by Sam007.
<?php// PHP program to find// mean and median// of sorted square// matrix. $N = 4; // Returns mean of// a given matrix of// size n x n.function findMean($a){ global $N; $sum = 0; // total sum calculation // of matrix for ($i = 0; $i < $N; $i++) for ($j = 0; $j < $N; $j++) $sum += $a[$i][$j]; return (double)$sum / ($N * $N);} // Function for calculating medianfunction findMedian($a){ global $N; if ($N % 2 != 0) return $a[$N / 2][$N / 2]; if ($N % 2 == 0) return ($a[($N - 2) / 2][$N - 1] + $a[$N / 2][0]) / 2.0;} // Driver Code $a= array(array(1, 2, 3, 4), array(5, 6, 7, 8), array(9, 10, 11, 12), array(13, 14, 15, 16)); echo "Mean : " , findMean($a),"\n", "Median : ", findMedian($a); // This code is contributed by vt_m.?>
<script> // Javascriptprogram to find mean and median// of sorted square matrix. // Returns mean of a given// matrix of size n x n.function findMean(a, n){ var sum = 0; var N = n; // Total sum calculation of matrix for(var i = 0; i < N; i++) for(var j = 0; j < N; j++) sum += a[i][j]; return sum / (N * N);} // Function for calculating medianfunction findMedian(a, n){ var N = n; if (N % 2 != 0) return a[N / 2][N / 2]; if (N % 2 == 0) return (a[(N - 2) / 2][ N - 1] + a[N / 2][0]) / (2.0); return 0;} // Driver Codevar a = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ]; var n = a.length;document.write("Mean : " + findMean(a, n) + "<br>");document.write("Median : " + findMedian(a, n) + "<br>"); // This code is contributed by Kirti </script>
Output:
Mean : 8.5
Median : 8.5
This article is contributed by Himanshu Ranjan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
KRV
vt_m
Sam007
SHUBHAMSINGH10
Kirti_Mangal
maths-mean
median-finding
Order-Statistics
statistical-algorithms
Matrix
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum size square sub-matrix with all 1s
Sudoku | Backtracking-7
Count all possible paths from top left to bottom right of a mXn matrix
Maximum size rectangle binary sub-matrix with all 1s
Inplace rotate square matrix by 90 degrees | Set 1
Min Cost Path | DP-6
Printing all solutions in N-Queen Problem
Rotate a matrix by 90 degree in clockwise direction without using any extra space
The Celebrity Problem
Python program to multiply two matrices
|
[
{
"code": null,
"e": 26499,
"s": 26471,
"text": "\n19 Apr, 2021"
},
{
"code": null,
"e": 26591,
"s": 26499,
"text": "Given a sorted matrix of size n*n. Calculate the mean and median of the matrix .Examples: "
},
{
"code": null,
"e": 26744,
"s": 26591,
"text": "Input : 1 2 3\n 4 5 6\n 7 8 9\nOutput :Mean: 5\n Median: 5\n\nInput : 1 1 1\n 2 2 2\n 4 4 4\nOutput :Mean: 2\n Median: 2"
},
{
"code": null,
"e": 27161,
"s": 26746,
"text": "Mean of matrix is = \n (sum of all elements of matrix)/\n (total elements of matrix)\nNote that this definition doesn't require\nmatrix to be sorted and works for all\nmatrices.\n\nMedian of a sorted matrix is calculated as:\n1. When n is odd\n median is mat[n/2][n/2]\n2. When n is even, median is average\n of middle two elements.\n Middle two elements can be found at indexes\n a[(n-2)/2][n-1] and a[n/2][0] "
},
{
"code": null,
"e": 27243,
"s": 27161,
"text": "If given matrix is unsorted, we can find its median by first sorting the matrix. "
},
{
"code": null,
"e": 27247,
"s": 27243,
"text": "C++"
},
{
"code": null,
"e": 27252,
"s": 27247,
"text": "Java"
},
{
"code": null,
"e": 27260,
"s": 27252,
"text": "Python3"
},
{
"code": null,
"e": 27263,
"s": 27260,
"text": "C#"
},
{
"code": null,
"e": 27267,
"s": 27263,
"text": "PHP"
},
{
"code": null,
"e": 27278,
"s": 27267,
"text": "Javascript"
},
{
"code": "// CPP program to find mean and median// of sorted square matrix.#include <bits/stdc++.h>using namespace std; const int N = 4; // Returns mean of a given matrix of// size n x n.double findMean(int a[][N]){ int sum = 0; // total sum calculation of matrix for (int i=0; i<N; i++) for (int j=0; j<N; j++) sum += a[i][j]; return (double)sum/(N*N);} // Function for calculating mediandouble findMedian(int a[][N]){ if (N % 2 != 0) return a[N/2][N/2]; if (N%2 == 0) return (a[(N-2)/2][N-1] + a[N/2][0])/2.0;} // Driver programint main(){ int a[N][N]= {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; cout << \"Mean : \" << findMean(a) << endl << \"Median : \"<< findMedian(a) << endl; return 0;}",
"e": 28121,
"s": 27278,
"text": null
},
{
"code": "// Java program to find mean and median// of sorted square matrix.import java.io.*; class GFG{ // Returns mean of a given// matrix of size n x n.static double findMean(int a[][], int n){ int sum = 0; int N=n; // total sum calculation of matrix for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) sum += a[i][j]; return (double)sum / (N * N);} // Function for calculating medianstatic double findMedian(int a[][], int n){ int N = n; if (N % 2 != 0) return a[N / 2][N / 2]; if (N % 2 == 0) return (a[(N - 2) / 2][ N - 1] + a[ N / 2][0]) / (2.0); return 0;} // Driver Code public static void main (String[] args) { int a[][]= {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; int n = a.length; System.out.println(\"Mean : \" + findMean(a, n)); System.out.println(\"Median : \" + findMedian(a, n)); } } // This code is contributed by KRV.",
"e": 29240,
"s": 28121,
"text": null
},
{
"code": "# Python3 program to find mean and median# of sorted square matrix.N = 4 # Returns mean of a given matrix of# size n x n.def findMean(a): summ = 0 # total sum calculation of matrix for i in range(N): for j in range(N): summ += a[i][j] return summ/(N*N) # Function for calculating mediandef findMedian(a): if (N % 2 != 0): return a[N//2][N//2] if (N % 2 == 0): return (a[(N - 2)//2][N - 1] + a[N//2][0])/2 # Driver programa = [[1, 2, 3, 4],[5, 6, 7, 8], [9, 10, 11, 12],[13, 14, 15, 16]]print(\"Mean :\", findMean(a))print(\"Median :\",findMedian(a)) # This code is contributed by shubhamsingh10",
"e": 29899,
"s": 29240,
"text": null
},
{
"code": "// C# program to find mean and median// of sorted square matrix.using System; class GFG { // Returns mean of a given // matrix of size n x n. static double findMean(int [,]a, int n) { int sum = 0; int N = n; // total sum calculation of matrix for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) sum += a[i,j]; return (double)sum / (N * N); } // Function for calculating median static double findMedian(int [,]a, int n) { int N = n; if (N % 2 != 0) return a[N / 2,N / 2]; if (N % 2 == 0) return ( a[(N - 2) / 2, (N - 1)] + a[ N / 2, 0] ) / (2.0); return 0; } // Driver Code public static void Main () { int [,]a= { { 1, 2, 3, 4}, { 5, 6, 7, 8}, { 9, 10, 11, 12}, {13, 14, 15, 16} }; int n = a.GetLength(0); Console.WriteLine(\"Mean : \" + findMean(a, n)); Console.WriteLine(\"Median : \" + findMedian(a, n)); } } // This code is contributed by Sam007.",
"e": 31160,
"s": 29899,
"text": null
},
{
"code": "<?php// PHP program to find// mean and median// of sorted square// matrix. $N = 4; // Returns mean of// a given matrix of// size n x n.function findMean($a){ global $N; $sum = 0; // total sum calculation // of matrix for ($i = 0; $i < $N; $i++) for ($j = 0; $j < $N; $j++) $sum += $a[$i][$j]; return (double)$sum / ($N * $N);} // Function for calculating medianfunction findMedian($a){ global $N; if ($N % 2 != 0) return $a[$N / 2][$N / 2]; if ($N % 2 == 0) return ($a[($N - 2) / 2][$N - 1] + $a[$N / 2][0]) / 2.0;} // Driver Code $a= array(array(1, 2, 3, 4), array(5, 6, 7, 8), array(9, 10, 11, 12), array(13, 14, 15, 16)); echo \"Mean : \" , findMean($a),\"\\n\", \"Median : \", findMedian($a); // This code is contributed by vt_m.?>",
"e": 32020,
"s": 31160,
"text": null
},
{
"code": "<script> // Javascriptprogram to find mean and median// of sorted square matrix. // Returns mean of a given// matrix of size n x n.function findMean(a, n){ var sum = 0; var N = n; // Total sum calculation of matrix for(var i = 0; i < N; i++) for(var j = 0; j < N; j++) sum += a[i][j]; return sum / (N * N);} // Function for calculating medianfunction findMedian(a, n){ var N = n; if (N % 2 != 0) return a[N / 2][N / 2]; if (N % 2 == 0) return (a[(N - 2) / 2][ N - 1] + a[N / 2][0]) / (2.0); return 0;} // Driver Codevar a = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ]; var n = a.length;document.write(\"Mean : \" + findMean(a, n) + \"<br>\");document.write(\"Median : \" + findMedian(a, n) + \"<br>\"); // This code is contributed by Kirti </script>",
"e": 32943,
"s": 32020,
"text": null
},
{
"code": null,
"e": 32952,
"s": 32943,
"text": "Output: "
},
{
"code": null,
"e": 32976,
"s": 32952,
"text": "Mean : 8.5\nMedian : 8.5"
},
{
"code": null,
"e": 33404,
"s": 32976,
"text": "This article is contributed by Himanshu Ranjan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 33408,
"s": 33404,
"text": "KRV"
},
{
"code": null,
"e": 33413,
"s": 33408,
"text": "vt_m"
},
{
"code": null,
"e": 33420,
"s": 33413,
"text": "Sam007"
},
{
"code": null,
"e": 33435,
"s": 33420,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 33448,
"s": 33435,
"text": "Kirti_Mangal"
},
{
"code": null,
"e": 33459,
"s": 33448,
"text": "maths-mean"
},
{
"code": null,
"e": 33474,
"s": 33459,
"text": "median-finding"
},
{
"code": null,
"e": 33491,
"s": 33474,
"text": "Order-Statistics"
},
{
"code": null,
"e": 33514,
"s": 33491,
"text": "statistical-algorithms"
},
{
"code": null,
"e": 33521,
"s": 33514,
"text": "Matrix"
},
{
"code": null,
"e": 33528,
"s": 33521,
"text": "Matrix"
},
{
"code": null,
"e": 33626,
"s": 33528,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33669,
"s": 33626,
"text": "Maximum size square sub-matrix with all 1s"
},
{
"code": null,
"e": 33693,
"s": 33669,
"text": "Sudoku | Backtracking-7"
},
{
"code": null,
"e": 33764,
"s": 33693,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 33817,
"s": 33764,
"text": "Maximum size rectangle binary sub-matrix with all 1s"
},
{
"code": null,
"e": 33868,
"s": 33817,
"text": "Inplace rotate square matrix by 90 degrees | Set 1"
},
{
"code": null,
"e": 33889,
"s": 33868,
"text": "Min Cost Path | DP-6"
},
{
"code": null,
"e": 33931,
"s": 33889,
"text": "Printing all solutions in N-Queen Problem"
},
{
"code": null,
"e": 34013,
"s": 33931,
"text": "Rotate a matrix by 90 degree in clockwise direction without using any extra space"
},
{
"code": null,
"e": 34035,
"s": 34013,
"text": "The Celebrity Problem"
}
] |
ISRO | ISRO CS 2013 | Question 39 - GeeksforGeeks
|
08 May, 2018
If the frame to be transmitted is 1101011011 and the CRC polynomial to be used for generating checksum is x4+ x + 1, then what is the transmitted frame?(A) 11010110111011(B) 11010110111101(C) 11010110111110(D) 11010110111001Answer: (C)Explanation:
Step-1:
Append (number of bits in divisor - 1) number
of zeroes at the end of data unit
Data unit = 1101011011, Divisor = 10011,
So, append 4 zeroes at the end.
= 11010110110000
Step 2
Divide using xor subtraction:
_________________
10111) 11010110110000 ( 101000001
10111
------
10011
10011
-------
10110
10011
--------
10100
10011
--------
1110
Step 3
Perform Xor-sum of the remainder with the appended
zeroes in data unit.
= 11010110110000 xor (1100)
= 11010110111110
So, option (C) is correct.Quiz of this Question
ISRO
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ISRO | ISRO CS 2016 | Question 29
ISRO | ISRO CS 2017 - May | Question 17
ISRO | ISRO CS 2017 | Question 54
ISRO | ISRO CS 2007 | Question 55
ISRO | ISRO CS 2017 - May | Question 40
ISRO | ISRO CS 2007 | Question 80
ISRO | ISRO CS 2017 - May | Question 13
ISRO | ISRO CS 2013 | Question 54
ISRO | ISRO CS 2013 | Question 51
ISRO | ISRO CS 2016 | Question 49
|
[
{
"code": null,
"e": 25673,
"s": 25645,
"text": "\n08 May, 2018"
},
{
"code": null,
"e": 25921,
"s": 25673,
"text": "If the frame to be transmitted is 1101011011 and the CRC polynomial to be used for generating checksum is x4+ x + 1, then what is the transmitted frame?(A) 11010110111011(B) 11010110111101(C) 11010110111110(D) 11010110111001Answer: (C)Explanation:"
},
{
"code": null,
"e": 26564,
"s": 25921,
"text": "Step-1: \nAppend (number of bits in divisor - 1) number\nof zeroes at the end of data unit\nData unit = 1101011011, Divisor = 10011,\nSo, append 4 zeroes at the end.\n = 11010110110000\n\nStep 2\nDivide using xor subtraction: \n _________________\n10111) 11010110110000 ( 101000001\n 10111\n ------\n 10011\n 10011\n -------\n 10110\n 10011\n --------\n 10100\n 10011\n --------\n 1110\n\n\nStep 3\nPerform Xor-sum of the remainder with the appended\nzeroes in data unit.\n= 11010110110000 xor (1100)\n= 11010110111110 "
},
{
"code": null,
"e": 26612,
"s": 26564,
"text": "So, option (C) is correct.Quiz of this Question"
},
{
"code": null,
"e": 26617,
"s": 26612,
"text": "ISRO"
},
{
"code": null,
"e": 26715,
"s": 26617,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26749,
"s": 26715,
"text": "ISRO | ISRO CS 2016 | Question 29"
},
{
"code": null,
"e": 26789,
"s": 26749,
"text": "ISRO | ISRO CS 2017 - May | Question 17"
},
{
"code": null,
"e": 26823,
"s": 26789,
"text": "ISRO | ISRO CS 2017 | Question 54"
},
{
"code": null,
"e": 26857,
"s": 26823,
"text": "ISRO | ISRO CS 2007 | Question 55"
},
{
"code": null,
"e": 26897,
"s": 26857,
"text": "ISRO | ISRO CS 2017 - May | Question 40"
},
{
"code": null,
"e": 26931,
"s": 26897,
"text": "ISRO | ISRO CS 2007 | Question 80"
},
{
"code": null,
"e": 26971,
"s": 26931,
"text": "ISRO | ISRO CS 2017 - May | Question 13"
},
{
"code": null,
"e": 27005,
"s": 26971,
"text": "ISRO | ISRO CS 2013 | Question 54"
},
{
"code": null,
"e": 27039,
"s": 27005,
"text": "ISRO | ISRO CS 2013 | Question 51"
}
] |
PostgreSQL - Function Parameter Modes - GeeksforGeeks
|
26 Jan, 2021
While using procedures and functions, PostgreSQL allows us to pass data from the calling program to the procedure or function and to receive data back from the procedure or function. This functionality is achieved using Parameters.
Parameters declared in the function definition are known as Formal parameters. When the procedure or function is invoked, the calling program supplies the data that is to be used in the called program’s processing as well as the variables that receive the results of the processing from the called program. The data and variables supplied by the calling program when the procedure or function are known as Actual parameters.
A Parameter mode is used to decide the behavior of the parameters. PL/pgSQL supports three parameter modes: in, out, and inout. By default, a parameter uses the IN mode.
The IN mode is used to pass a value to the function. IN parameters simply act like constants. The IN parameters cannot be assigned any value. The IN mode is the default mode which is assigned if not specified explicitly.
The OUT parameters are declared as a part of the argument list and are returned as a part of the result. The OUT parameters are very useful in functions that require returning multiple values. They act like uninitialized variables.Unlike the IN parameters, a value must be assigned to the OUT parameters.
The INOUT mode is simply a combination of both IN and OUT modes. In the INOUT Mode, the caller passes an argument to the procedure or function. During the function processing, the value of the argument changes, and the same value is returned by the function. Thus, the INOUT parameters act like initialized variables, and they should be assigned a value during function processing.
The following table illustrates the three parameter mode:
For testing, we create a sample table using the below commands to perform examples:
CREATE TABLE employees (
employee_id serial PRIMARY KEY,
full_name VARCHAR NOT NULL,
manager_id INT
);
Then we insert data into our employee table as follows:
INSERT INTO employees (
employee_id,
full_name,
manager_id
)
VALUES
(1, 'M.S Dhoni', NULL),
(2, 'Sachin Tendulkar', 1),
(3, 'R. Sharma', 1),
(4, 'S. Raina', 1),
(5, 'B. Kumar', 1),
(6, 'Y. Singh', 2),
(7, 'Virender Sehwag ', 2),
(8, 'Ajinkya Rahane', 2),
(9, 'Shikhar Dhawan', 2),
(10, 'Mohammed Shami', 3),
(11, 'Shreyas Iyer', 3),
(12, 'Mayank Agarwal', 3),
(13, 'K. L. Rahul', 3),
(14, 'Hardik Pandya', 4),
(15, 'Dinesh Karthik', 4),
(16, 'Jasprit Bumrah', 7),
(17, 'Kuldeep Yadav', 7),
(18, 'Yuzvendra Chahal', 8),
(19, 'Rishabh Pant', 8),
(20, 'Sanju Samson', 8);
The table is:
Example 1:
The following function is created to find the name of the employee along with its manager id given the employee id and its manager id.
create or replace function get_stats(
in eid int,
out name varchar,
inout mid int)
language plpgsql
as $$
begin
select full_name,manager_id
into name,mid
from employees
where manager_id=mid
and
employee_id=eid;
end; $$;
To call this function, we need to provide employee id and then manager id. As an example,
select * from get_stats(2,1);
Output:
In this example, we have taken the employee name as OUT as we need to output the name, employee id as IN as it is only required as input, and manager id as INOUT as it is both required as an input as well as an output.
Example 2:
The following function is used to get the count of employees in the employee table.
create or replace function empcount(
out ecount int)
language plpgsql
as $$
begin
select count(*)
into ecount
from employees;
end; $$;
To call this function :
select * from empcount();
Output:
Example 3:
The following function is used to swap the contents of 2 variables
create or replace function swapper(
inout x int,
inout y int)
language plpgsql
as $$
begin
select x,y into y,x;
end; $$;
To call this function :
select * from swapper(198,457);
Output:
As we need to change the values and then display the changed values, we use INOUT mode.
Picked
PostgreSQL-function
Technical Scripter 2020
PostgreSQL
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - CREATE PROCEDURE
PostgreSQL - GROUP BY clause
PostgreSQL - DROP INDEX
PostgreSQL - TIME Data Type
PostgreSQL - REPLACE Function
PostgreSQL - CREATE SCHEMA
PostgreSQL - SELECT
PostgreSQL - ROW_NUMBER Function
PostgreSQL - Cursor
PostgreSQL - LEFT JOIN
|
[
{
"code": null,
"e": 25367,
"s": 25339,
"text": "\n26 Jan, 2021"
},
{
"code": null,
"e": 25599,
"s": 25367,
"text": "While using procedures and functions, PostgreSQL allows us to pass data from the calling program to the procedure or function and to receive data back from the procedure or function. This functionality is achieved using Parameters."
},
{
"code": null,
"e": 26024,
"s": 25599,
"text": "Parameters declared in the function definition are known as Formal parameters. When the procedure or function is invoked, the calling program supplies the data that is to be used in the called program’s processing as well as the variables that receive the results of the processing from the called program. The data and variables supplied by the calling program when the procedure or function are known as Actual parameters."
},
{
"code": null,
"e": 26195,
"s": 26024,
"text": "A Parameter mode is used to decide the behavior of the parameters. PL/pgSQL supports three parameter modes: in, out, and inout. By default, a parameter uses the IN mode. "
},
{
"code": null,
"e": 26416,
"s": 26195,
"text": "The IN mode is used to pass a value to the function. IN parameters simply act like constants. The IN parameters cannot be assigned any value. The IN mode is the default mode which is assigned if not specified explicitly."
},
{
"code": null,
"e": 26721,
"s": 26416,
"text": "The OUT parameters are declared as a part of the argument list and are returned as a part of the result. The OUT parameters are very useful in functions that require returning multiple values. They act like uninitialized variables.Unlike the IN parameters, a value must be assigned to the OUT parameters."
},
{
"code": null,
"e": 27103,
"s": 26721,
"text": "The INOUT mode is simply a combination of both IN and OUT modes. In the INOUT Mode, the caller passes an argument to the procedure or function. During the function processing, the value of the argument changes, and the same value is returned by the function. Thus, the INOUT parameters act like initialized variables, and they should be assigned a value during function processing."
},
{
"code": null,
"e": 27161,
"s": 27103,
"text": "The following table illustrates the three parameter mode:"
},
{
"code": null,
"e": 27245,
"s": 27161,
"text": "For testing, we create a sample table using the below commands to perform examples:"
},
{
"code": null,
"e": 27361,
"s": 27245,
"text": "CREATE TABLE employees (\n\n employee_id serial PRIMARY KEY,\n\n full_name VARCHAR NOT NULL,\n\n manager_id INT\n\n);"
},
{
"code": null,
"e": 27417,
"s": 27361,
"text": "Then we insert data into our employee table as follows:"
},
{
"code": null,
"e": 28055,
"s": 27417,
"text": "INSERT INTO employees (\n employee_id,\n full_name,\n manager_id\n)\nVALUES\n (1, 'M.S Dhoni', NULL),\n (2, 'Sachin Tendulkar', 1),\n (3, 'R. Sharma', 1),\n (4, 'S. Raina', 1),\n (5, 'B. Kumar', 1),\n (6, 'Y. Singh', 2),\n (7, 'Virender Sehwag ', 2),\n (8, 'Ajinkya Rahane', 2),\n (9, 'Shikhar Dhawan', 2),\n (10, 'Mohammed Shami', 3),\n (11, 'Shreyas Iyer', 3),\n (12, 'Mayank Agarwal', 3),\n (13, 'K. L. Rahul', 3),\n (14, 'Hardik Pandya', 4),\n (15, 'Dinesh Karthik', 4),\n (16, 'Jasprit Bumrah', 7),\n (17, 'Kuldeep Yadav', 7),\n (18, 'Yuzvendra Chahal', 8),\n (19, 'Rishabh Pant', 8),\n (20, 'Sanju Samson', 8);"
},
{
"code": null,
"e": 28069,
"s": 28055,
"text": "The table is:"
},
{
"code": null,
"e": 28080,
"s": 28069,
"text": "Example 1:"
},
{
"code": null,
"e": 28216,
"s": 28080,
"text": "The following function is created to find the name of the employee along with its manager id given the employee id and its manager id. "
},
{
"code": null,
"e": 28454,
"s": 28216,
"text": "create or replace function get_stats(\n in eid int,\n out name varchar,\n inout mid int)\nlanguage plpgsql\nas $$\nbegin\n select full_name,manager_id\n into name,mid\n from employees\n where manager_id=mid\n and\n employee_id=eid;\nend; $$;"
},
{
"code": null,
"e": 28544,
"s": 28454,
"text": "To call this function, we need to provide employee id and then manager id. As an example,"
},
{
"code": null,
"e": 28574,
"s": 28544,
"text": "select * from get_stats(2,1);"
},
{
"code": null,
"e": 28582,
"s": 28574,
"text": "Output:"
},
{
"code": null,
"e": 28802,
"s": 28582,
"text": "In this example, we have taken the employee name as OUT as we need to output the name, employee id as IN as it is only required as input, and manager id as INOUT as it is both required as an input as well as an output. "
},
{
"code": null,
"e": 28813,
"s": 28802,
"text": "Example 2:"
},
{
"code": null,
"e": 28897,
"s": 28813,
"text": "The following function is used to get the count of employees in the employee table."
},
{
"code": null,
"e": 29040,
"s": 28897,
"text": "create or replace function empcount(\n out ecount int)\nlanguage plpgsql\nas $$\nbegin\n select count(*)\n into ecount\n from employees;\nend; $$;"
},
{
"code": null,
"e": 29064,
"s": 29040,
"text": "To call this function :"
},
{
"code": null,
"e": 29090,
"s": 29064,
"text": "select * from empcount();"
},
{
"code": null,
"e": 29098,
"s": 29090,
"text": "Output:"
},
{
"code": null,
"e": 29109,
"s": 29098,
"text": "Example 3:"
},
{
"code": null,
"e": 29176,
"s": 29109,
"text": "The following function is used to swap the contents of 2 variables"
},
{
"code": null,
"e": 29303,
"s": 29176,
"text": "create or replace function swapper(\n inout x int,\n inout y int)\nlanguage plpgsql\nas $$\nbegin\n select x,y into y,x;\nend; $$;"
},
{
"code": null,
"e": 29327,
"s": 29303,
"text": "To call this function :"
},
{
"code": null,
"e": 29359,
"s": 29327,
"text": "select * from swapper(198,457);"
},
{
"code": null,
"e": 29367,
"s": 29359,
"text": "Output:"
},
{
"code": null,
"e": 29455,
"s": 29367,
"text": "As we need to change the values and then display the changed values, we use INOUT mode."
},
{
"code": null,
"e": 29462,
"s": 29455,
"text": "Picked"
},
{
"code": null,
"e": 29482,
"s": 29462,
"text": "PostgreSQL-function"
},
{
"code": null,
"e": 29506,
"s": 29482,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 29517,
"s": 29506,
"text": "PostgreSQL"
},
{
"code": null,
"e": 29536,
"s": 29517,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29634,
"s": 29536,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29664,
"s": 29634,
"text": "PostgreSQL - CREATE PROCEDURE"
},
{
"code": null,
"e": 29693,
"s": 29664,
"text": "PostgreSQL - GROUP BY clause"
},
{
"code": null,
"e": 29717,
"s": 29693,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 29745,
"s": 29717,
"text": "PostgreSQL - TIME Data Type"
},
{
"code": null,
"e": 29775,
"s": 29745,
"text": "PostgreSQL - REPLACE Function"
},
{
"code": null,
"e": 29802,
"s": 29775,
"text": "PostgreSQL - CREATE SCHEMA"
},
{
"code": null,
"e": 29822,
"s": 29802,
"text": "PostgreSQL - SELECT"
},
{
"code": null,
"e": 29855,
"s": 29822,
"text": "PostgreSQL - ROW_NUMBER Function"
},
{
"code": null,
"e": 29875,
"s": 29855,
"text": "PostgreSQL - Cursor"
}
] |
Convert a normal BST to Balanced BST - GeeksforGeeks
|
23 Aug, 2021
Given a BST (Binary Search Tree) that may be unbalanced, convert it into a balanced BST that has minimum possible height.Examples :
Input:
30
/
20
/
10
Output:
20
/ \
10 30
Input:
4
/
3
/
2
/
1
Output:
3 3 2
/ \ / \ / \
1 4 OR 2 4 OR 1 3 OR ..
\ / \
2 1 4
Input:
4
/ \
3 5
/ \
2 6
/ \
1 7
Output:
4
/ \
2 6
/ \ / \
1 3 5 7
A Simple Solution is to traverse nodes in Inorder and one by one insert into a self-balancing BST like AVL tree. Time complexity of this solution is O(n Log n) and this solution doesn’t guarantee An Efficient Solution can construct balanced BST in O(n) time with minimum possible height. Below are steps.
Traverse given BST in inorder and store result in an array. This step takes O(n) time. Note that this array would be sorted as inorder traversal of BST always produces sorted sequence.Build a balanced BST from the above created sorted array using the recursive approach discussed here. This step also takes O(n) time as we traverse every element exactly once and processing an element takes O(1) time.
Traverse given BST in inorder and store result in an array. This step takes O(n) time. Note that this array would be sorted as inorder traversal of BST always produces sorted sequence.
Build a balanced BST from the above created sorted array using the recursive approach discussed here. This step also takes O(n) time as we traverse every element exactly once and processing an element takes O(1) time.
Below is the implementation of above steps.
C++
Java
Python3
C#
Javascript
// C++ program to convert a left unbalanced BST to// a balanced BST#include <bits/stdc++.h>using namespace std; struct Node{ int data; Node* left, *right;}; /* This function traverse the skewed binary tree and stores its nodes pointers in vector nodes[] */void storeBSTNodes(Node* root, vector<Node*> &nodes){ // Base case if (root==NULL) return; // Store nodes in Inorder (which is sorted // order for BST) storeBSTNodes(root->left, nodes); nodes.push_back(root); storeBSTNodes(root->right, nodes);} /* Recursive function to construct binary tree */Node* buildTreeUtil(vector<Node*> &nodes, int start, int end){ // base case if (start > end) return NULL; /* Get the middle element and make it root */ int mid = (start + end)/2; Node *root = nodes[mid]; /* Using index in Inorder traversal, construct left and right subtress */ root->left = buildTreeUtil(nodes, start, mid-1); root->right = buildTreeUtil(nodes, mid+1, end); return root;} // This functions converts an unbalanced BST to// a balanced BSTNode* buildTree(Node* root){ // Store nodes of given BST in sorted order vector<Node *> nodes; storeBSTNodes(root, nodes); // Constructs BST from nodes[] int n = nodes.size(); return buildTreeUtil(nodes, 0, n-1);} // Utility function to create a new nodeNode* newNode(int data){ Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node);} /* Function to do preorder traversal of tree */void preOrder(Node* node){ if (node == NULL) return; printf("%d ", node->data); preOrder(node->left); preOrder(node->right);} // Driver programint main(){ /* Constructed skewed binary tree is 10 / 8 / 7 / 6 / 5 */ Node* root = newNode(10); root->left = newNode(8); root->left->left = newNode(7); root->left->left->left = newNode(6); root->left->left->left->left = newNode(5); root = buildTree(root); printf("Preorder traversal of balanced " "BST is : \n"); preOrder(root); return 0;}
// Java program to convert a left unbalanced BST to a balanced BST import java.util.*; /* A binary tree node has data, pointer to left child and a pointer to right child */class Node{ int data; Node left, right; public Node(int data) { this.data = data; left = right = null; }} class BinaryTree{ Node root; /* This function traverse the skewed binary tree and stores its nodes pointers in vector nodes[] */ void storeBSTNodes(Node root, Vector<Node> nodes) { // Base case if (root == null) return; // Store nodes in Inorder (which is sorted // order for BST) storeBSTNodes(root.left, nodes); nodes.add(root); storeBSTNodes(root.right, nodes); } /* Recursive function to construct binary tree */ Node buildTreeUtil(Vector<Node> nodes, int start, int end) { // base case if (start > end) return null; /* Get the middle element and make it root */ int mid = (start + end) / 2; Node node = nodes.get(mid); /* Using index in Inorder traversal, construct left and right subtress */ node.left = buildTreeUtil(nodes, start, mid - 1); node.right = buildTreeUtil(nodes, mid + 1, end); return node; } // This functions converts an unbalanced BST to // a balanced BST Node buildTree(Node root) { // Store nodes of given BST in sorted order Vector<Node> nodes = new Vector<Node>(); storeBSTNodes(root, nodes); // Constructs BST from nodes[] int n = nodes.size(); return buildTreeUtil(nodes, 0, n - 1); } /* Function to do preorder traversal of tree */ void preOrder(Node node) { if (node == null) return; System.out.print(node.data + " "); preOrder(node.left); preOrder(node.right); } // Driver program to test the above functions public static void main(String[] args) { /* Constructed skewed binary tree is 10 / 8 / 7 / 6 / 5 */ BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(8); tree.root.left.left = new Node(7); tree.root.left.left.left = new Node(6); tree.root.left.left.left.left = new Node(5); tree.root = tree.buildTree(tree.root); System.out.println("Preorder traversal of balanced BST is :"); tree.preOrder(tree.root); }} // This code has been contributed by Mayank Jaiswal(mayank_24)
# Python3 program to convert a left# unbalanced BST to a balanced BSTimport sysimport math # A binary tree node has data, pointer to left child# and a pointer to right childclass Node: def __init__(self,data): self.data=data self.left=None self.right=None # This function traverse the skewed binary tree and# stores its nodes pointers in vector nodes[]def storeBSTNodes(root,nodes): # Base case if not root: return # Store nodes in Inorder (which is sorted # order for BST) storeBSTNodes(root.left,nodes) nodes.append(root) storeBSTNodes(root.right,nodes) # Recursive function to construct binary treedef buildTreeUtil(nodes,start,end): # base case if start>end: return None # Get the middle element and make it root mid=(start+end)//2 node=nodes[mid] # Using index in Inorder traversal, construct # left and right subtress node.left=buildTreeUtil(nodes,start,mid-1) node.right=buildTreeUtil(nodes,mid+1,end) return node # This functions converts an unbalanced BST to# a balanced BSTdef buildTree(root): # Store nodes of given BST in sorted order nodes=[] storeBSTNodes(root,nodes) # Constructs BST from nodes[] n=len(nodes) return buildTreeUtil(nodes,0,n-1) # Function to do preorder traversal of treedef preOrder(root): if not root: return print("{} ".format(root.data),end="") preOrder(root.left) preOrder(root.right) # Driver codeif __name__=='__main__': # Constructed skewed binary tree is # 10 # / # 8 # / # 7 # / # 6 # / # 5 root = Node(10) root.left = Node(8) root.left.left = Node(7) root.left.left.left = Node(6) root.left.left.left.left = Node(5) root = buildTree(root) print("Preorder traversal of balanced BST is :") preOrder(root) # This code has been contributed by Vikash Kumar 37
using System;using System.Collections.Generic; // C# program to convert a left unbalanced BST to a balanced BST /* A binary tree node has data, pointer to left child and a pointer to right child */public class Node{ public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; }} public class BinaryTree{ public Node root; /* This function traverse the skewed binary tree and stores its nodes pointers in vector nodes[] */ public virtual void storeBSTNodes(Node root, List<Node> nodes) { // Base case if (root == null) { return; } // Store nodes in Inorder (which is sorted // order for BST) storeBSTNodes(root.left, nodes); nodes.Add(root); storeBSTNodes(root.right, nodes); } /* Recursive function to construct binary tree */ public virtual Node buildTreeUtil(List<Node> nodes, int start, int end) { // base case if (start > end) { return null; } /* Get the middle element and make it root */ int mid = (start + end) / 2; Node node = nodes[mid]; /* Using index in Inorder traversal, construct left and right subtress */ node.left = buildTreeUtil(nodes, start, mid - 1); node.right = buildTreeUtil(nodes, mid + 1, end); return node; } // This functions converts an unbalanced BST to // a balanced BST public virtual Node buildTree(Node root) { // Store nodes of given BST in sorted order List<Node> nodes = new List<Node>(); storeBSTNodes(root, nodes); // Constructs BST from nodes[] int n = nodes.Count; return buildTreeUtil(nodes, 0, n - 1); } /* Function to do preorder traversal of tree */ public virtual void preOrder(Node node) { if (node == null) { return; } Console.Write(node.data + " "); preOrder(node.left); preOrder(node.right); } // Driver program to test the above functions public static void Main(string[] args) { /* Constructed skewed binary tree is 10 / 8 / 7 / 6 / 5 */ BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(8); tree.root.left.left = new Node(7); tree.root.left.left.left = new Node(6); tree.root.left.left.left.left = new Node(5); tree.root = tree.buildTree(tree.root); Console.WriteLine("Preorder traversal of balanced BST is :"); tree.preOrder(tree.root); }} // This code is contributed by Shrikant13
<script> // JavaScript program to convert a left // unbalanced BST to a balanced BST class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } let root; /* This function traverse the skewed binary tree and stores its nodes pointers in vector nodes[] */ function storeBSTNodes(root, nodes) { // Base case if (root == null) return; // Store nodes in Inorder (which is sorted // order for BST) storeBSTNodes(root.left, nodes); nodes.push(root); storeBSTNodes(root.right, nodes); } /* Recursive function to construct binary tree */ function buildTreeUtil(nodes, start, end) { // base case if (start > end) return null; /* Get the middle element and make it root */ let mid = parseInt((start + end) / 2, 10); let node = nodes[mid]; /* Using index in Inorder traversal, construct left and right subtress */ node.left = buildTreeUtil(nodes, start, mid - 1); node.right = buildTreeUtil(nodes, mid + 1, end); return node; } // This functions converts an unbalanced BST to // a balanced BST function buildTree(root) { // Store nodes of given BST in sorted order let nodes = []; storeBSTNodes(root, nodes); // Constructs BST from nodes[] let n = nodes.length; return buildTreeUtil(nodes, 0, n - 1); } /* Function to do preorder traversal of tree */ function preOrder(node) { if (node == null) return; document.write(node.data + " "); preOrder(node.left); preOrder(node.right); } /* Constructed skewed binary tree is 10 / 8 / 7 / 6 / 5 */ root = new Node(10); root.left = new Node(8); root.left.left = new Node(7); root.left.left.left = new Node(6); root.left.left.left.left = new Node(5); root = buildTree(root); document.write("Preorder traversal of balanced BST is :" + "</br>"); preOrder(root); </script>
Output :
Preorder traversal of balanced BST is :
7 5 6 8 10
YouTubeGeeksforGeeks507K subscribersConvert a normal BST to Balanced BST | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:36•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=ElUqyFsddvo" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed Aditya Goel. If you likeGeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
shrikanth13
Vikash Kumar 37
suresh07
clintra
Binary Search Tree
Tree
Binary Search Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Advantages of BST over Hash Table
Difference between Binary Tree and Binary Search Tree
Binary Tree to Binary Search Tree Conversion
Merge Two Balanced Binary Search Trees
set vs unordered_set in C++ STL
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
Binary Tree | Set 3 (Types of Binary Tree)
Inorder Tree Traversal without Recursion
|
[
{
"code": null,
"e": 26243,
"s": 26215,
"text": "\n23 Aug, 2021"
},
{
"code": null,
"e": 26376,
"s": 26243,
"text": "Given a BST (Binary Search Tree) that may be unbalanced, convert it into a balanced BST that has minimum possible height.Examples : "
},
{
"code": null,
"e": 26906,
"s": 26376,
"text": "Input:\n 30\n /\n 20\n /\n 10\nOutput:\n 20\n / \\\n 10 30\n\n\nInput:\n 4\n /\n 3\n /\n 2\n /\n 1\nOutput:\n 3 3 2\n / \\ / \\ / \\\n 1 4 OR 2 4 OR 1 3 OR ..\n \\ / \\\n 2 1 4 \n\nInput:\n 4\n / \\\n 3 5\n / \\\n 2 6 \n / \\\n 1 7\nOutput:\n 4\n / \\\n 2 6\n / \\ / \\\n1 3 5 7 "
},
{
"code": null,
"e": 27215,
"s": 26908,
"text": "A Simple Solution is to traverse nodes in Inorder and one by one insert into a self-balancing BST like AVL tree. Time complexity of this solution is O(n Log n) and this solution doesn’t guarantee An Efficient Solution can construct balanced BST in O(n) time with minimum possible height. Below are steps. "
},
{
"code": null,
"e": 27617,
"s": 27215,
"text": "Traverse given BST in inorder and store result in an array. This step takes O(n) time. Note that this array would be sorted as inorder traversal of BST always produces sorted sequence.Build a balanced BST from the above created sorted array using the recursive approach discussed here. This step also takes O(n) time as we traverse every element exactly once and processing an element takes O(1) time."
},
{
"code": null,
"e": 27802,
"s": 27617,
"text": "Traverse given BST in inorder and store result in an array. This step takes O(n) time. Note that this array would be sorted as inorder traversal of BST always produces sorted sequence."
},
{
"code": null,
"e": 28020,
"s": 27802,
"text": "Build a balanced BST from the above created sorted array using the recursive approach discussed here. This step also takes O(n) time as we traverse every element exactly once and processing an element takes O(1) time."
},
{
"code": null,
"e": 28066,
"s": 28020,
"text": "Below is the implementation of above steps. "
},
{
"code": null,
"e": 28070,
"s": 28066,
"text": "C++"
},
{
"code": null,
"e": 28075,
"s": 28070,
"text": "Java"
},
{
"code": null,
"e": 28083,
"s": 28075,
"text": "Python3"
},
{
"code": null,
"e": 28086,
"s": 28083,
"text": "C#"
},
{
"code": null,
"e": 28097,
"s": 28086,
"text": "Javascript"
},
{
"code": "// C++ program to convert a left unbalanced BST to// a balanced BST#include <bits/stdc++.h>using namespace std; struct Node{ int data; Node* left, *right;}; /* This function traverse the skewed binary tree and stores its nodes pointers in vector nodes[] */void storeBSTNodes(Node* root, vector<Node*> &nodes){ // Base case if (root==NULL) return; // Store nodes in Inorder (which is sorted // order for BST) storeBSTNodes(root->left, nodes); nodes.push_back(root); storeBSTNodes(root->right, nodes);} /* Recursive function to construct binary tree */Node* buildTreeUtil(vector<Node*> &nodes, int start, int end){ // base case if (start > end) return NULL; /* Get the middle element and make it root */ int mid = (start + end)/2; Node *root = nodes[mid]; /* Using index in Inorder traversal, construct left and right subtress */ root->left = buildTreeUtil(nodes, start, mid-1); root->right = buildTreeUtil(nodes, mid+1, end); return root;} // This functions converts an unbalanced BST to// a balanced BSTNode* buildTree(Node* root){ // Store nodes of given BST in sorted order vector<Node *> nodes; storeBSTNodes(root, nodes); // Constructs BST from nodes[] int n = nodes.size(); return buildTreeUtil(nodes, 0, n-1);} // Utility function to create a new nodeNode* newNode(int data){ Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node);} /* Function to do preorder traversal of tree */void preOrder(Node* node){ if (node == NULL) return; printf(\"%d \", node->data); preOrder(node->left); preOrder(node->right);} // Driver programint main(){ /* Constructed skewed binary tree is 10 / 8 / 7 / 6 / 5 */ Node* root = newNode(10); root->left = newNode(8); root->left->left = newNode(7); root->left->left->left = newNode(6); root->left->left->left->left = newNode(5); root = buildTree(root); printf(\"Preorder traversal of balanced \" \"BST is : \\n\"); preOrder(root); return 0;}",
"e": 30297,
"s": 28097,
"text": null
},
{
"code": "// Java program to convert a left unbalanced BST to a balanced BST import java.util.*; /* A binary tree node has data, pointer to left child and a pointer to right child */class Node{ int data; Node left, right; public Node(int data) { this.data = data; left = right = null; }} class BinaryTree{ Node root; /* This function traverse the skewed binary tree and stores its nodes pointers in vector nodes[] */ void storeBSTNodes(Node root, Vector<Node> nodes) { // Base case if (root == null) return; // Store nodes in Inorder (which is sorted // order for BST) storeBSTNodes(root.left, nodes); nodes.add(root); storeBSTNodes(root.right, nodes); } /* Recursive function to construct binary tree */ Node buildTreeUtil(Vector<Node> nodes, int start, int end) { // base case if (start > end) return null; /* Get the middle element and make it root */ int mid = (start + end) / 2; Node node = nodes.get(mid); /* Using index in Inorder traversal, construct left and right subtress */ node.left = buildTreeUtil(nodes, start, mid - 1); node.right = buildTreeUtil(nodes, mid + 1, end); return node; } // This functions converts an unbalanced BST to // a balanced BST Node buildTree(Node root) { // Store nodes of given BST in sorted order Vector<Node> nodes = new Vector<Node>(); storeBSTNodes(root, nodes); // Constructs BST from nodes[] int n = nodes.size(); return buildTreeUtil(nodes, 0, n - 1); } /* Function to do preorder traversal of tree */ void preOrder(Node node) { if (node == null) return; System.out.print(node.data + \" \"); preOrder(node.left); preOrder(node.right); } // Driver program to test the above functions public static void main(String[] args) { /* Constructed skewed binary tree is 10 / 8 / 7 / 6 / 5 */ BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(8); tree.root.left.left = new Node(7); tree.root.left.left.left = new Node(6); tree.root.left.left.left.left = new Node(5); tree.root = tree.buildTree(tree.root); System.out.println(\"Preorder traversal of balanced BST is :\"); tree.preOrder(tree.root); }} // This code has been contributed by Mayank Jaiswal(mayank_24)",
"e": 32944,
"s": 30297,
"text": null
},
{
"code": "# Python3 program to convert a left# unbalanced BST to a balanced BSTimport sysimport math # A binary tree node has data, pointer to left child# and a pointer to right childclass Node: def __init__(self,data): self.data=data self.left=None self.right=None # This function traverse the skewed binary tree and# stores its nodes pointers in vector nodes[]def storeBSTNodes(root,nodes): # Base case if not root: return # Store nodes in Inorder (which is sorted # order for BST) storeBSTNodes(root.left,nodes) nodes.append(root) storeBSTNodes(root.right,nodes) # Recursive function to construct binary treedef buildTreeUtil(nodes,start,end): # base case if start>end: return None # Get the middle element and make it root mid=(start+end)//2 node=nodes[mid] # Using index in Inorder traversal, construct # left and right subtress node.left=buildTreeUtil(nodes,start,mid-1) node.right=buildTreeUtil(nodes,mid+1,end) return node # This functions converts an unbalanced BST to# a balanced BSTdef buildTree(root): # Store nodes of given BST in sorted order nodes=[] storeBSTNodes(root,nodes) # Constructs BST from nodes[] n=len(nodes) return buildTreeUtil(nodes,0,n-1) # Function to do preorder traversal of treedef preOrder(root): if not root: return print(\"{} \".format(root.data),end=\"\") preOrder(root.left) preOrder(root.right) # Driver codeif __name__=='__main__': # Constructed skewed binary tree is # 10 # / # 8 # / # 7 # / # 6 # / # 5 root = Node(10) root.left = Node(8) root.left.left = Node(7) root.left.left.left = Node(6) root.left.left.left.left = Node(5) root = buildTree(root) print(\"Preorder traversal of balanced BST is :\") preOrder(root) # This code has been contributed by Vikash Kumar 37",
"e": 34896,
"s": 32944,
"text": null
},
{
"code": "using System;using System.Collections.Generic; // C# program to convert a left unbalanced BST to a balanced BST /* A binary tree node has data, pointer to left child and a pointer to right child */public class Node{ public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; }} public class BinaryTree{ public Node root; /* This function traverse the skewed binary tree and stores its nodes pointers in vector nodes[] */ public virtual void storeBSTNodes(Node root, List<Node> nodes) { // Base case if (root == null) { return; } // Store nodes in Inorder (which is sorted // order for BST) storeBSTNodes(root.left, nodes); nodes.Add(root); storeBSTNodes(root.right, nodes); } /* Recursive function to construct binary tree */ public virtual Node buildTreeUtil(List<Node> nodes, int start, int end) { // base case if (start > end) { return null; } /* Get the middle element and make it root */ int mid = (start + end) / 2; Node node = nodes[mid]; /* Using index in Inorder traversal, construct left and right subtress */ node.left = buildTreeUtil(nodes, start, mid - 1); node.right = buildTreeUtil(nodes, mid + 1, end); return node; } // This functions converts an unbalanced BST to // a balanced BST public virtual Node buildTree(Node root) { // Store nodes of given BST in sorted order List<Node> nodes = new List<Node>(); storeBSTNodes(root, nodes); // Constructs BST from nodes[] int n = nodes.Count; return buildTreeUtil(nodes, 0, n - 1); } /* Function to do preorder traversal of tree */ public virtual void preOrder(Node node) { if (node == null) { return; } Console.Write(node.data + \" \"); preOrder(node.left); preOrder(node.right); } // Driver program to test the above functions public static void Main(string[] args) { /* Constructed skewed binary tree is 10 / 8 / 7 / 6 / 5 */ BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(8); tree.root.left.left = new Node(7); tree.root.left.left.left = new Node(6); tree.root.left.left.left.left = new Node(5); tree.root = tree.buildTree(tree.root); Console.WriteLine(\"Preorder traversal of balanced BST is :\"); tree.preOrder(tree.root); }} // This code is contributed by Shrikant13",
"e": 37671,
"s": 34896,
"text": null
},
{
"code": "<script> // JavaScript program to convert a left // unbalanced BST to a balanced BST class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } let root; /* This function traverse the skewed binary tree and stores its nodes pointers in vector nodes[] */ function storeBSTNodes(root, nodes) { // Base case if (root == null) return; // Store nodes in Inorder (which is sorted // order for BST) storeBSTNodes(root.left, nodes); nodes.push(root); storeBSTNodes(root.right, nodes); } /* Recursive function to construct binary tree */ function buildTreeUtil(nodes, start, end) { // base case if (start > end) return null; /* Get the middle element and make it root */ let mid = parseInt((start + end) / 2, 10); let node = nodes[mid]; /* Using index in Inorder traversal, construct left and right subtress */ node.left = buildTreeUtil(nodes, start, mid - 1); node.right = buildTreeUtil(nodes, mid + 1, end); return node; } // This functions converts an unbalanced BST to // a balanced BST function buildTree(root) { // Store nodes of given BST in sorted order let nodes = []; storeBSTNodes(root, nodes); // Constructs BST from nodes[] let n = nodes.length; return buildTreeUtil(nodes, 0, n - 1); } /* Function to do preorder traversal of tree */ function preOrder(node) { if (node == null) return; document.write(node.data + \" \"); preOrder(node.left); preOrder(node.right); } /* Constructed skewed binary tree is 10 / 8 / 7 / 6 / 5 */ root = new Node(10); root.left = new Node(8); root.left.left = new Node(7); root.left.left.left = new Node(6); root.left.left.left.left = new Node(5); root = buildTree(root); document.write(\"Preorder traversal of balanced BST is :\" + \"</br>\"); preOrder(root); </script>",
"e": 39940,
"s": 37671,
"text": null
},
{
"code": null,
"e": 39950,
"s": 39940,
"text": "Output : "
},
{
"code": null,
"e": 40003,
"s": 39950,
"text": "Preorder traversal of balanced BST is : \n7 5 6 8 10 "
},
{
"code": null,
"e": 40841,
"s": 40005,
"text": "YouTubeGeeksforGeeks507K subscribersConvert a normal BST to Balanced BST | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:36•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=ElUqyFsddvo\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 41227,
"s": 40841,
"text": "This article is contributed Aditya Goel. If you likeGeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 41239,
"s": 41227,
"text": "shrikanth13"
},
{
"code": null,
"e": 41255,
"s": 41239,
"text": "Vikash Kumar 37"
},
{
"code": null,
"e": 41264,
"s": 41255,
"text": "suresh07"
},
{
"code": null,
"e": 41272,
"s": 41264,
"text": "clintra"
},
{
"code": null,
"e": 41291,
"s": 41272,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 41296,
"s": 41291,
"text": "Tree"
},
{
"code": null,
"e": 41315,
"s": 41296,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 41320,
"s": 41315,
"text": "Tree"
},
{
"code": null,
"e": 41418,
"s": 41320,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41452,
"s": 41418,
"text": "Advantages of BST over Hash Table"
},
{
"code": null,
"e": 41506,
"s": 41452,
"text": "Difference between Binary Tree and Binary Search Tree"
},
{
"code": null,
"e": 41551,
"s": 41506,
"text": "Binary Tree to Binary Search Tree Conversion"
},
{
"code": null,
"e": 41590,
"s": 41551,
"text": "Merge Two Balanced Binary Search Trees"
},
{
"code": null,
"e": 41622,
"s": 41590,
"text": "set vs unordered_set in C++ STL"
},
{
"code": null,
"e": 41672,
"s": 41622,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 41707,
"s": 41672,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 41741,
"s": 41707,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 41784,
"s": 41741,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
}
] |
Python: filecmp.cmp() method - GeeksforGeeks
|
10 Jan, 2020
Filecmp module in Python provides functions to compare files and directories. This module comes under Python’s standard utility modules. This module also consider the properties of files and directories for comparison in addition to data in them.
filecmp.cmp() method in Python is used to compare two files. This method by default performs shallow comparison (as by default shallow = True) that means only the os.stat() signatures (like size, date modified etc.) of both files are compared and if they have identical signatures then files are considered to be equal irrespective of contents of the files. If shallow is set to False then the comparison is done by comparing the contents of both files.
Syntax: filecmp.cmp(file1, file2, shallow = True)
Parameter:file1: The path of first file to be compared. It can be a string, bytes, os.PathLike object or an integer representing the path of the file.file2: The path of second file to be compared. It can be a string, bytes, os.PathLike object or an integer representing the path of the file.shallow (optional): A bool value ‘True’ or ‘False’. The default value of this parameter is True. If its value is True then only the metadata of files are compared. If False then the contents of the files are compared.
Return Type: This method returns a bool value True if specified files are equal or False if they are not.
# Python program to demonstrate# filecmp.cmp() method import filecmp # Path of first filefile1 = "/home/geeks/Desktop/gfg/data.txt" # Path of second filefile2 = "/home/geeks/Desktop/gfg/gfg.txt" # Compare the os.stat()# signature i.e the metadata# of both files comp = filecmp.cmp(file1, file2) # Print the result of comparisonprint(comp) # Compare the# contents of both filescomp = filecmp.cmp(file1, file2, shallow = False) # Print the result of comparisonprint(comp)
False
True
python-file-handling
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 25939,
"s": 25911,
"text": "\n10 Jan, 2020"
},
{
"code": null,
"e": 26186,
"s": 25939,
"text": "Filecmp module in Python provides functions to compare files and directories. This module comes under Python’s standard utility modules. This module also consider the properties of files and directories for comparison in addition to data in them."
},
{
"code": null,
"e": 26640,
"s": 26186,
"text": "filecmp.cmp() method in Python is used to compare two files. This method by default performs shallow comparison (as by default shallow = True) that means only the os.stat() signatures (like size, date modified etc.) of both files are compared and if they have identical signatures then files are considered to be equal irrespective of contents of the files. If shallow is set to False then the comparison is done by comparing the contents of both files."
},
{
"code": null,
"e": 26690,
"s": 26640,
"text": "Syntax: filecmp.cmp(file1, file2, shallow = True)"
},
{
"code": null,
"e": 27199,
"s": 26690,
"text": "Parameter:file1: The path of first file to be compared. It can be a string, bytes, os.PathLike object or an integer representing the path of the file.file2: The path of second file to be compared. It can be a string, bytes, os.PathLike object or an integer representing the path of the file.shallow (optional): A bool value ‘True’ or ‘False’. The default value of this parameter is True. If its value is True then only the metadata of files are compared. If False then the contents of the files are compared."
},
{
"code": null,
"e": 27305,
"s": 27199,
"text": "Return Type: This method returns a bool value True if specified files are equal or False if they are not."
},
{
"code": "# Python program to demonstrate# filecmp.cmp() method import filecmp # Path of first filefile1 = \"/home/geeks/Desktop/gfg/data.txt\" # Path of second filefile2 = \"/home/geeks/Desktop/gfg/gfg.txt\" # Compare the os.stat()# signature i.e the metadata# of both files comp = filecmp.cmp(file1, file2) # Print the result of comparisonprint(comp) # Compare the# contents of both filescomp = filecmp.cmp(file1, file2, shallow = False) # Print the result of comparisonprint(comp)",
"e": 27790,
"s": 27305,
"text": null
},
{
"code": null,
"e": 27802,
"s": 27790,
"text": "False\nTrue\n"
},
{
"code": null,
"e": 27823,
"s": 27802,
"text": "python-file-handling"
},
{
"code": null,
"e": 27838,
"s": 27823,
"text": "python-utility"
},
{
"code": null,
"e": 27845,
"s": 27838,
"text": "Python"
},
{
"code": null,
"e": 27943,
"s": 27845,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27961,
"s": 27943,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27996,
"s": 27961,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28028,
"s": 27996,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28050,
"s": 28028,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28092,
"s": 28050,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28122,
"s": 28092,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28148,
"s": 28122,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28177,
"s": 28148,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28221,
"s": 28177,
"text": "Reading and Writing to text files in Python"
}
] |
Understanding static_assert in C++ 11 - GeeksforGeeks
|
06 Jan, 2022
What is static assertion?
Static assertions are a way to check if a condition is true when the code is compiled. If it isn’t, the compiler is required to issue an error message and stop the compiling process. The condition that needs to be checked is a constant expression.
Performs compile-time assertion checking
Syntax:static_assert( constant_expression, string_literal );
static_assert( constant_expression, string_literal );
How has static assertion been done prior to C++ 11 standard?
Prior to the C++ 11 standard the primary mean of producing a compile-time error message was via the #error directive, which causes the implementation to produce a diagnostic message that includes the message that followed it. For example:
CPP
// Static assertion using #error directive#include <iostream>using namespace std;#if !defined(__geeksforgeeks)#error "Geeksforgeeks hasn't been defined yet".#endifint main(){ return 0;}
Error: Geeksforgeeks hasn’t been defined yet.
What is the problem with #error directive?
The #error directive works well will simple tasks. However, it fails when compile time assertion needs to be done for complex tasks such as checking the size of a data type using the sizeof operator. It is because the tokens such as ‘sizeof’ are not converted to source tokens until after the preprocessing translation stage at which point you can no longer use preprocessing directives.
How to do static assertion since C++ 11 standard?
The C++ 11 standard introduced a feature named static_assert() which can be used to test a software assertion at the compile time.
Syntax:
static_assert( constant_expression, string_literal );
Parameters:
constant_expression: An integral constant expression
that can be converted to a Boolean.
string_literal: The error message that is displayed
when the constant_expression parameter is false.
The ‘constant_expression’ parameter represents a software assertion (a condition that you expect to be true at a particular point in your program) that needs to be checked during the compile time. If the condition is true, the static_assert declaration has no effect. If the condition is false, the assertion fails, the compiler displays the message in string_literal parameter and the compilation fails with an error. It is, however, important to note that the string_literal parameter is optional.
Example:
CPP
// CPP code to demonstrate// static assertion using static_assert#include <iostream>using namespace std; template <class T, int Size>class Vector { // Compile time assertion to check if // the size of the vector is greater than // 3 or not. If any vector is declared whose // size is less than 4, the assertion will fail static_assert(Size > 3, "Vector size is too small!"); T m_values[Size];}; int main(){ Vector<int, 4> four; // This will work Vector<short, 2> two; // This will fail return 0;}
Output:
error: static assertion failed: Vector size is too small!
In the above code, we’ve created a template class named vector where we don’t wanna allow a vector to be created whose size is less than 4. Therefore, inside the template body, we put a static_assert statement to check if the vector being made is of size>3. In case of failure, the assertion will fail with the error message: ” Vector size is too small”.
This is exactly what happens in the declaration of the vector class object ‘two’. The size passed to it is ‘2’, which fails the condition to be checked, therefore producing the compile time error, and thus halting the compilation process.
What are the advantages of static_assert over #error?
Unlike #error, assertion using static_assert takes place after the preprocessing translation stage. Therefore, it is possible to check for the size of a datatype with sizeof using static_assert.CPPCPP// Datatype#include <iostream> using namespace std;// No error produced.// The program compiles well because// the size of long datatype is 8 bytesstatic_assert(sizeof(long) == 8, ode relies on 'long' being exactly 8 bytes");int main(){ return 0;}Libraries can detect common usage errors at compile time.Implementations of the C++ Standard Library can detect and diagnose common usage errors, improving usability.
Unlike #error, assertion using static_assert takes place after the preprocessing translation stage. Therefore, it is possible to check for the size of a datatype with sizeof using static_assert.CPPCPP// Datatype#include <iostream> using namespace std;// No error produced.// The program compiles well because// the size of long datatype is 8 bytesstatic_assert(sizeof(long) == 8, ode relies on 'long' being exactly 8 bytes");int main(){ return 0;}
CPP
// Datatype#include <iostream> using namespace std;// No error produced.// The program compiles well because// the size of long datatype is 8 bytesstatic_assert(sizeof(long) == 8, ode relies on 'long' being exactly 8 bytes");int main(){ return 0;}
Libraries can detect common usage errors at compile time.
Implementations of the C++ Standard Library can detect and diagnose common usage errors, improving usability.
Declaration Scopes
static_assert can be used in namespace scope, class scope, as well as block scope. The examples of each of the aforementioned scopes are as follows:
Namespace scope:CPPCPP// CPP program to illustrate// declaring static_assert in namespace scope#include <iostream>static_assert(sizeof(void*) == 8, "DTAMDL(*LLP64) is not allowed for this module.");int main(){ cout << "Assertion passed. The program didn't produce an error"; return 0;}Output:assertion passed. The program didn't produce an errorClass scope:CPPCPP// CPP program to illustrate class scope in// static assertion using static_assert#include <iostream>using namespace std; template <class T, int Size>class Vector { // Compile time assertion to check if // the size of the vector is greater than // 3 or not. If any vector is declared whose // size is less than 4, the assertion will fail static_assert(Size > 3, "Vector size is too small!"); T m_values[Size];}; int main(){ Vector<int, 4> four; // This will work Vector<short, 2> two; // This will fail return 0;}Output:error: static assertion failed: Vector size is too small!Block scope:CPPCPP// CPP program to illustrate// declaring static_assert in block scopetemplate <typename T, int N>void f(){ static_assert(N >= 0, "length of array a is negative."); T a[N];}int main(){ // assertion fails here // because the length of the array passed // is below 0 f<int, -1>(); return 0;}Output:error: static assertion failed: length of array a is negative.
Namespace scope:CPPCPP// CPP program to illustrate// declaring static_assert in namespace scope#include <iostream>static_assert(sizeof(void*) == 8, "DTAMDL(*LLP64) is not allowed for this module.");int main(){ cout << "Assertion passed. The program didn't produce an error"; return 0;}Output:assertion passed. The program didn't produce an error
CPP
// CPP program to illustrate// declaring static_assert in namespace scope#include <iostream>static_assert(sizeof(void*) == 8, "DTAMDL(*LLP64) is not allowed for this module.");int main(){ cout << "Assertion passed. The program didn't produce an error"; return 0;}
Output:
assertion passed. The program didn't produce an error
Class scope:CPPCPP// CPP program to illustrate class scope in// static assertion using static_assert#include <iostream>using namespace std; template <class T, int Size>class Vector { // Compile time assertion to check if // the size of the vector is greater than // 3 or not. If any vector is declared whose // size is less than 4, the assertion will fail static_assert(Size > 3, "Vector size is too small!"); T m_values[Size];}; int main(){ Vector<int, 4> four; // This will work Vector<short, 2> two; // This will fail return 0;}Output:error: static assertion failed: Vector size is too small!
CPP
// CPP program to illustrate class scope in// static assertion using static_assert#include <iostream>using namespace std; template <class T, int Size>class Vector { // Compile time assertion to check if // the size of the vector is greater than // 3 or not. If any vector is declared whose // size is less than 4, the assertion will fail static_assert(Size > 3, "Vector size is too small!"); T m_values[Size];}; int main(){ Vector<int, 4> four; // This will work Vector<short, 2> two; // This will fail return 0;}
Output:
error: static assertion failed: Vector size is too small!
Block scope:CPPCPP// CPP program to illustrate// declaring static_assert in block scopetemplate <typename T, int N>void f(){ static_assert(N >= 0, "length of array a is negative."); T a[N];}int main(){ // assertion fails here // because the length of the array passed // is below 0 f<int, -1>(); return 0;}Output:error: static assertion failed: length of array a is negative.
CPP
// CPP program to illustrate// declaring static_assert in block scopetemplate <typename T, int N>void f(){ static_assert(N >= 0, "length of array a is negative."); T a[N];}int main(){ // assertion fails here // because the length of the array passed // is below 0 f<int, -1>(); return 0;}
Output:
error: static assertion failed: length of array a is negative.
Erroneous static_assert
The constant_expression passed in static_assertion needs to be a valid expression. For example, consider the following code:
CPP
// CPP program to illustrate// demonstrating an erroneous static_assert declarationint main(){ static_assert(1 / 0, "never shows up!"); return 0;}
prog.cpp:5:2: error: non-constant condition for static assertion
static_assert(1 / 0, "never shows up!");
^
In the above piece of code, the expression ‘1/0‘ is not a valid constant expression. Therefore, When this is compiled, instead of showing the string literal in the static_assert declaration, the compiler issues an error message indicating that the divisor must not be zero.
sooda367
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Virtual Function in C++
Bitwise Operators in C/C++
Constructors in C++
Operator Overloading in C++
Socket Programming in C/C++
Object Oriented Programming in C++
Copy Constructor in C++
|
[
{
"code": null,
"e": 25681,
"s": 25653,
"text": "\n06 Jan, 2022"
},
{
"code": null,
"e": 25707,
"s": 25681,
"text": "What is static assertion?"
},
{
"code": null,
"e": 25955,
"s": 25707,
"text": "Static assertions are a way to check if a condition is true when the code is compiled. If it isn’t, the compiler is required to issue an error message and stop the compiling process. The condition that needs to be checked is a constant expression."
},
{
"code": null,
"e": 25996,
"s": 25955,
"text": "Performs compile-time assertion checking"
},
{
"code": null,
"e": 26058,
"s": 25996,
"text": "Syntax:static_assert( constant_expression, string_literal ); "
},
{
"code": null,
"e": 26113,
"s": 26058,
"text": "static_assert( constant_expression, string_literal ); "
},
{
"code": null,
"e": 26174,
"s": 26113,
"text": "How has static assertion been done prior to C++ 11 standard?"
},
{
"code": null,
"e": 26413,
"s": 26174,
"text": "Prior to the C++ 11 standard the primary mean of producing a compile-time error message was via the #error directive, which causes the implementation to produce a diagnostic message that includes the message that followed it. For example:"
},
{
"code": null,
"e": 26417,
"s": 26413,
"text": "CPP"
},
{
"code": "// Static assertion using #error directive#include <iostream>using namespace std;#if !defined(__geeksforgeeks)#error \"Geeksforgeeks hasn't been defined yet\".#endifint main(){ return 0;}",
"e": 26606,
"s": 26417,
"text": null
},
{
"code": null,
"e": 26652,
"s": 26606,
"text": "Error: Geeksforgeeks hasn’t been defined yet."
},
{
"code": null,
"e": 26695,
"s": 26652,
"text": "What is the problem with #error directive?"
},
{
"code": null,
"e": 27083,
"s": 26695,
"text": "The #error directive works well will simple tasks. However, it fails when compile time assertion needs to be done for complex tasks such as checking the size of a data type using the sizeof operator. It is because the tokens such as ‘sizeof’ are not converted to source tokens until after the preprocessing translation stage at which point you can no longer use preprocessing directives."
},
{
"code": null,
"e": 27133,
"s": 27083,
"text": "How to do static assertion since C++ 11 standard?"
},
{
"code": null,
"e": 27264,
"s": 27133,
"text": "The C++ 11 standard introduced a feature named static_assert() which can be used to test a software assertion at the compile time."
},
{
"code": null,
"e": 27272,
"s": 27264,
"text": "Syntax:"
},
{
"code": null,
"e": 27533,
"s": 27272,
"text": "static_assert( constant_expression, string_literal ); \nParameters:\nconstant_expression: An integral constant expression \nthat can be converted to a Boolean.\nstring_literal: The error message that is displayed \nwhen the constant_expression parameter is false. "
},
{
"code": null,
"e": 28033,
"s": 27533,
"text": "The ‘constant_expression’ parameter represents a software assertion (a condition that you expect to be true at a particular point in your program) that needs to be checked during the compile time. If the condition is true, the static_assert declaration has no effect. If the condition is false, the assertion fails, the compiler displays the message in string_literal parameter and the compilation fails with an error. It is, however, important to note that the string_literal parameter is optional."
},
{
"code": null,
"e": 28042,
"s": 28033,
"text": "Example:"
},
{
"code": null,
"e": 28046,
"s": 28042,
"text": "CPP"
},
{
"code": "// CPP code to demonstrate// static assertion using static_assert#include <iostream>using namespace std; template <class T, int Size>class Vector { // Compile time assertion to check if // the size of the vector is greater than // 3 or not. If any vector is declared whose // size is less than 4, the assertion will fail static_assert(Size > 3, \"Vector size is too small!\"); T m_values[Size];}; int main(){ Vector<int, 4> four; // This will work Vector<short, 2> two; // This will fail return 0;}",
"e": 28576,
"s": 28046,
"text": null
},
{
"code": null,
"e": 28584,
"s": 28576,
"text": "Output:"
},
{
"code": null,
"e": 28642,
"s": 28584,
"text": "error: static assertion failed: Vector size is too small!"
},
{
"code": null,
"e": 28997,
"s": 28642,
"text": "In the above code, we’ve created a template class named vector where we don’t wanna allow a vector to be created whose size is less than 4. Therefore, inside the template body, we put a static_assert statement to check if the vector being made is of size>3. In case of failure, the assertion will fail with the error message: ” Vector size is too small”."
},
{
"code": null,
"e": 29236,
"s": 28997,
"text": "This is exactly what happens in the declaration of the vector class object ‘two’. The size passed to it is ‘2’, which fails the condition to be checked, therefore producing the compile time error, and thus halting the compilation process."
},
{
"code": null,
"e": 29290,
"s": 29236,
"text": "What are the advantages of static_assert over #error?"
},
{
"code": null,
"e": 29908,
"s": 29290,
"text": "Unlike #error, assertion using static_assert takes place after the preprocessing translation stage. Therefore, it is possible to check for the size of a datatype with sizeof using static_assert.CPPCPP// Datatype#include <iostream> using namespace std;// No error produced.// The program compiles well because// the size of long datatype is 8 bytesstatic_assert(sizeof(long) == 8, ode relies on 'long' being exactly 8 bytes\");int main(){ return 0;}Libraries can detect common usage errors at compile time.Implementations of the C++ Standard Library can detect and diagnose common usage errors, improving usability."
},
{
"code": null,
"e": 30360,
"s": 29908,
"text": "Unlike #error, assertion using static_assert takes place after the preprocessing translation stage. Therefore, it is possible to check for the size of a datatype with sizeof using static_assert.CPPCPP// Datatype#include <iostream> using namespace std;// No error produced.// The program compiles well because// the size of long datatype is 8 bytesstatic_assert(sizeof(long) == 8, ode relies on 'long' being exactly 8 bytes\");int main(){ return 0;}"
},
{
"code": null,
"e": 30364,
"s": 30360,
"text": "CPP"
},
{
"code": "// Datatype#include <iostream> using namespace std;// No error produced.// The program compiles well because// the size of long datatype is 8 bytesstatic_assert(sizeof(long) == 8, ode relies on 'long' being exactly 8 bytes\");int main(){ return 0;}",
"e": 30616,
"s": 30364,
"text": null
},
{
"code": null,
"e": 30674,
"s": 30616,
"text": "Libraries can detect common usage errors at compile time."
},
{
"code": null,
"e": 30784,
"s": 30674,
"text": "Implementations of the C++ Standard Library can detect and diagnose common usage errors, improving usability."
},
{
"code": null,
"e": 30803,
"s": 30784,
"text": "Declaration Scopes"
},
{
"code": null,
"e": 30952,
"s": 30803,
"text": "static_assert can be used in namespace scope, class scope, as well as block scope. The examples of each of the aforementioned scopes are as follows:"
},
{
"code": null,
"e": 32332,
"s": 30952,
"text": "Namespace scope:CPPCPP// CPP program to illustrate// declaring static_assert in namespace scope#include <iostream>static_assert(sizeof(void*) == 8, \"DTAMDL(*LLP64) is not allowed for this module.\");int main(){ cout << \"Assertion passed. The program didn't produce an error\"; return 0;}Output:assertion passed. The program didn't produce an errorClass scope:CPPCPP// CPP program to illustrate class scope in// static assertion using static_assert#include <iostream>using namespace std; template <class T, int Size>class Vector { // Compile time assertion to check if // the size of the vector is greater than // 3 or not. If any vector is declared whose // size is less than 4, the assertion will fail static_assert(Size > 3, \"Vector size is too small!\"); T m_values[Size];}; int main(){ Vector<int, 4> four; // This will work Vector<short, 2> two; // This will fail return 0;}Output:error: static assertion failed: Vector size is too small!Block scope:CPPCPP// CPP program to illustrate// declaring static_assert in block scopetemplate <typename T, int N>void f(){ static_assert(N >= 0, \"length of array a is negative.\"); T a[N];}int main(){ // assertion fails here // because the length of the array passed // is below 0 f<int, -1>(); return 0;}Output:error: static assertion failed: length of array a is negative."
},
{
"code": null,
"e": 32688,
"s": 32332,
"text": "Namespace scope:CPPCPP// CPP program to illustrate// declaring static_assert in namespace scope#include <iostream>static_assert(sizeof(void*) == 8, \"DTAMDL(*LLP64) is not allowed for this module.\");int main(){ cout << \"Assertion passed. The program didn't produce an error\"; return 0;}Output:assertion passed. The program didn't produce an error"
},
{
"code": null,
"e": 32692,
"s": 32688,
"text": "CPP"
},
{
"code": "// CPP program to illustrate// declaring static_assert in namespace scope#include <iostream>static_assert(sizeof(void*) == 8, \"DTAMDL(*LLP64) is not allowed for this module.\");int main(){ cout << \"Assertion passed. The program didn't produce an error\"; return 0;}",
"e": 32966,
"s": 32692,
"text": null
},
{
"code": null,
"e": 32974,
"s": 32966,
"text": "Output:"
},
{
"code": null,
"e": 33028,
"s": 32974,
"text": "assertion passed. The program didn't produce an error"
},
{
"code": null,
"e": 33657,
"s": 33028,
"text": "Class scope:CPPCPP// CPP program to illustrate class scope in// static assertion using static_assert#include <iostream>using namespace std; template <class T, int Size>class Vector { // Compile time assertion to check if // the size of the vector is greater than // 3 or not. If any vector is declared whose // size is less than 4, the assertion will fail static_assert(Size > 3, \"Vector size is too small!\"); T m_values[Size];}; int main(){ Vector<int, 4> four; // This will work Vector<short, 2> two; // This will fail return 0;}Output:error: static assertion failed: Vector size is too small!"
},
{
"code": null,
"e": 33661,
"s": 33657,
"text": "CPP"
},
{
"code": "// CPP program to illustrate class scope in// static assertion using static_assert#include <iostream>using namespace std; template <class T, int Size>class Vector { // Compile time assertion to check if // the size of the vector is greater than // 3 or not. If any vector is declared whose // size is less than 4, the assertion will fail static_assert(Size > 3, \"Vector size is too small!\"); T m_values[Size];}; int main(){ Vector<int, 4> four; // This will work Vector<short, 2> two; // This will fail return 0;}",
"e": 34208,
"s": 33661,
"text": null
},
{
"code": null,
"e": 34216,
"s": 34208,
"text": "Output:"
},
{
"code": null,
"e": 34274,
"s": 34216,
"text": "error: static assertion failed: Vector size is too small!"
},
{
"code": null,
"e": 34671,
"s": 34274,
"text": "Block scope:CPPCPP// CPP program to illustrate// declaring static_assert in block scopetemplate <typename T, int N>void f(){ static_assert(N >= 0, \"length of array a is negative.\"); T a[N];}int main(){ // assertion fails here // because the length of the array passed // is below 0 f<int, -1>(); return 0;}Output:error: static assertion failed: length of array a is negative."
},
{
"code": null,
"e": 34675,
"s": 34671,
"text": "CPP"
},
{
"code": "// CPP program to illustrate// declaring static_assert in block scopetemplate <typename T, int N>void f(){ static_assert(N >= 0, \"length of array a is negative.\"); T a[N];}int main(){ // assertion fails here // because the length of the array passed // is below 0 f<int, -1>(); return 0;}",
"e": 34985,
"s": 34675,
"text": null
},
{
"code": null,
"e": 34993,
"s": 34985,
"text": "Output:"
},
{
"code": null,
"e": 35056,
"s": 34993,
"text": "error: static assertion failed: length of array a is negative."
},
{
"code": null,
"e": 35080,
"s": 35056,
"text": "Erroneous static_assert"
},
{
"code": null,
"e": 35205,
"s": 35080,
"text": "The constant_expression passed in static_assertion needs to be a valid expression. For example, consider the following code:"
},
{
"code": null,
"e": 35209,
"s": 35205,
"text": "CPP"
},
{
"code": "// CPP program to illustrate// demonstrating an erroneous static_assert declarationint main(){ static_assert(1 / 0, \"never shows up!\"); return 0;}",
"e": 35362,
"s": 35209,
"text": null
},
{
"code": null,
"e": 35474,
"s": 35362,
"text": "prog.cpp:5:2: error: non-constant condition for static assertion\n static_assert(1 / 0, \"never shows up!\");\n ^"
},
{
"code": null,
"e": 35748,
"s": 35474,
"text": "In the above piece of code, the expression ‘1/0‘ is not a valid constant expression. Therefore, When this is compiled, instead of showing the string literal in the static_assert declaration, the compiler issues an error message indicating that the divisor must not be zero."
},
{
"code": null,
"e": 35757,
"s": 35748,
"text": "sooda367"
},
{
"code": null,
"e": 35761,
"s": 35757,
"text": "C++"
},
{
"code": null,
"e": 35765,
"s": 35761,
"text": "CPP"
},
{
"code": null,
"e": 35863,
"s": 35765,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35882,
"s": 35863,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 35925,
"s": 35882,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 35949,
"s": 35925,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 35973,
"s": 35949,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 36000,
"s": 35973,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 36020,
"s": 36000,
"text": "Constructors in C++"
},
{
"code": null,
"e": 36048,
"s": 36020,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 36076,
"s": 36048,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 36111,
"s": 36076,
"text": "Object Oriented Programming in C++"
}
] |
How to set up Kubernetes cluster on local machine using minikube ? - GeeksforGeeks
|
03 Feb, 2021
Creating a Kubernetes cluster on AWS, Google Cloud, etc, can be a little difficult and cost you a pretty decent amount of money. If you have a Windows machine or a mac then it is easy to create a multi-container cluster using Docker Desktop for windows/mac and use Kubernetes to manage the cluster.
Perquisites: Have some basic knowledge of Docker and Kubernetes.
But for Linux bases system, you have to either go for a cloud-based solution which is costly. So we can create our own cluster on our local machine using minikube. It is local Kubernetes, focusing on making it easy to learn and develop for Kubernetes. You just need docker installed or any Virtual machine environment. In the following example, we have used the virtual box.
Installing Minikube: To install minikube on Linux, use the following command:
curl -LO https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64sudo install minikube-linux-amd64 /usr/local/bin/minikube
Example: To test this out we are going to use a ticket selling web application that is built using NodeJS, ExpressJS, NextJS and used nats-streaming for event transmission, ingress-nginx for networking and loadbalancing. A different docker image for different services and have used minikube to run the cluster locally using minikube.
Github link of Repo: Use the https://github.com/afif1400/gittix-micro link to fork the project.
Note: After you install docker or virtual box and minikube we just have to start minikube and use skaffold to run all the containers or different microservices.
So after you clone the repo go to the root directory, first start minikube –driver is used to specify the environment you can change it to docker as well. But there is a bug in ingress using the docker environment.
minikube start --driver="virtualbox"
Now minikube has started the Kubernetes cluster inside it, you can also configure the resources used by it by going through the docs of the official website provided in the reference.
We need to enable a couple of add-ons on minikube to run the application. First is the dashboard which is a GUI to monitor cluster deployment services etc and the second add-on is ingress.
Command for enabling dashboard:
minikube addons enable dashboard
Command for enabling ingress:
minikube addons enable ingress
Now we need to expose the ingress-nginx deployment so that it can be reached from the outer world. Use the following command to do so:
kubectl expose deployment ingress-nginx-controller --target-port=80
--type=NodePort -n kube-system
Now to verify that the service is running run: and the output should be similar to the output given below.
kubectl get services -n kube-system
Next, Set an environment variable which is a jwt-secret, to set this, run the following command:
kubectl create secret generic jwt-secret --from-literal=JWT_KEY=asdf
This we will be using in our authentication service for generating the jwt token.
Step to run the application:
Use the following command to run the application:
skaffold dev
When you run this command all the dependencies for each of the services will be installed and build the image, starting the cluster. If skaffold fails in between just re-run the above command.
Output:
Stop minikube: Following is the command to stop minikube:
minikube stop
Delete the cluster: Following is the command to delete the cluster:
minikube delete
References:
Docker: https://docs.docker.com/get-started/overview/
Ingressnginx: https://kubernetes.github.io/ingress-nginx/
Skaffold: https://skaffold.dev/docs/
Minikube: https://minikube.sigs.k8s.io/docs
NodeJS-Questions
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between dependencies, devDependencies and peerDependencies
How to connect Node.js with React.js ?
Node.js Export Module
Mongoose Populate() Method
Mongoose find() Function
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26267,
"s": 26239,
"text": "\n03 Feb, 2021"
},
{
"code": null,
"e": 26566,
"s": 26267,
"text": "Creating a Kubernetes cluster on AWS, Google Cloud, etc, can be a little difficult and cost you a pretty decent amount of money. If you have a Windows machine or a mac then it is easy to create a multi-container cluster using Docker Desktop for windows/mac and use Kubernetes to manage the cluster."
},
{
"code": null,
"e": 26632,
"s": 26566,
"text": "Perquisites: Have some basic knowledge of Docker and Kubernetes. "
},
{
"code": null,
"e": 27008,
"s": 26632,
"text": "But for Linux bases system, you have to either go for a cloud-based solution which is costly. So we can create our own cluster on our local machine using minikube. It is local Kubernetes, focusing on making it easy to learn and develop for Kubernetes. You just need docker installed or any Virtual machine environment. In the following example, we have used the virtual box. "
},
{
"code": null,
"e": 27086,
"s": 27008,
"text": "Installing Minikube: To install minikube on Linux, use the following command:"
},
{
"code": null,
"e": 27229,
"s": 27086,
"text": "curl -LO https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64sudo install minikube-linux-amd64 /usr/local/bin/minikube"
},
{
"code": null,
"e": 27565,
"s": 27229,
"text": "Example: To test this out we are going to use a ticket selling web application that is built using NodeJS, ExpressJS, NextJS and used nats-streaming for event transmission, ingress-nginx for networking and loadbalancing. A different docker image for different services and have used minikube to run the cluster locally using minikube. "
},
{
"code": null,
"e": 27661,
"s": 27565,
"text": "Github link of Repo: Use the https://github.com/afif1400/gittix-micro link to fork the project."
},
{
"code": null,
"e": 27822,
"s": 27661,
"text": "Note: After you install docker or virtual box and minikube we just have to start minikube and use skaffold to run all the containers or different microservices."
},
{
"code": null,
"e": 28037,
"s": 27822,
"text": "So after you clone the repo go to the root directory, first start minikube –driver is used to specify the environment you can change it to docker as well. But there is a bug in ingress using the docker environment."
},
{
"code": null,
"e": 28074,
"s": 28037,
"text": "minikube start --driver=\"virtualbox\""
},
{
"code": null,
"e": 28258,
"s": 28074,
"text": "Now minikube has started the Kubernetes cluster inside it, you can also configure the resources used by it by going through the docs of the official website provided in the reference."
},
{
"code": null,
"e": 28448,
"s": 28258,
"text": "We need to enable a couple of add-ons on minikube to run the application. First is the dashboard which is a GUI to monitor cluster deployment services etc and the second add-on is ingress. "
},
{
"code": null,
"e": 28480,
"s": 28448,
"text": "Command for enabling dashboard:"
},
{
"code": null,
"e": 28513,
"s": 28480,
"text": "minikube addons enable dashboard"
},
{
"code": null,
"e": 28543,
"s": 28513,
"text": "Command for enabling ingress:"
},
{
"code": null,
"e": 28574,
"s": 28543,
"text": "minikube addons enable ingress"
},
{
"code": null,
"e": 28709,
"s": 28574,
"text": "Now we need to expose the ingress-nginx deployment so that it can be reached from the outer world. Use the following command to do so:"
},
{
"code": null,
"e": 28809,
"s": 28709,
"text": "kubectl expose deployment ingress-nginx-controller --target-port=80 \n--type=NodePort -n kube-system"
},
{
"code": null,
"e": 28916,
"s": 28809,
"text": "Now to verify that the service is running run: and the output should be similar to the output given below."
},
{
"code": null,
"e": 28952,
"s": 28916,
"text": "kubectl get services -n kube-system"
},
{
"code": null,
"e": 29049,
"s": 28952,
"text": "Next, Set an environment variable which is a jwt-secret, to set this, run the following command:"
},
{
"code": null,
"e": 29118,
"s": 29049,
"text": "kubectl create secret generic jwt-secret --from-literal=JWT_KEY=asdf"
},
{
"code": null,
"e": 29201,
"s": 29118,
"text": "This we will be using in our authentication service for generating the jwt token. "
},
{
"code": null,
"e": 29230,
"s": 29201,
"text": "Step to run the application:"
},
{
"code": null,
"e": 29280,
"s": 29230,
"text": "Use the following command to run the application:"
},
{
"code": null,
"e": 29293,
"s": 29280,
"text": "skaffold dev"
},
{
"code": null,
"e": 29487,
"s": 29293,
"text": "When you run this command all the dependencies for each of the services will be installed and build the image, starting the cluster. If skaffold fails in between just re-run the above command. "
},
{
"code": null,
"e": 29495,
"s": 29487,
"text": "Output:"
},
{
"code": null,
"e": 29553,
"s": 29495,
"text": "Stop minikube: Following is the command to stop minikube:"
},
{
"code": null,
"e": 29567,
"s": 29553,
"text": "minikube stop"
},
{
"code": null,
"e": 29635,
"s": 29567,
"text": "Delete the cluster: Following is the command to delete the cluster:"
},
{
"code": null,
"e": 29651,
"s": 29635,
"text": "minikube delete"
},
{
"code": null,
"e": 29663,
"s": 29651,
"text": "References:"
},
{
"code": null,
"e": 29717,
"s": 29663,
"text": "Docker: https://docs.docker.com/get-started/overview/"
},
{
"code": null,
"e": 29775,
"s": 29717,
"text": "Ingressnginx: https://kubernetes.github.io/ingress-nginx/"
},
{
"code": null,
"e": 29812,
"s": 29775,
"text": "Skaffold: https://skaffold.dev/docs/"
},
{
"code": null,
"e": 29856,
"s": 29812,
"text": "Minikube: https://minikube.sigs.k8s.io/docs"
},
{
"code": null,
"e": 29873,
"s": 29856,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 29881,
"s": 29873,
"text": "Node.js"
},
{
"code": null,
"e": 29898,
"s": 29881,
"text": "Web Technologies"
},
{
"code": null,
"e": 29996,
"s": 29898,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30066,
"s": 29996,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 30105,
"s": 30066,
"text": "How to connect Node.js with React.js ?"
},
{
"code": null,
"e": 30127,
"s": 30105,
"text": "Node.js Export Module"
},
{
"code": null,
"e": 30154,
"s": 30127,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 30179,
"s": 30154,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 30219,
"s": 30179,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30264,
"s": 30219,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30307,
"s": 30264,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 30357,
"s": 30307,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
What is Components Inheritance in React ? - GeeksforGeeks
|
14 Jul, 2021
Inheritance is a concept that plays a major role in object-oriented programming. It is a technique that allows objects to have those properties that are already existing on previous objects.
Two classes exist are:
Superclass(Parent Class)
Subclass(Child Class)
In React, the composition model is used instead of inheritance, so that code can be re-used again between the components. In react extends keyword is used on the main function i.e the constructor function. By using the extends keyword you can have the present component have all the component properties from the already existing component. The composition model uses the super-sub class relationship by passing the state and props. The sub-class segment can access any progressions to one another.
Creating React Application:
Step 1: Create a React application using the following command in the terminal/ command prompt:create-react-app foldername
Step 1: Create a React application using the following command in the terminal/ command prompt:
create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: It will look like the following:
Project Structure
Here, you have two components i.e. AppComponent and a ChildComponent, and the child component takes over all the app properties.
Example: Now write down the following code in the App.js file. Here, App is our default(parent) component where we have written our code. In the below code, this.state.message is passed to ChildComponent.
App.js
import logo from './logo.svg';import React from 'react';import './App.css';import ChildComponent from "./ChildComponent"; class App extends React.Component { constructor(props) { super(props); this.state = { message: " Geeks for Geeks message" }; } render() { return ( <div> <ChildComponent message={this.state.message} /> </div> ); }}export default App;
Now write down the following code in the ChildComponent.js file. The child component accepts all the app component properties.
ChildComponent.js
import React from "react"; class ChildComponent extends React.Component { render() { const { message } = this.props; return ( <div> <p> Message from App component : <b>{message}</b> </p> </div> ); }} export default ChildComponent;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
Child Component accessed App component properties
Picked
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
Axios in React: A Guide for Beginners
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26071,
"s": 26043,
"text": "\n14 Jul, 2021"
},
{
"code": null,
"e": 26262,
"s": 26071,
"text": "Inheritance is a concept that plays a major role in object-oriented programming. It is a technique that allows objects to have those properties that are already existing on previous objects."
},
{
"code": null,
"e": 26285,
"s": 26262,
"text": "Two classes exist are:"
},
{
"code": null,
"e": 26310,
"s": 26285,
"text": "Superclass(Parent Class)"
},
{
"code": null,
"e": 26332,
"s": 26310,
"text": "Subclass(Child Class)"
},
{
"code": null,
"e": 26831,
"s": 26332,
"text": "In React, the composition model is used instead of inheritance, so that code can be re-used again between the components. In react extends keyword is used on the main function i.e the constructor function. By using the extends keyword you can have the present component have all the component properties from the already existing component. The composition model uses the super-sub class relationship by passing the state and props. The sub-class segment can access any progressions to one another."
},
{
"code": null,
"e": 26861,
"s": 26833,
"text": "Creating React Application:"
},
{
"code": null,
"e": 26984,
"s": 26861,
"text": "Step 1: Create a React application using the following command in the terminal/ command prompt:create-react-app foldername"
},
{
"code": null,
"e": 27080,
"s": 26984,
"text": "Step 1: Create a React application using the following command in the terminal/ command prompt:"
},
{
"code": null,
"e": 27108,
"s": 27080,
"text": "create-react-app foldername"
},
{
"code": null,
"e": 27221,
"s": 27108,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 27321,
"s": 27221,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 27335,
"s": 27321,
"text": "cd foldername"
},
{
"code": null,
"e": 27387,
"s": 27335,
"text": "Project Structure: It will look like the following:"
},
{
"code": null,
"e": 27405,
"s": 27387,
"text": "Project Structure"
},
{
"code": null,
"e": 27534,
"s": 27405,
"text": "Here, you have two components i.e. AppComponent and a ChildComponent, and the child component takes over all the app properties."
},
{
"code": null,
"e": 27739,
"s": 27534,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default(parent) component where we have written our code. In the below code, this.state.message is passed to ChildComponent."
},
{
"code": null,
"e": 27746,
"s": 27739,
"text": "App.js"
},
{
"code": "import logo from './logo.svg';import React from 'react';import './App.css';import ChildComponent from \"./ChildComponent\"; class App extends React.Component { constructor(props) { super(props); this.state = { message: \" Geeks for Geeks message\" }; } render() { return ( <div> <ChildComponent message={this.state.message} /> </div> ); }}export default App;",
"e": 28199,
"s": 27746,
"text": null
},
{
"code": null,
"e": 28326,
"s": 28199,
"text": "Now write down the following code in the ChildComponent.js file. The child component accepts all the app component properties."
},
{
"code": null,
"e": 28344,
"s": 28326,
"text": "ChildComponent.js"
},
{
"code": "import React from \"react\"; class ChildComponent extends React.Component { render() { const { message } = this.props; return ( <div> <p> Message from App component : <b>{message}</b> </p> </div> ); }} export default ChildComponent;",
"e": 28639,
"s": 28344,
"text": null
},
{
"code": null,
"e": 28752,
"s": 28639,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 28762,
"s": 28752,
"text": "npm start"
},
{
"code": null,
"e": 28771,
"s": 28762,
"text": "Output: "
},
{
"code": null,
"e": 28821,
"s": 28771,
"text": "Child Component accessed App component properties"
},
{
"code": null,
"e": 28828,
"s": 28821,
"text": "Picked"
},
{
"code": null,
"e": 28844,
"s": 28828,
"text": "React-Questions"
},
{
"code": null,
"e": 28852,
"s": 28844,
"text": "ReactJS"
},
{
"code": null,
"e": 28869,
"s": 28852,
"text": "Web Technologies"
},
{
"code": null,
"e": 28967,
"s": 28869,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28994,
"s": 28967,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 29036,
"s": 28994,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 29074,
"s": 29036,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 29109,
"s": 29074,
"text": "How to create a table in ReactJS ?"
},
{
"code": null,
"e": 29167,
"s": 29109,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 29207,
"s": 29167,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29240,
"s": 29207,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29285,
"s": 29240,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29335,
"s": 29285,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
ReactJS Reactstrap Spinners Component - GeeksforGeeks
|
28 Jul, 2021
Reactstrap is a popular front-end library that is easy to use React Bootstrap 4 components. This library contains the stateless React components for Bootstrap 4. The Spinner component allows the user to show the loading effect. It is used for the purpose of indicating a loading state. We can use the following approach in ReactJS to use the ReactJS Reactstrap Spinner Component.
Spinner Props:
bsPrefix: This prop is used to denote the change in component in css.It is used to customize the bootstrap css .The default value is spinner and type is string .
size: The size of props is used to demonstrate the size of the spinner .The size of props is used in component size variations . The type of size is sm.
color: The color props is used to denote the color of the spinner.
className: The className props is used to denote the class name for styling the component in css .
children: It is used to pass the children element to this component in React JS .The type of children is element .
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, install the required module using the following command:
npm install reactstrap bootstrap
Project Structure: It will look like the following.
Project Structure
Example 1: Now write down the following code in the App.js file. Here, we have shown a spinner with grow type.
App.js
import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Spinner } from "reactstrap" function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Reactstrap Simple Spinner Component</h4> <Spinner type="grow" color="warning" children={false} /> </div> );} export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Example 2: Now write down the following code in the App.js file. Here, we have shown a spinner without grow type.
App.js
import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Spinner } from "reactstrap" function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Reactstrap Spinner Component</h4> <Spinner style={{ width: '2rem', height: '2rem' }} children={false} /> </div> );} export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference: https://reactstrap.github.io/components/spinners/
Reactstrap
JavaScript
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
How to pass data from one component to other component in ReactJS ?
ReactJS Functional Components
|
[
{
"code": null,
"e": 26582,
"s": 26554,
"text": "\n28 Jul, 2021"
},
{
"code": null,
"e": 26962,
"s": 26582,
"text": "Reactstrap is a popular front-end library that is easy to use React Bootstrap 4 components. This library contains the stateless React components for Bootstrap 4. The Spinner component allows the user to show the loading effect. It is used for the purpose of indicating a loading state. We can use the following approach in ReactJS to use the ReactJS Reactstrap Spinner Component."
},
{
"code": null,
"e": 26977,
"s": 26962,
"text": "Spinner Props:"
},
{
"code": null,
"e": 27140,
"s": 26977,
"text": "bsPrefix: This prop is used to denote the change in component in css.It is used to customize the bootstrap css .The default value is spinner and type is string ."
},
{
"code": null,
"e": 27293,
"s": 27140,
"text": "size: The size of props is used to demonstrate the size of the spinner .The size of props is used in component size variations . The type of size is sm."
},
{
"code": null,
"e": 27361,
"s": 27293,
"text": "color: The color props is used to denote the color of the spinner."
},
{
"code": null,
"e": 27461,
"s": 27361,
"text": "className: The className props is used to denote the class name for styling the component in css ."
},
{
"code": null,
"e": 27576,
"s": 27461,
"text": "children: It is used to pass the children element to this component in React JS .The type of children is element ."
},
{
"code": null,
"e": 27626,
"s": 27576,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 27690,
"s": 27626,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 27722,
"s": 27690,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 27824,
"s": 27724,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 27838,
"s": 27824,
"text": "cd foldername"
},
{
"code": null,
"e": 27943,
"s": 27838,
"text": "Step 3: After creating the ReactJS application, install the required module using the following command:"
},
{
"code": null,
"e": 27976,
"s": 27943,
"text": "npm install reactstrap bootstrap"
},
{
"code": null,
"e": 28028,
"s": 27976,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 28046,
"s": 28028,
"text": "Project Structure"
},
{
"code": null,
"e": 28157,
"s": 28046,
"text": "Example 1: Now write down the following code in the App.js file. Here, we have shown a spinner with grow type."
},
{
"code": null,
"e": 28164,
"s": 28157,
"text": "App.js"
},
{
"code": "import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Spinner } from \"reactstrap\" function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Reactstrap Simple Spinner Component</h4> <Spinner type=\"grow\" color=\"warning\" children={false} /> </div> );} export default App;",
"e": 28578,
"s": 28164,
"text": null
},
{
"code": null,
"e": 28691,
"s": 28578,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 28701,
"s": 28691,
"text": "npm start"
},
{
"code": null,
"e": 28800,
"s": 28701,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 28914,
"s": 28800,
"text": "Example 2: Now write down the following code in the App.js file. Here, we have shown a spinner without grow type."
},
{
"code": null,
"e": 28921,
"s": 28914,
"text": "App.js"
},
{
"code": "import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Spinner } from \"reactstrap\" function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Reactstrap Spinner Component</h4> <Spinner style={{ width: '2rem', height: '2rem' }} children={false} /> </div> );} export default App;",
"e": 29340,
"s": 28921,
"text": null
},
{
"code": null,
"e": 29453,
"s": 29340,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 29463,
"s": 29453,
"text": "npm start"
},
{
"code": null,
"e": 29562,
"s": 29463,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 29623,
"s": 29562,
"text": "Reference: https://reactstrap.github.io/components/spinners/"
},
{
"code": null,
"e": 29634,
"s": 29623,
"text": "Reactstrap"
},
{
"code": null,
"e": 29645,
"s": 29634,
"text": "JavaScript"
},
{
"code": null,
"e": 29653,
"s": 29645,
"text": "ReactJS"
},
{
"code": null,
"e": 29670,
"s": 29653,
"text": "Web Technologies"
},
{
"code": null,
"e": 29768,
"s": 29670,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29808,
"s": 29768,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29869,
"s": 29808,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29910,
"s": 29869,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 29932,
"s": 29910,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 29986,
"s": 29932,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 30029,
"s": 29986,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 30074,
"s": 30029,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 30139,
"s": 30074,
"text": "How to pass data from child component to its parent in ReactJS ?"
},
{
"code": null,
"e": 30207,
"s": 30139,
"text": "How to pass data from one component to other component in ReactJS ?"
}
] |
Find difference between sums of two diagonals - GeeksforGeeks
|
28 Apr, 2022
Given a matrix of n X n. The task is to calculate the absolute difference between the sums of its diagonal.Examples:
Input : mat[][] = 11 2 4
4 5 6
10 8 -12
Output : 15
Sum of primary diagonal = 11 + 5 + (-12) = 4.
Sum of secondary diagonal = 4 + 5 + 10 = 19.
Difference = |19 - 4| = 15.
Input : mat[][] = 10 2
4 5
Output : 7
Calculate the sums across the two diagonals of a square matrix. Along the first diagonal of the matrix, row index = column index i.e mat[i][j] lies on the first diagonal if i = j. Along the other diagonal, row index = n – 1 – column index i.e mat[i][j] lies on the second diagonal if i = n-1-j. By using two loops we traverse the entire matrix and calculate the sum across the diagonals of the matrix.Below is the implementation of this approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find the difference// between the sum of diagonal.#include <bits/stdc++.h>#define MAX 100using namespace std; int difference(int arr[][MAX], int n){ // Initialize sums of diagonals int d1 = 0, d2 = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // finding sum of primary diagonal if (i == j) d1 += arr[i][j]; // finding sum of secondary diagonal if (i == n - j - 1) d2 += arr[i][j]; } } // Absolute difference of the sums // across the diagonals return abs(d1 - d2);} // Driven Programint main(){ int n = 3; int arr[][MAX] = { {11, 2, 4}, {4 , 5, 6}, {10, 8, -12} }; cout << difference(arr, n); return 0;}
// JAVA Code for Find difference between sums// of two diagonalsclass GFG { public static int difference(int arr[][], int n) { // Initialize sums of diagonals int d1 = 0, d2 = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // finding sum of primary diagonal if (i == j) d1 += arr[i][j]; // finding sum of secondary diagonal if (i == n - j - 1) d2 += arr[i][j]; } } // Absolute difference of the sums // across the diagonals return Math.abs(d1 - d2); } /* Driver program to test above function */ public static void main(String[] args) { int n = 3; int arr[][] = { {11, 2, 4}, {4 , 5, 6}, {10, 8, -12} }; System.out.print(difference(arr, n)); } }// This code is contributed by Arnav Kr. Mandal.
# Python3 program to find the difference# between the sum of diagonal.def difference(arr, n): # Initialize sums of diagonals d1 = 0 d2 = 0 for i in range(0, n): for j in range(0, n): # finding sum of primary diagonal if (i == j): d1 += arr[i][j] # finding sum of secondary diagonal if (i == n - j - 1): d2 += arr[i][j] # Absolute difference of the sums # across the diagonals return abs(d1 - d2); # Driver Coden = 3 arr = [[11, 2, 4], [4 , 5, 6], [10, 8, -12]] print(difference(arr, n)) # This code is contributed# by ihritik
// C# Code for find difference between// sums of two diagonalsusing System; public class GFG{ // Function to calculate difference public static int difference(int[,] arr, int n) { // Initialize sums of diagonals int d1 = 0, d2 = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // finding sum of primary diagonal if (i == j) d1 += arr[i, j]; // finding sum of secondary diagonal if (i == n - j - 1) d2 += arr[i, j]; } } // Absolute difference of the // sums across the diagonals return Math.Abs(d1 - d2); } // Driver Code public static void Main() { int n = 3; int[,] arr ={{11, 2, 4}, {4 , 5, 6}, {10, 8, -12}}; Console.Write(difference(arr, n)); }} // This code is contributed by shiv_bhakt.
<?php// PHP program to find the difference// between the sum of diagonal. function difference($arr, $n){ // Initialize sums of diagonals $d1 = 0; $d2 = 0; for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) { // finding sum of // primary diagonal if ($i == $j) $d1 += $arr[$i][$j]; // finding sum of // secondary diagonal if ($i == $n - $j - 1) $d2 += $arr[$i][$j]; } } // Absolute difference of the sums // across the diagonals return abs($d1 - $d2);} // Driver Code{ $n = 3; $arr = array(array(11, 2, 4), array(4 , 5, 6), array(10, 8, -12)); echo difference($arr, $n); return 0;} // This code is contributed by nitin mittal.?>
<script> // Javascript Code for Find difference between sums// of two diagonals function difference(arr,n) { // Initialize sums of diagonals let d1 = 0, d2 = 0; for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { // finding sum of primary diagonal if (i == j) d1 += arr[i][j]; // finding sum of secondary diagonal if (i == n - j - 1) d2 += arr[i][j]; } } // Absolute difference of the sums // across the diagonals return Math.abs(d1 - d2); } /* Driver program to test above function */ let n = 3; let arr = [ [11, 2, 4], [4 , 5, 6], [10, 8, -12] ]; document.write(difference(arr, n)); // This code is contributed Bobby </script>
Output:
15
Time complexity: O(n*n)We can optimize the above solution to work in O(n) using the patterns present in indexes of cells.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find the difference// between the sum of diagonal.#include <bits/stdc++.h>#define MAX 100using namespace std; int difference(int arr[][MAX], int n){ // Initialize sums of diagonals int d1 = 0, d2 = 0; for (int i = 0; i < n; i++) { d1 += arr[i][i]; d2 += arr[i][n-i-1]; } // Absolute difference of the sums // across the diagonals return abs(d1 - d2);} // Driven Programint main(){ int n = 3; int arr[][MAX] = { {11, 2, 4}, {4 , 5, 6}, {10, 8, -12} }; cout << difference(arr, n); return 0;}
// JAVA Code for Find difference between sums// of two diagonals class GFG { public static int difference(int arr[][], int n) { // Initialize sums of diagonals int d1 = 0, d2 = 0; for (int i = 0; i < n; i++) { d1 += arr[i][i]; d2 += arr[i][n-i-1]; } // Absolute difference of the sums // across the diagonals return Math.abs(d1 - d2); } /* Driver program to test above function */ public static void main(String[] args) { int n = 3; int arr[][] = { {11, 2, 4}, {4 , 5, 6}, {10, 8, -12} }; System.out.print(difference(arr, n)); } }// This code is contributed by Arnav Kr. Mandal.
# Python3 program to find the difference# between the sum of diagonal.def difference(arr, n): # Initialize sums of diagonals d1 = 0 d2 = 0 for i in range(0, n): d1 = d1 + arr[i][i] d2 = d2 + arr[i][n - i - 1] # Absolute difference of the sums # across the diagonals return abs(d1 - d2) # Driver Coden = 3 arr = [[11, 2, 4], [4 , 5, 6], [10, 8, -12]] print(difference(arr, n)) # This code is contributed# by ihritik
// C# Code for find difference between// sums of two diagonalsusing System; public class GFG { //Function to find difference public static int difference(int[,] arr, int n) { // Initialize sums of diagonals int d1 = 0, d2 = 0; for (int i = 0; i < n; i++) { d1 += arr[i, i]; d2 += arr[i, n - i - 1]; } // Absolute difference of the sums // across the diagonals return Math.Abs(d1 - d2); } // Driver Code public static void Main() { int n = 3; int[,] arr ={{11, 2, 4}, {4 , 5, 6}, {10, 8, -12}}; Console.Write(difference(arr, n)); }} // This code is contributed by shiv_bhakt.
<?php// PHP program to find the difference// between the sum of diagonal. function difference($arr, $n){ // Initialize sums of diagonals $d1 = 0; $d2 = 0; for ($i = 0; $i < $n; $i++) { $d1 += $arr[$i][$i]; $d2 += $arr[$i][$n-$i-1]; } // Absolute difference of the sums // across the diagonals return abs($d1 - $d2);} // Driver Code{ $n = 3; $arr =array(array(11, 2, 4), array(4, 5, 6), array(10, 8, -12)); echo difference($arr, $n); return 0;} // This code is contributed by nitin mittal.?>
<script>// JAVA SCRIPT Code for Find difference between sums// of two diagonals function difference(arr,n) { // Initialize sums of diagonals let d1 = 0, d2 = 0; for (let i = 0; i < n; i++) { d1 += arr[i][i]; d2 += arr[i][n-i-1]; } // Absolute difference of the sums // across the diagonals return Math.abs(d1 - d2); } /* Driver program to test above function */ let n = 3; let arr = [[11, 2, 4], [4 , 5, 6], [10, 8, -12]]; document.write(difference(arr, n)); // This code is contributed by sravan kumar Gottumukkala</script>
Output:
15
Time complexity : O(n)This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Vishal_Khoda
nitin mittal
ihritik
gottumukkalabobby
sravankumar8128
senkottuvelan
Matrix
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum size square sub-matrix with all 1s
Sudoku | Backtracking-7
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Maximum size rectangle binary sub-matrix with all 1s
Program to multiply two matrices
Inplace rotate square matrix by 90 degrees | Set 1
Min Cost Path | DP-6
Rotate a matrix by 90 degree in clockwise direction without using any extra space
The Celebrity Problem
Python program to multiply two matrices
|
[
{
"code": null,
"e": 26262,
"s": 26234,
"text": "\n28 Apr, 2022"
},
{
"code": null,
"e": 26381,
"s": 26262,
"text": "Given a matrix of n X n. The task is to calculate the absolute difference between the sums of its diagonal.Examples: "
},
{
"code": null,
"e": 26649,
"s": 26381,
"text": "Input : mat[][] = 11 2 4\n 4 5 6\n 10 8 -12 \nOutput : 15\nSum of primary diagonal = 11 + 5 + (-12) = 4.\nSum of secondary diagonal = 4 + 5 + 10 = 19.\nDifference = |19 - 4| = 15.\n\n\nInput : mat[][] = 10 2\n 4 5\nOutput : 7"
},
{
"code": null,
"e": 27100,
"s": 26651,
"text": "Calculate the sums across the two diagonals of a square matrix. Along the first diagonal of the matrix, row index = column index i.e mat[i][j] lies on the first diagonal if i = j. Along the other diagonal, row index = n – 1 – column index i.e mat[i][j] lies on the second diagonal if i = n-1-j. By using two loops we traverse the entire matrix and calculate the sum across the diagonals of the matrix.Below is the implementation of this approach: "
},
{
"code": null,
"e": 27104,
"s": 27100,
"text": "C++"
},
{
"code": null,
"e": 27109,
"s": 27104,
"text": "Java"
},
{
"code": null,
"e": 27117,
"s": 27109,
"text": "Python3"
},
{
"code": null,
"e": 27120,
"s": 27117,
"text": "C#"
},
{
"code": null,
"e": 27124,
"s": 27120,
"text": "PHP"
},
{
"code": null,
"e": 27135,
"s": 27124,
"text": "Javascript"
},
{
"code": "// C++ program to find the difference// between the sum of diagonal.#include <bits/stdc++.h>#define MAX 100using namespace std; int difference(int arr[][MAX], int n){ // Initialize sums of diagonals int d1 = 0, d2 = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // finding sum of primary diagonal if (i == j) d1 += arr[i][j]; // finding sum of secondary diagonal if (i == n - j - 1) d2 += arr[i][j]; } } // Absolute difference of the sums // across the diagonals return abs(d1 - d2);} // Driven Programint main(){ int n = 3; int arr[][MAX] = { {11, 2, 4}, {4 , 5, 6}, {10, 8, -12} }; cout << difference(arr, n); return 0;}",
"e": 27938,
"s": 27135,
"text": null
},
{
"code": "// JAVA Code for Find difference between sums// of two diagonalsclass GFG { public static int difference(int arr[][], int n) { // Initialize sums of diagonals int d1 = 0, d2 = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // finding sum of primary diagonal if (i == j) d1 += arr[i][j]; // finding sum of secondary diagonal if (i == n - j - 1) d2 += arr[i][j]; } } // Absolute difference of the sums // across the diagonals return Math.abs(d1 - d2); } /* Driver program to test above function */ public static void main(String[] args) { int n = 3; int arr[][] = { {11, 2, 4}, {4 , 5, 6}, {10, 8, -12} }; System.out.print(difference(arr, n)); } }// This code is contributed by Arnav Kr. Mandal.",
"e": 28977,
"s": 27938,
"text": null
},
{
"code": "# Python3 program to find the difference# between the sum of diagonal.def difference(arr, n): # Initialize sums of diagonals d1 = 0 d2 = 0 for i in range(0, n): for j in range(0, n): # finding sum of primary diagonal if (i == j): d1 += arr[i][j] # finding sum of secondary diagonal if (i == n - j - 1): d2 += arr[i][j] # Absolute difference of the sums # across the diagonals return abs(d1 - d2); # Driver Coden = 3 arr = [[11, 2, 4], [4 , 5, 6], [10, 8, -12]] print(difference(arr, n)) # This code is contributed# by ihritik",
"e": 29647,
"s": 28977,
"text": null
},
{
"code": "// C# Code for find difference between// sums of two diagonalsusing System; public class GFG{ // Function to calculate difference public static int difference(int[,] arr, int n) { // Initialize sums of diagonals int d1 = 0, d2 = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // finding sum of primary diagonal if (i == j) d1 += arr[i, j]; // finding sum of secondary diagonal if (i == n - j - 1) d2 += arr[i, j]; } } // Absolute difference of the // sums across the diagonals return Math.Abs(d1 - d2); } // Driver Code public static void Main() { int n = 3; int[,] arr ={{11, 2, 4}, {4 , 5, 6}, {10, 8, -12}}; Console.Write(difference(arr, n)); }} // This code is contributed by shiv_bhakt.",
"e": 30729,
"s": 29647,
"text": null
},
{
"code": "<?php// PHP program to find the difference// between the sum of diagonal. function difference($arr, $n){ // Initialize sums of diagonals $d1 = 0; $d2 = 0; for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) { // finding sum of // primary diagonal if ($i == $j) $d1 += $arr[$i][$j]; // finding sum of // secondary diagonal if ($i == $n - $j - 1) $d2 += $arr[$i][$j]; } } // Absolute difference of the sums // across the diagonals return abs($d1 - $d2);} // Driver Code{ $n = 3; $arr = array(array(11, 2, 4), array(4 , 5, 6), array(10, 8, -12)); echo difference($arr, $n); return 0;} // This code is contributed by nitin mittal.?>",
"e": 31572,
"s": 30729,
"text": null
},
{
"code": "<script> // Javascript Code for Find difference between sums// of two diagonals function difference(arr,n) { // Initialize sums of diagonals let d1 = 0, d2 = 0; for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { // finding sum of primary diagonal if (i == j) d1 += arr[i][j]; // finding sum of secondary diagonal if (i == n - j - 1) d2 += arr[i][j]; } } // Absolute difference of the sums // across the diagonals return Math.abs(d1 - d2); } /* Driver program to test above function */ let n = 3; let arr = [ [11, 2, 4], [4 , 5, 6], [10, 8, -12] ]; document.write(difference(arr, n)); // This code is contributed Bobby </script>",
"e": 32516,
"s": 31572,
"text": null
},
{
"code": null,
"e": 32526,
"s": 32516,
"text": "Output: "
},
{
"code": null,
"e": 32529,
"s": 32526,
"text": "15"
},
{
"code": null,
"e": 32653,
"s": 32529,
"text": "Time complexity: O(n*n)We can optimize the above solution to work in O(n) using the patterns present in indexes of cells. "
},
{
"code": null,
"e": 32657,
"s": 32653,
"text": "C++"
},
{
"code": null,
"e": 32662,
"s": 32657,
"text": "Java"
},
{
"code": null,
"e": 32670,
"s": 32662,
"text": "Python3"
},
{
"code": null,
"e": 32673,
"s": 32670,
"text": "C#"
},
{
"code": null,
"e": 32677,
"s": 32673,
"text": "PHP"
},
{
"code": null,
"e": 32688,
"s": 32677,
"text": "Javascript"
},
{
"code": "// C++ program to find the difference// between the sum of diagonal.#include <bits/stdc++.h>#define MAX 100using namespace std; int difference(int arr[][MAX], int n){ // Initialize sums of diagonals int d1 = 0, d2 = 0; for (int i = 0; i < n; i++) { d1 += arr[i][i]; d2 += arr[i][n-i-1]; } // Absolute difference of the sums // across the diagonals return abs(d1 - d2);} // Driven Programint main(){ int n = 3; int arr[][MAX] = { {11, 2, 4}, {4 , 5, 6}, {10, 8, -12} }; cout << difference(arr, n); return 0;}",
"e": 33277,
"s": 32688,
"text": null
},
{
"code": "// JAVA Code for Find difference between sums// of two diagonals class GFG { public static int difference(int arr[][], int n) { // Initialize sums of diagonals int d1 = 0, d2 = 0; for (int i = 0; i < n; i++) { d1 += arr[i][i]; d2 += arr[i][n-i-1]; } // Absolute difference of the sums // across the diagonals return Math.abs(d1 - d2); } /* Driver program to test above function */ public static void main(String[] args) { int n = 3; int arr[][] = { {11, 2, 4}, {4 , 5, 6}, {10, 8, -12} }; System.out.print(difference(arr, n)); } }// This code is contributed by Arnav Kr. Mandal.",
"e": 34070,
"s": 33277,
"text": null
},
{
"code": "# Python3 program to find the difference# between the sum of diagonal.def difference(arr, n): # Initialize sums of diagonals d1 = 0 d2 = 0 for i in range(0, n): d1 = d1 + arr[i][i] d2 = d2 + arr[i][n - i - 1] # Absolute difference of the sums # across the diagonals return abs(d1 - d2) # Driver Coden = 3 arr = [[11, 2, 4], [4 , 5, 6], [10, 8, -12]] print(difference(arr, n)) # This code is contributed# by ihritik",
"e": 34547,
"s": 34070,
"text": null
},
{
"code": "// C# Code for find difference between// sums of two diagonalsusing System; public class GFG { //Function to find difference public static int difference(int[,] arr, int n) { // Initialize sums of diagonals int d1 = 0, d2 = 0; for (int i = 0; i < n; i++) { d1 += arr[i, i]; d2 += arr[i, n - i - 1]; } // Absolute difference of the sums // across the diagonals return Math.Abs(d1 - d2); } // Driver Code public static void Main() { int n = 3; int[,] arr ={{11, 2, 4}, {4 , 5, 6}, {10, 8, -12}}; Console.Write(difference(arr, n)); }} // This code is contributed by shiv_bhakt.",
"e": 35369,
"s": 34547,
"text": null
},
{
"code": "<?php// PHP program to find the difference// between the sum of diagonal. function difference($arr, $n){ // Initialize sums of diagonals $d1 = 0; $d2 = 0; for ($i = 0; $i < $n; $i++) { $d1 += $arr[$i][$i]; $d2 += $arr[$i][$n-$i-1]; } // Absolute difference of the sums // across the diagonals return abs($d1 - $d2);} // Driver Code{ $n = 3; $arr =array(array(11, 2, 4), array(4, 5, 6), array(10, 8, -12)); echo difference($arr, $n); return 0;} // This code is contributed by nitin mittal.?>",
"e": 35949,
"s": 35369,
"text": null
},
{
"code": "<script>// JAVA SCRIPT Code for Find difference between sums// of two diagonals function difference(arr,n) { // Initialize sums of diagonals let d1 = 0, d2 = 0; for (let i = 0; i < n; i++) { d1 += arr[i][i]; d2 += arr[i][n-i-1]; } // Absolute difference of the sums // across the diagonals return Math.abs(d1 - d2); } /* Driver program to test above function */ let n = 3; let arr = [[11, 2, 4], [4 , 5, 6], [10, 8, -12]]; document.write(difference(arr, n)); // This code is contributed by sravan kumar Gottumukkala</script>",
"e": 36651,
"s": 35949,
"text": null
},
{
"code": null,
"e": 36661,
"s": 36651,
"text": "Output: "
},
{
"code": null,
"e": 36664,
"s": 36661,
"text": "15"
},
{
"code": null,
"e": 37107,
"s": 36664,
"text": "Time complexity : O(n)This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 37120,
"s": 37107,
"text": "Vishal_Khoda"
},
{
"code": null,
"e": 37133,
"s": 37120,
"text": "nitin mittal"
},
{
"code": null,
"e": 37141,
"s": 37133,
"text": "ihritik"
},
{
"code": null,
"e": 37159,
"s": 37141,
"text": "gottumukkalabobby"
},
{
"code": null,
"e": 37175,
"s": 37159,
"text": "sravankumar8128"
},
{
"code": null,
"e": 37189,
"s": 37175,
"text": "senkottuvelan"
},
{
"code": null,
"e": 37196,
"s": 37189,
"text": "Matrix"
},
{
"code": null,
"e": 37203,
"s": 37196,
"text": "Matrix"
},
{
"code": null,
"e": 37301,
"s": 37203,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37344,
"s": 37301,
"text": "Maximum size square sub-matrix with all 1s"
},
{
"code": null,
"e": 37368,
"s": 37344,
"text": "Sudoku | Backtracking-7"
},
{
"code": null,
"e": 37430,
"s": 37368,
"text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)"
},
{
"code": null,
"e": 37483,
"s": 37430,
"text": "Maximum size rectangle binary sub-matrix with all 1s"
},
{
"code": null,
"e": 37516,
"s": 37483,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 37567,
"s": 37516,
"text": "Inplace rotate square matrix by 90 degrees | Set 1"
},
{
"code": null,
"e": 37588,
"s": 37567,
"text": "Min Cost Path | DP-6"
},
{
"code": null,
"e": 37670,
"s": 37588,
"text": "Rotate a matrix by 90 degree in clockwise direction without using any extra space"
},
{
"code": null,
"e": 37692,
"s": 37670,
"text": "The Celebrity Problem"
}
] |
Initializing a List in Java - GeeksforGeeks
|
13 May, 2022
The Java.util.List is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. List Interface is implemented by ArrayList, LinkedList, Vector and Stack classes.
List is an interface, and the instances of List can be created in the following ways:
List a = new ArrayList();
List b = new LinkedList();
List c = new Vector();
List d = new Stack();
Below are the following ways to initialize a list:
Using List.add() methodSince list is an interface, one can’t directly instantiate it. However, one can create objects of those classes which have implemented this interface and instantiate them.Few classes which have implemented the List interface are Stack, ArrayList, LinkedList, Vector etc.Syntax:List<Integer> list=new ArrayList<Integer>();
List<Integer> llist=new LinkedList<Integer>();
List<Integer> stack=new Stack<Integer>();
Examples:import java.util.*;import java.util.function.Supplier; public class GFG { public static void main(String args[]) { // For ArrayList List<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(3); System.out.println("ArrayList : " + list.toString()); // For LinkedList List<Integer> llist = new LinkedList<Integer>(); llist.add(2); llist.add(4); System.out.println("LinkedList : " + llist.toString()); // For Stack List<Integer> stack = new Stack<Integer>(); stack.add(3); stack.add(1); System.out.println("Stack : " + stack.toString()); }}Output:ArrayList : [1, 3]
LinkedList : [2, 4]
Stack : [3, 1]
Double Brace Initialization can also be used to do the above work.Syntax:List<Integer> list=new ArrayList<Integer>(){{
add(1);
add(2);
add(3);
}};
Examples:import java.util.*; public class GFG { public static void main(String args[]) { // For ArrayList List<Integer> list = new ArrayList<Integer>() {{ add(1); add(3); } }; System.out.println("ArrayList : " + list.toString()); // For LinkedList List<Integer> llist = new LinkedList<Integer>() {{ add(2); add(4); } }; System.out.println("LinkedList : " + llist.toString()); // For Stack List<Integer> stack = new Stack<Integer>() {{ add(3); add(1); } }; System.out.println("Stack : " + stack.toString()); }}Output:ArrayList : [1, 3]
LinkedList : [2, 4]
Stack : [3, 1]
Using Arrays.asList()Creating Immutable ListArrays.asList() creates an immutable list from an array. Hence it can be used to instantiate a list with an array.Syntax:List<Integer> list=Arrays.asList(1, 2, 3);Examples:import java.util.Arrays;import java.util.List; public class GFG { public static void main(String args[]) { // Instantiating List using Arrays.asList() List<Integer> list = Arrays.asList(1, 2, 3); // Print the list System.out.println("List : " + list.toString()); }}Output:List : [1, 2, 3]
Creating Mutable ListSyntax:List<Integer> list=new ArrayList<>(Arrays.asList(1, 2, 3));Examples:import java.util.ArrayList;import java.util.Arrays;import java.util.List; public class GFG { public static void main(String args[]) { // Creating a mutable list using Arrays.asList() List<Integer> list = new ArrayList<>( Arrays.asList(1, 2, 3)); // Print the list System.out.println("List : " + list.toString()); list.add(5); // Print the list System.out.println("Modified list : " + list.toString()); }}Output:List : [1, 2, 3]
Modified list : [1, 2, 3, 5]
Using Collections class methodsThere are various methods in Collections class that can be used to instantiate a list. They are:Using Collections.addAll()Collections class has a static method addAll() which can be used to initialize a list. Collections.addAll() take in any number of elements after it is specified with the Collection in which the elements are to be inserted.Syntax:List<Integer> list = Collections.EMPTY_LIST;
Collections.addAll(list = new ArrayList<Integer>(), 1, 2, 3, 4);
Examples:import java.util.*; public class GFG { public static void main(String args[]) { // Create an empty list List<Integer> list = new ArrayList<Integer>(); // Instantiating list using Collections.addAll() Collections.addAll(list, 1, 2, 3, 4); // Print the list System.out.println("List : " + list.toString()); }}Output:List : [1, 2, 3, 4]
Using Collections.unmodifiableList()Collections.unmodifiableList() returns a list which can’t be altered i.e. it can neither add or delete an element. Any attempt to modify the list will result in an UnsupportedOperationExample.Syntax:List<Integer> list = Collections
.unmodifiableList(Arrays.asList(1, 2, 3));
Example 1:import java.util.*; public class GFG { public static void main(String args[]) { // Creating the list List<Integer> list = Collections.unmodifiableList( Arrays.asList(1, 2, 3)); // Print the list System.out.println("List : " + list.toString()); }}Output:List : [1, 2, 3]
Example 2:import java.util.*; public class GFG { public static void main(String args[]) { try { // Creating the list List<Integer> list = Collections.unmodifiableList( Arrays.asList(1, 2, 3)); // Print the list System.out.println("List : " + list.toString()); // Trying to modify the list System.out.println("Trying to modify the list"); list.set(0, list.get(0)); } catch (Exception e) { System.out.println("Exception : " + e); } }}Output:List : [1, 2, 3]
Trying to modify the list
Exception : java.lang.UnsupportedOperationException
Using Collections.singletonList()Collections.singletonList() returns an immutable list consisting of one element only.Syntax:List<Integer> list = Collections.singletonList(2);Example 1:import java.util.*; public class GFG { public static void main(String args[]) { // Creating the list List<Integer> list = Collections.singletonList(2); // Print the list System.out.println("List : " + list.toString()); }}Output:List : [2]
Using Java 8 StreamWith the introduction of Stream and functional programming in Java 8, now one can construct any stream of objects and then collect them as a list.Syntax:1. List<Integer> list
= Stream.of(1, 2, 3)
.collect(Collectors.toList());
2. List<Integer> list
= Stream.of(1, 2, 3)
.collect(Collectors.toCollection(ArrayList::new));
3. List<Integer> list
= Stream.of(1, 2, 3, 4)
.collect(Collectors.collectingAndThen(Collectors.toList(),
Collections::unmodifiableList));
Examples:import java.util.*;import java.util.stream.Collectors;import java.util.stream.Stream; public class GFG { public static void main(String args[]) { // Creating a List using Syntax 1 List<Integer> list1 = Stream.of(1, 2, 3) .collect(Collectors.toList()); // Printing the list System.out.println("List using Syntax 1: " + list1.toString()); // Creating a List using Syntax 2 List<Integer> list2 = Stream .of(3, 2, 1) .collect( Collectors .toCollection(ArrayList::new)); // Printing the list System.out.println("List using Syntax 2: " + list2.toString()); // Creating a List using Syntax 3 List<Integer> list3 = Stream .of(1, 2, 3, 4) .collect( Collectors .collectingAndThen( Collectors.toList(), Collections::unmodifiableList)); // Printing the list System.out.println("List using Syntax 3: " + list3.toString()); }}Output:List using Syntax 1: [1, 2, 3]
List using Syntax 2: [3, 2, 1]
List using Syntax 3: [1, 2, 3, 4]
Using Java 9 List.of()Java 9 introduced List.of() method which takes in any number of arguments and constructs a compact and unmodifiable list out of them.Syntax:List<Integer> unmodifiableList = List.of(1, 2, 3);Examples:import java.util.List; public class GFG { public static void main(String args[]) { // Creating a list using List.of() List<Integer> unmodifiableList = List.of(1, 2, 3); // Printing the List System.out.println("List : " + unmodifiableList.toString()); }}OUTPUT:[1, 2, 3]
Using List.add() methodSince list is an interface, one can’t directly instantiate it. However, one can create objects of those classes which have implemented this interface and instantiate them.Few classes which have implemented the List interface are Stack, ArrayList, LinkedList, Vector etc.Syntax:List<Integer> list=new ArrayList<Integer>();
List<Integer> llist=new LinkedList<Integer>();
List<Integer> stack=new Stack<Integer>();
Examples:import java.util.*;import java.util.function.Supplier; public class GFG { public static void main(String args[]) { // For ArrayList List<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(3); System.out.println("ArrayList : " + list.toString()); // For LinkedList List<Integer> llist = new LinkedList<Integer>(); llist.add(2); llist.add(4); System.out.println("LinkedList : " + llist.toString()); // For Stack List<Integer> stack = new Stack<Integer>(); stack.add(3); stack.add(1); System.out.println("Stack : " + stack.toString()); }}Output:ArrayList : [1, 3]
LinkedList : [2, 4]
Stack : [3, 1]
Double Brace Initialization can also be used to do the above work.Syntax:List<Integer> list=new ArrayList<Integer>(){{
add(1);
add(2);
add(3);
}};
Examples:import java.util.*; public class GFG { public static void main(String args[]) { // For ArrayList List<Integer> list = new ArrayList<Integer>() {{ add(1); add(3); } }; System.out.println("ArrayList : " + list.toString()); // For LinkedList List<Integer> llist = new LinkedList<Integer>() {{ add(2); add(4); } }; System.out.println("LinkedList : " + llist.toString()); // For Stack List<Integer> stack = new Stack<Integer>() {{ add(3); add(1); } }; System.out.println("Stack : " + stack.toString()); }}Output:ArrayList : [1, 3]
LinkedList : [2, 4]
Stack : [3, 1]
Since list is an interface, one can’t directly instantiate it. However, one can create objects of those classes which have implemented this interface and instantiate them.
Few classes which have implemented the List interface are Stack, ArrayList, LinkedList, Vector etc.
Syntax:
List<Integer> list=new ArrayList<Integer>();
List<Integer> llist=new LinkedList<Integer>();
List<Integer> stack=new Stack<Integer>();
Examples:
import java.util.*;import java.util.function.Supplier; public class GFG { public static void main(String args[]) { // For ArrayList List<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(3); System.out.println("ArrayList : " + list.toString()); // For LinkedList List<Integer> llist = new LinkedList<Integer>(); llist.add(2); llist.add(4); System.out.println("LinkedList : " + llist.toString()); // For Stack List<Integer> stack = new Stack<Integer>(); stack.add(3); stack.add(1); System.out.println("Stack : " + stack.toString()); }}
ArrayList : [1, 3]
LinkedList : [2, 4]
Stack : [3, 1]
Double Brace Initialization can also be used to do the above work.
Syntax:
List<Integer> list=new ArrayList<Integer>(){{
add(1);
add(2);
add(3);
}};
Examples:
import java.util.*; public class GFG { public static void main(String args[]) { // For ArrayList List<Integer> list = new ArrayList<Integer>() {{ add(1); add(3); } }; System.out.println("ArrayList : " + list.toString()); // For LinkedList List<Integer> llist = new LinkedList<Integer>() {{ add(2); add(4); } }; System.out.println("LinkedList : " + llist.toString()); // For Stack List<Integer> stack = new Stack<Integer>() {{ add(3); add(1); } }; System.out.println("Stack : " + stack.toString()); }}
ArrayList : [1, 3]
LinkedList : [2, 4]
Stack : [3, 1]
Using Arrays.asList()Creating Immutable ListArrays.asList() creates an immutable list from an array. Hence it can be used to instantiate a list with an array.Syntax:List<Integer> list=Arrays.asList(1, 2, 3);Examples:import java.util.Arrays;import java.util.List; public class GFG { public static void main(String args[]) { // Instantiating List using Arrays.asList() List<Integer> list = Arrays.asList(1, 2, 3); // Print the list System.out.println("List : " + list.toString()); }}Output:List : [1, 2, 3]
Creating Mutable ListSyntax:List<Integer> list=new ArrayList<>(Arrays.asList(1, 2, 3));Examples:import java.util.ArrayList;import java.util.Arrays;import java.util.List; public class GFG { public static void main(String args[]) { // Creating a mutable list using Arrays.asList() List<Integer> list = new ArrayList<>( Arrays.asList(1, 2, 3)); // Print the list System.out.println("List : " + list.toString()); list.add(5); // Print the list System.out.println("Modified list : " + list.toString()); }}Output:List : [1, 2, 3]
Modified list : [1, 2, 3, 5]
Creating Immutable ListArrays.asList() creates an immutable list from an array. Hence it can be used to instantiate a list with an array.Syntax:List<Integer> list=Arrays.asList(1, 2, 3);Examples:import java.util.Arrays;import java.util.List; public class GFG { public static void main(String args[]) { // Instantiating List using Arrays.asList() List<Integer> list = Arrays.asList(1, 2, 3); // Print the list System.out.println("List : " + list.toString()); }}Output:List : [1, 2, 3]
Arrays.asList() creates an immutable list from an array. Hence it can be used to instantiate a list with an array.
Syntax:
List<Integer> list=Arrays.asList(1, 2, 3);
Examples:
import java.util.Arrays;import java.util.List; public class GFG { public static void main(String args[]) { // Instantiating List using Arrays.asList() List<Integer> list = Arrays.asList(1, 2, 3); // Print the list System.out.println("List : " + list.toString()); }}
List : [1, 2, 3]
Creating Mutable ListSyntax:List<Integer> list=new ArrayList<>(Arrays.asList(1, 2, 3));Examples:import java.util.ArrayList;import java.util.Arrays;import java.util.List; public class GFG { public static void main(String args[]) { // Creating a mutable list using Arrays.asList() List<Integer> list = new ArrayList<>( Arrays.asList(1, 2, 3)); // Print the list System.out.println("List : " + list.toString()); list.add(5); // Print the list System.out.println("Modified list : " + list.toString()); }}Output:List : [1, 2, 3]
Modified list : [1, 2, 3, 5]
Syntax:
List<Integer> list=new ArrayList<>(Arrays.asList(1, 2, 3));
Examples:
import java.util.ArrayList;import java.util.Arrays;import java.util.List; public class GFG { public static void main(String args[]) { // Creating a mutable list using Arrays.asList() List<Integer> list = new ArrayList<>( Arrays.asList(1, 2, 3)); // Print the list System.out.println("List : " + list.toString()); list.add(5); // Print the list System.out.println("Modified list : " + list.toString()); }}
List : [1, 2, 3]
Modified list : [1, 2, 3, 5]
Using Collections class methodsThere are various methods in Collections class that can be used to instantiate a list. They are:Using Collections.addAll()Collections class has a static method addAll() which can be used to initialize a list. Collections.addAll() take in any number of elements after it is specified with the Collection in which the elements are to be inserted.Syntax:List<Integer> list = Collections.EMPTY_LIST;
Collections.addAll(list = new ArrayList<Integer>(), 1, 2, 3, 4);
Examples:import java.util.*; public class GFG { public static void main(String args[]) { // Create an empty list List<Integer> list = new ArrayList<Integer>(); // Instantiating list using Collections.addAll() Collections.addAll(list, 1, 2, 3, 4); // Print the list System.out.println("List : " + list.toString()); }}Output:List : [1, 2, 3, 4]
Using Collections.unmodifiableList()Collections.unmodifiableList() returns a list which can’t be altered i.e. it can neither add or delete an element. Any attempt to modify the list will result in an UnsupportedOperationExample.Syntax:List<Integer> list = Collections
.unmodifiableList(Arrays.asList(1, 2, 3));
Example 1:import java.util.*; public class GFG { public static void main(String args[]) { // Creating the list List<Integer> list = Collections.unmodifiableList( Arrays.asList(1, 2, 3)); // Print the list System.out.println("List : " + list.toString()); }}Output:List : [1, 2, 3]
Example 2:import java.util.*; public class GFG { public static void main(String args[]) { try { // Creating the list List<Integer> list = Collections.unmodifiableList( Arrays.asList(1, 2, 3)); // Print the list System.out.println("List : " + list.toString()); // Trying to modify the list System.out.println("Trying to modify the list"); list.set(0, list.get(0)); } catch (Exception e) { System.out.println("Exception : " + e); } }}Output:List : [1, 2, 3]
Trying to modify the list
Exception : java.lang.UnsupportedOperationException
Using Collections.singletonList()Collections.singletonList() returns an immutable list consisting of one element only.Syntax:List<Integer> list = Collections.singletonList(2);Example 1:import java.util.*; public class GFG { public static void main(String args[]) { // Creating the list List<Integer> list = Collections.singletonList(2); // Print the list System.out.println("List : " + list.toString()); }}Output:List : [2]
There are various methods in Collections class that can be used to instantiate a list. They are:
Using Collections.addAll()Collections class has a static method addAll() which can be used to initialize a list. Collections.addAll() take in any number of elements after it is specified with the Collection in which the elements are to be inserted.Syntax:List<Integer> list = Collections.EMPTY_LIST;
Collections.addAll(list = new ArrayList<Integer>(), 1, 2, 3, 4);
Examples:import java.util.*; public class GFG { public static void main(String args[]) { // Create an empty list List<Integer> list = new ArrayList<Integer>(); // Instantiating list using Collections.addAll() Collections.addAll(list, 1, 2, 3, 4); // Print the list System.out.println("List : " + list.toString()); }}Output:List : [1, 2, 3, 4]
Using Collections.unmodifiableList()Collections.unmodifiableList() returns a list which can’t be altered i.e. it can neither add or delete an element. Any attempt to modify the list will result in an UnsupportedOperationExample.Syntax:List<Integer> list = Collections
.unmodifiableList(Arrays.asList(1, 2, 3));
Example 1:import java.util.*; public class GFG { public static void main(String args[]) { // Creating the list List<Integer> list = Collections.unmodifiableList( Arrays.asList(1, 2, 3)); // Print the list System.out.println("List : " + list.toString()); }}Output:List : [1, 2, 3]
Example 2:import java.util.*; public class GFG { public static void main(String args[]) { try { // Creating the list List<Integer> list = Collections.unmodifiableList( Arrays.asList(1, 2, 3)); // Print the list System.out.println("List : " + list.toString()); // Trying to modify the list System.out.println("Trying to modify the list"); list.set(0, list.get(0)); } catch (Exception e) { System.out.println("Exception : " + e); } }}Output:List : [1, 2, 3]
Trying to modify the list
Exception : java.lang.UnsupportedOperationException
Using Collections.singletonList()Collections.singletonList() returns an immutable list consisting of one element only.Syntax:List<Integer> list = Collections.singletonList(2);Example 1:import java.util.*; public class GFG { public static void main(String args[]) { // Creating the list List<Integer> list = Collections.singletonList(2); // Print the list System.out.println("List : " + list.toString()); }}Output:List : [2]
Using Collections.addAll()Collections class has a static method addAll() which can be used to initialize a list. Collections.addAll() take in any number of elements after it is specified with the Collection in which the elements are to be inserted.Syntax:List<Integer> list = Collections.EMPTY_LIST;
Collections.addAll(list = new ArrayList<Integer>(), 1, 2, 3, 4);
Examples:import java.util.*; public class GFG { public static void main(String args[]) { // Create an empty list List<Integer> list = new ArrayList<Integer>(); // Instantiating list using Collections.addAll() Collections.addAll(list, 1, 2, 3, 4); // Print the list System.out.println("List : " + list.toString()); }}Output:List : [1, 2, 3, 4]
Collections class has a static method addAll() which can be used to initialize a list. Collections.addAll() take in any number of elements after it is specified with the Collection in which the elements are to be inserted.
Syntax:
List<Integer> list = Collections.EMPTY_LIST;
Collections.addAll(list = new ArrayList<Integer>(), 1, 2, 3, 4);
Examples:
import java.util.*; public class GFG { public static void main(String args[]) { // Create an empty list List<Integer> list = new ArrayList<Integer>(); // Instantiating list using Collections.addAll() Collections.addAll(list, 1, 2, 3, 4); // Print the list System.out.println("List : " + list.toString()); }}
List : [1, 2, 3, 4]
Using Collections.unmodifiableList()Collections.unmodifiableList() returns a list which can’t be altered i.e. it can neither add or delete an element. Any attempt to modify the list will result in an UnsupportedOperationExample.Syntax:List<Integer> list = Collections
.unmodifiableList(Arrays.asList(1, 2, 3));
Example 1:import java.util.*; public class GFG { public static void main(String args[]) { // Creating the list List<Integer> list = Collections.unmodifiableList( Arrays.asList(1, 2, 3)); // Print the list System.out.println("List : " + list.toString()); }}Output:List : [1, 2, 3]
Example 2:import java.util.*; public class GFG { public static void main(String args[]) { try { // Creating the list List<Integer> list = Collections.unmodifiableList( Arrays.asList(1, 2, 3)); // Print the list System.out.println("List : " + list.toString()); // Trying to modify the list System.out.println("Trying to modify the list"); list.set(0, list.get(0)); } catch (Exception e) { System.out.println("Exception : " + e); } }}Output:List : [1, 2, 3]
Trying to modify the list
Exception : java.lang.UnsupportedOperationException
Collections.unmodifiableList() returns a list which can’t be altered i.e. it can neither add or delete an element. Any attempt to modify the list will result in an UnsupportedOperationExample.
Syntax:
List<Integer> list = Collections
.unmodifiableList(Arrays.asList(1, 2, 3));
Example 1:
import java.util.*; public class GFG { public static void main(String args[]) { // Creating the list List<Integer> list = Collections.unmodifiableList( Arrays.asList(1, 2, 3)); // Print the list System.out.println("List : " + list.toString()); }}
List : [1, 2, 3]
Example 2:
import java.util.*; public class GFG { public static void main(String args[]) { try { // Creating the list List<Integer> list = Collections.unmodifiableList( Arrays.asList(1, 2, 3)); // Print the list System.out.println("List : " + list.toString()); // Trying to modify the list System.out.println("Trying to modify the list"); list.set(0, list.get(0)); } catch (Exception e) { System.out.println("Exception : " + e); } }}
List : [1, 2, 3]
Trying to modify the list
Exception : java.lang.UnsupportedOperationException
Using Collections.singletonList()Collections.singletonList() returns an immutable list consisting of one element only.Syntax:List<Integer> list = Collections.singletonList(2);Example 1:import java.util.*; public class GFG { public static void main(String args[]) { // Creating the list List<Integer> list = Collections.singletonList(2); // Print the list System.out.println("List : " + list.toString()); }}Output:List : [2]
Collections.singletonList() returns an immutable list consisting of one element only.
Syntax:
List<Integer> list = Collections.singletonList(2);
Example 1:
import java.util.*; public class GFG { public static void main(String args[]) { // Creating the list List<Integer> list = Collections.singletonList(2); // Print the list System.out.println("List : " + list.toString()); }}
List : [2]
Using Java 8 StreamWith the introduction of Stream and functional programming in Java 8, now one can construct any stream of objects and then collect them as a list.Syntax:1. List<Integer> list
= Stream.of(1, 2, 3)
.collect(Collectors.toList());
2. List<Integer> list
= Stream.of(1, 2, 3)
.collect(Collectors.toCollection(ArrayList::new));
3. List<Integer> list
= Stream.of(1, 2, 3, 4)
.collect(Collectors.collectingAndThen(Collectors.toList(),
Collections::unmodifiableList));
Examples:import java.util.*;import java.util.stream.Collectors;import java.util.stream.Stream; public class GFG { public static void main(String args[]) { // Creating a List using Syntax 1 List<Integer> list1 = Stream.of(1, 2, 3) .collect(Collectors.toList()); // Printing the list System.out.println("List using Syntax 1: " + list1.toString()); // Creating a List using Syntax 2 List<Integer> list2 = Stream .of(3, 2, 1) .collect( Collectors .toCollection(ArrayList::new)); // Printing the list System.out.println("List using Syntax 2: " + list2.toString()); // Creating a List using Syntax 3 List<Integer> list3 = Stream .of(1, 2, 3, 4) .collect( Collectors .collectingAndThen( Collectors.toList(), Collections::unmodifiableList)); // Printing the list System.out.println("List using Syntax 3: " + list3.toString()); }}Output:List using Syntax 1: [1, 2, 3]
List using Syntax 2: [3, 2, 1]
List using Syntax 3: [1, 2, 3, 4]
With the introduction of Stream and functional programming in Java 8, now one can construct any stream of objects and then collect them as a list.
Syntax:
1. List<Integer> list
= Stream.of(1, 2, 3)
.collect(Collectors.toList());
2. List<Integer> list
= Stream.of(1, 2, 3)
.collect(Collectors.toCollection(ArrayList::new));
3. List<Integer> list
= Stream.of(1, 2, 3, 4)
.collect(Collectors.collectingAndThen(Collectors.toList(),
Collections::unmodifiableList));
Examples:
import java.util.*;import java.util.stream.Collectors;import java.util.stream.Stream; public class GFG { public static void main(String args[]) { // Creating a List using Syntax 1 List<Integer> list1 = Stream.of(1, 2, 3) .collect(Collectors.toList()); // Printing the list System.out.println("List using Syntax 1: " + list1.toString()); // Creating a List using Syntax 2 List<Integer> list2 = Stream .of(3, 2, 1) .collect( Collectors .toCollection(ArrayList::new)); // Printing the list System.out.println("List using Syntax 2: " + list2.toString()); // Creating a List using Syntax 3 List<Integer> list3 = Stream .of(1, 2, 3, 4) .collect( Collectors .collectingAndThen( Collectors.toList(), Collections::unmodifiableList)); // Printing the list System.out.println("List using Syntax 3: " + list3.toString()); }}
List using Syntax 1: [1, 2, 3]
List using Syntax 2: [3, 2, 1]
List using Syntax 3: [1, 2, 3, 4]
Using Java 9 List.of()Java 9 introduced List.of() method which takes in any number of arguments and constructs a compact and unmodifiable list out of them.Syntax:List<Integer> unmodifiableList = List.of(1, 2, 3);Examples:import java.util.List; public class GFG { public static void main(String args[]) { // Creating a list using List.of() List<Integer> unmodifiableList = List.of(1, 2, 3); // Printing the List System.out.println("List : " + unmodifiableList.toString()); }}OUTPUT:[1, 2, 3]
Java 9 introduced List.of() method which takes in any number of arguments and constructs a compact and unmodifiable list out of them.
Syntax:
List<Integer> unmodifiableList = List.of(1, 2, 3);
Examples:
import java.util.List; public class GFG { public static void main(String args[]) { // Creating a list using List.of() List<Integer> unmodifiableList = List.of(1, 2, 3); // Printing the List System.out.println("List : " + unmodifiableList.toString()); }}
OUTPUT:
[1, 2, 3]
chhabradhanvi
Java - util package
Java 8
java-basics
java-list
Java-List-Programs
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
Convert a String to Character Array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
|
[
{
"code": null,
"e": 26243,
"s": 26215,
"text": "\n13 May, 2022"
},
{
"code": null,
"e": 26557,
"s": 26243,
"text": "The Java.util.List is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. List Interface is implemented by ArrayList, LinkedList, Vector and Stack classes."
},
{
"code": null,
"e": 26643,
"s": 26557,
"text": "List is an interface, and the instances of List can be created in the following ways:"
},
{
"code": null,
"e": 26743,
"s": 26643,
"text": "List a = new ArrayList();\nList b = new LinkedList();\nList c = new Vector(); \nList d = new Stack(); "
},
{
"code": null,
"e": 26794,
"s": 26743,
"text": "Below are the following ways to initialize a list:"
},
{
"code": null,
"e": 35508,
"s": 26794,
"text": "Using List.add() methodSince list is an interface, one can’t directly instantiate it. However, one can create objects of those classes which have implemented this interface and instantiate them.Few classes which have implemented the List interface are Stack, ArrayList, LinkedList, Vector etc.Syntax:List<Integer> list=new ArrayList<Integer>();\nList<Integer> llist=new LinkedList<Integer>();\nList<Integer> stack=new Stack<Integer>();\nExamples:import java.util.*;import java.util.function.Supplier; public class GFG { public static void main(String args[]) { // For ArrayList List<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(3); System.out.println(\"ArrayList : \" + list.toString()); // For LinkedList List<Integer> llist = new LinkedList<Integer>(); llist.add(2); llist.add(4); System.out.println(\"LinkedList : \" + llist.toString()); // For Stack List<Integer> stack = new Stack<Integer>(); stack.add(3); stack.add(1); System.out.println(\"Stack : \" + stack.toString()); }}Output:ArrayList : [1, 3]\nLinkedList : [2, 4]\nStack : [3, 1]\nDouble Brace Initialization can also be used to do the above work.Syntax:List<Integer> list=new ArrayList<Integer>(){{\n add(1);\n add(2);\n add(3);\n }};\nExamples:import java.util.*; public class GFG { public static void main(String args[]) { // For ArrayList List<Integer> list = new ArrayList<Integer>() {{ add(1); add(3); } }; System.out.println(\"ArrayList : \" + list.toString()); // For LinkedList List<Integer> llist = new LinkedList<Integer>() {{ add(2); add(4); } }; System.out.println(\"LinkedList : \" + llist.toString()); // For Stack List<Integer> stack = new Stack<Integer>() {{ add(3); add(1); } }; System.out.println(\"Stack : \" + stack.toString()); }}Output:ArrayList : [1, 3]\nLinkedList : [2, 4]\nStack : [3, 1]\nUsing Arrays.asList()Creating Immutable ListArrays.asList() creates an immutable list from an array. Hence it can be used to instantiate a list with an array.Syntax:List<Integer> list=Arrays.asList(1, 2, 3);Examples:import java.util.Arrays;import java.util.List; public class GFG { public static void main(String args[]) { // Instantiating List using Arrays.asList() List<Integer> list = Arrays.asList(1, 2, 3); // Print the list System.out.println(\"List : \" + list.toString()); }}Output:List : [1, 2, 3]\nCreating Mutable ListSyntax:List<Integer> list=new ArrayList<>(Arrays.asList(1, 2, 3));Examples:import java.util.ArrayList;import java.util.Arrays;import java.util.List; public class GFG { public static void main(String args[]) { // Creating a mutable list using Arrays.asList() List<Integer> list = new ArrayList<>( Arrays.asList(1, 2, 3)); // Print the list System.out.println(\"List : \" + list.toString()); list.add(5); // Print the list System.out.println(\"Modified list : \" + list.toString()); }}Output:List : [1, 2, 3]\nModified list : [1, 2, 3, 5]\nUsing Collections class methodsThere are various methods in Collections class that can be used to instantiate a list. They are:Using Collections.addAll()Collections class has a static method addAll() which can be used to initialize a list. Collections.addAll() take in any number of elements after it is specified with the Collection in which the elements are to be inserted.Syntax:List<Integer> list = Collections.EMPTY_LIST;\nCollections.addAll(list = new ArrayList<Integer>(), 1, 2, 3, 4);\nExamples:import java.util.*; public class GFG { public static void main(String args[]) { // Create an empty list List<Integer> list = new ArrayList<Integer>(); // Instantiating list using Collections.addAll() Collections.addAll(list, 1, 2, 3, 4); // Print the list System.out.println(\"List : \" + list.toString()); }}Output:List : [1, 2, 3, 4]\nUsing Collections.unmodifiableList()Collections.unmodifiableList() returns a list which can’t be altered i.e. it can neither add or delete an element. Any attempt to modify the list will result in an UnsupportedOperationExample.Syntax:List<Integer> list = Collections\n .unmodifiableList(Arrays.asList(1, 2, 3));\nExample 1:import java.util.*; public class GFG { public static void main(String args[]) { // Creating the list List<Integer> list = Collections.unmodifiableList( Arrays.asList(1, 2, 3)); // Print the list System.out.println(\"List : \" + list.toString()); }}Output:List : [1, 2, 3]\nExample 2:import java.util.*; public class GFG { public static void main(String args[]) { try { // Creating the list List<Integer> list = Collections.unmodifiableList( Arrays.asList(1, 2, 3)); // Print the list System.out.println(\"List : \" + list.toString()); // Trying to modify the list System.out.println(\"Trying to modify the list\"); list.set(0, list.get(0)); } catch (Exception e) { System.out.println(\"Exception : \" + e); } }}Output:List : [1, 2, 3]\nTrying to modify the list\nException : java.lang.UnsupportedOperationException\nUsing Collections.singletonList()Collections.singletonList() returns an immutable list consisting of one element only.Syntax:List<Integer> list = Collections.singletonList(2);Example 1:import java.util.*; public class GFG { public static void main(String args[]) { // Creating the list List<Integer> list = Collections.singletonList(2); // Print the list System.out.println(\"List : \" + list.toString()); }}Output:List : [2]\nUsing Java 8 StreamWith the introduction of Stream and functional programming in Java 8, now one can construct any stream of objects and then collect them as a list.Syntax:1. List<Integer> list \n = Stream.of(1, 2, 3)\n .collect(Collectors.toList());\n2. List<Integer> list \n = Stream.of(1, 2, 3)\n .collect(Collectors.toCollection(ArrayList::new));\n3. List<Integer> list \n = Stream.of(1, 2, 3, 4)\n .collect(Collectors.collectingAndThen(Collectors.toList(), \n Collections::unmodifiableList));\nExamples:import java.util.*;import java.util.stream.Collectors;import java.util.stream.Stream; public class GFG { public static void main(String args[]) { // Creating a List using Syntax 1 List<Integer> list1 = Stream.of(1, 2, 3) .collect(Collectors.toList()); // Printing the list System.out.println(\"List using Syntax 1: \" + list1.toString()); // Creating a List using Syntax 2 List<Integer> list2 = Stream .of(3, 2, 1) .collect( Collectors .toCollection(ArrayList::new)); // Printing the list System.out.println(\"List using Syntax 2: \" + list2.toString()); // Creating a List using Syntax 3 List<Integer> list3 = Stream .of(1, 2, 3, 4) .collect( Collectors .collectingAndThen( Collectors.toList(), Collections::unmodifiableList)); // Printing the list System.out.println(\"List using Syntax 3: \" + list3.toString()); }}Output:List using Syntax 1: [1, 2, 3]\nList using Syntax 2: [3, 2, 1]\nList using Syntax 3: [1, 2, 3, 4]\nUsing Java 9 List.of()Java 9 introduced List.of() method which takes in any number of arguments and constructs a compact and unmodifiable list out of them.Syntax:List<Integer> unmodifiableList = List.of(1, 2, 3);Examples:import java.util.List; public class GFG { public static void main(String args[]) { // Creating a list using List.of() List<Integer> unmodifiableList = List.of(1, 2, 3); // Printing the List System.out.println(\"List : \" + unmodifiableList.toString()); }}OUTPUT:[1, 2, 3]\n"
},
{
"code": null,
"e": 37675,
"s": 35508,
"text": "Using List.add() methodSince list is an interface, one can’t directly instantiate it. However, one can create objects of those classes which have implemented this interface and instantiate them.Few classes which have implemented the List interface are Stack, ArrayList, LinkedList, Vector etc.Syntax:List<Integer> list=new ArrayList<Integer>();\nList<Integer> llist=new LinkedList<Integer>();\nList<Integer> stack=new Stack<Integer>();\nExamples:import java.util.*;import java.util.function.Supplier; public class GFG { public static void main(String args[]) { // For ArrayList List<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(3); System.out.println(\"ArrayList : \" + list.toString()); // For LinkedList List<Integer> llist = new LinkedList<Integer>(); llist.add(2); llist.add(4); System.out.println(\"LinkedList : \" + llist.toString()); // For Stack List<Integer> stack = new Stack<Integer>(); stack.add(3); stack.add(1); System.out.println(\"Stack : \" + stack.toString()); }}Output:ArrayList : [1, 3]\nLinkedList : [2, 4]\nStack : [3, 1]\nDouble Brace Initialization can also be used to do the above work.Syntax:List<Integer> list=new ArrayList<Integer>(){{\n add(1);\n add(2);\n add(3);\n }};\nExamples:import java.util.*; public class GFG { public static void main(String args[]) { // For ArrayList List<Integer> list = new ArrayList<Integer>() {{ add(1); add(3); } }; System.out.println(\"ArrayList : \" + list.toString()); // For LinkedList List<Integer> llist = new LinkedList<Integer>() {{ add(2); add(4); } }; System.out.println(\"LinkedList : \" + llist.toString()); // For Stack List<Integer> stack = new Stack<Integer>() {{ add(3); add(1); } }; System.out.println(\"Stack : \" + stack.toString()); }}Output:ArrayList : [1, 3]\nLinkedList : [2, 4]\nStack : [3, 1]\n"
},
{
"code": null,
"e": 37847,
"s": 37675,
"text": "Since list is an interface, one can’t directly instantiate it. However, one can create objects of those classes which have implemented this interface and instantiate them."
},
{
"code": null,
"e": 37947,
"s": 37847,
"text": "Few classes which have implemented the List interface are Stack, ArrayList, LinkedList, Vector etc."
},
{
"code": null,
"e": 37955,
"s": 37947,
"text": "Syntax:"
},
{
"code": null,
"e": 38090,
"s": 37955,
"text": "List<Integer> list=new ArrayList<Integer>();\nList<Integer> llist=new LinkedList<Integer>();\nList<Integer> stack=new Stack<Integer>();\n"
},
{
"code": null,
"e": 38100,
"s": 38090,
"text": "Examples:"
},
{
"code": "import java.util.*;import java.util.function.Supplier; public class GFG { public static void main(String args[]) { // For ArrayList List<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(3); System.out.println(\"ArrayList : \" + list.toString()); // For LinkedList List<Integer> llist = new LinkedList<Integer>(); llist.add(2); llist.add(4); System.out.println(\"LinkedList : \" + llist.toString()); // For Stack List<Integer> stack = new Stack<Integer>(); stack.add(3); stack.add(1); System.out.println(\"Stack : \" + stack.toString()); }}",
"e": 38770,
"s": 38100,
"text": null
},
{
"code": null,
"e": 38825,
"s": 38770,
"text": "ArrayList : [1, 3]\nLinkedList : [2, 4]\nStack : [3, 1]\n"
},
{
"code": null,
"e": 38892,
"s": 38825,
"text": "Double Brace Initialization can also be used to do the above work."
},
{
"code": null,
"e": 38900,
"s": 38892,
"text": "Syntax:"
},
{
"code": null,
"e": 39073,
"s": 38900,
"text": "List<Integer> list=new ArrayList<Integer>(){{\n add(1);\n add(2);\n add(3);\n }};\n"
},
{
"code": null,
"e": 39083,
"s": 39073,
"text": "Examples:"
},
{
"code": "import java.util.*; public class GFG { public static void main(String args[]) { // For ArrayList List<Integer> list = new ArrayList<Integer>() {{ add(1); add(3); } }; System.out.println(\"ArrayList : \" + list.toString()); // For LinkedList List<Integer> llist = new LinkedList<Integer>() {{ add(2); add(4); } }; System.out.println(\"LinkedList : \" + llist.toString()); // For Stack List<Integer> stack = new Stack<Integer>() {{ add(3); add(1); } }; System.out.println(\"Stack : \" + stack.toString()); }}",
"e": 39762,
"s": 39083,
"text": null
},
{
"code": null,
"e": 39817,
"s": 39762,
"text": "ArrayList : [1, 3]\nLinkedList : [2, 4]\nStack : [3, 1]\n"
},
{
"code": null,
"e": 40996,
"s": 39817,
"text": "Using Arrays.asList()Creating Immutable ListArrays.asList() creates an immutable list from an array. Hence it can be used to instantiate a list with an array.Syntax:List<Integer> list=Arrays.asList(1, 2, 3);Examples:import java.util.Arrays;import java.util.List; public class GFG { public static void main(String args[]) { // Instantiating List using Arrays.asList() List<Integer> list = Arrays.asList(1, 2, 3); // Print the list System.out.println(\"List : \" + list.toString()); }}Output:List : [1, 2, 3]\nCreating Mutable ListSyntax:List<Integer> list=new ArrayList<>(Arrays.asList(1, 2, 3));Examples:import java.util.ArrayList;import java.util.Arrays;import java.util.List; public class GFG { public static void main(String args[]) { // Creating a mutable list using Arrays.asList() List<Integer> list = new ArrayList<>( Arrays.asList(1, 2, 3)); // Print the list System.out.println(\"List : \" + list.toString()); list.add(5); // Print the list System.out.println(\"Modified list : \" + list.toString()); }}Output:List : [1, 2, 3]\nModified list : [1, 2, 3, 5]\n"
},
{
"code": null,
"e": 41523,
"s": 40996,
"text": "Creating Immutable ListArrays.asList() creates an immutable list from an array. Hence it can be used to instantiate a list with an array.Syntax:List<Integer> list=Arrays.asList(1, 2, 3);Examples:import java.util.Arrays;import java.util.List; public class GFG { public static void main(String args[]) { // Instantiating List using Arrays.asList() List<Integer> list = Arrays.asList(1, 2, 3); // Print the list System.out.println(\"List : \" + list.toString()); }}Output:List : [1, 2, 3]\n"
},
{
"code": null,
"e": 41638,
"s": 41523,
"text": "Arrays.asList() creates an immutable list from an array. Hence it can be used to instantiate a list with an array."
},
{
"code": null,
"e": 41646,
"s": 41638,
"text": "Syntax:"
},
{
"code": null,
"e": 41689,
"s": 41646,
"text": "List<Integer> list=Arrays.asList(1, 2, 3);"
},
{
"code": null,
"e": 41699,
"s": 41689,
"text": "Examples:"
},
{
"code": "import java.util.Arrays;import java.util.List; public class GFG { public static void main(String args[]) { // Instantiating List using Arrays.asList() List<Integer> list = Arrays.asList(1, 2, 3); // Print the list System.out.println(\"List : \" + list.toString()); }}",
"e": 42007,
"s": 41699,
"text": null
},
{
"code": null,
"e": 42025,
"s": 42007,
"text": "List : [1, 2, 3]\n"
},
{
"code": null,
"e": 42657,
"s": 42025,
"text": "Creating Mutable ListSyntax:List<Integer> list=new ArrayList<>(Arrays.asList(1, 2, 3));Examples:import java.util.ArrayList;import java.util.Arrays;import java.util.List; public class GFG { public static void main(String args[]) { // Creating a mutable list using Arrays.asList() List<Integer> list = new ArrayList<>( Arrays.asList(1, 2, 3)); // Print the list System.out.println(\"List : \" + list.toString()); list.add(5); // Print the list System.out.println(\"Modified list : \" + list.toString()); }}Output:List : [1, 2, 3]\nModified list : [1, 2, 3, 5]\n"
},
{
"code": null,
"e": 42665,
"s": 42657,
"text": "Syntax:"
},
{
"code": null,
"e": 42725,
"s": 42665,
"text": "List<Integer> list=new ArrayList<>(Arrays.asList(1, 2, 3));"
},
{
"code": null,
"e": 42735,
"s": 42725,
"text": "Examples:"
},
{
"code": "import java.util.ArrayList;import java.util.Arrays;import java.util.List; public class GFG { public static void main(String args[]) { // Creating a mutable list using Arrays.asList() List<Integer> list = new ArrayList<>( Arrays.asList(1, 2, 3)); // Print the list System.out.println(\"List : \" + list.toString()); list.add(5); // Print the list System.out.println(\"Modified list : \" + list.toString()); }}",
"e": 43218,
"s": 42735,
"text": null
},
{
"code": null,
"e": 43265,
"s": 43218,
"text": "List : [1, 2, 3]\nModified list : [1, 2, 3, 5]\n"
},
{
"code": null,
"e": 45960,
"s": 43265,
"text": "Using Collections class methodsThere are various methods in Collections class that can be used to instantiate a list. They are:Using Collections.addAll()Collections class has a static method addAll() which can be used to initialize a list. Collections.addAll() take in any number of elements after it is specified with the Collection in which the elements are to be inserted.Syntax:List<Integer> list = Collections.EMPTY_LIST;\nCollections.addAll(list = new ArrayList<Integer>(), 1, 2, 3, 4);\nExamples:import java.util.*; public class GFG { public static void main(String args[]) { // Create an empty list List<Integer> list = new ArrayList<Integer>(); // Instantiating list using Collections.addAll() Collections.addAll(list, 1, 2, 3, 4); // Print the list System.out.println(\"List : \" + list.toString()); }}Output:List : [1, 2, 3, 4]\nUsing Collections.unmodifiableList()Collections.unmodifiableList() returns a list which can’t be altered i.e. it can neither add or delete an element. Any attempt to modify the list will result in an UnsupportedOperationExample.Syntax:List<Integer> list = Collections\n .unmodifiableList(Arrays.asList(1, 2, 3));\nExample 1:import java.util.*; public class GFG { public static void main(String args[]) { // Creating the list List<Integer> list = Collections.unmodifiableList( Arrays.asList(1, 2, 3)); // Print the list System.out.println(\"List : \" + list.toString()); }}Output:List : [1, 2, 3]\nExample 2:import java.util.*; public class GFG { public static void main(String args[]) { try { // Creating the list List<Integer> list = Collections.unmodifiableList( Arrays.asList(1, 2, 3)); // Print the list System.out.println(\"List : \" + list.toString()); // Trying to modify the list System.out.println(\"Trying to modify the list\"); list.set(0, list.get(0)); } catch (Exception e) { System.out.println(\"Exception : \" + e); } }}Output:List : [1, 2, 3]\nTrying to modify the list\nException : java.lang.UnsupportedOperationException\nUsing Collections.singletonList()Collections.singletonList() returns an immutable list consisting of one element only.Syntax:List<Integer> list = Collections.singletonList(2);Example 1:import java.util.*; public class GFG { public static void main(String args[]) { // Creating the list List<Integer> list = Collections.singletonList(2); // Print the list System.out.println(\"List : \" + list.toString()); }}Output:List : [2]\n"
},
{
"code": null,
"e": 46057,
"s": 45960,
"text": "There are various methods in Collections class that can be used to instantiate a list. They are:"
},
{
"code": null,
"e": 48625,
"s": 46057,
"text": "Using Collections.addAll()Collections class has a static method addAll() which can be used to initialize a list. Collections.addAll() take in any number of elements after it is specified with the Collection in which the elements are to be inserted.Syntax:List<Integer> list = Collections.EMPTY_LIST;\nCollections.addAll(list = new ArrayList<Integer>(), 1, 2, 3, 4);\nExamples:import java.util.*; public class GFG { public static void main(String args[]) { // Create an empty list List<Integer> list = new ArrayList<Integer>(); // Instantiating list using Collections.addAll() Collections.addAll(list, 1, 2, 3, 4); // Print the list System.out.println(\"List : \" + list.toString()); }}Output:List : [1, 2, 3, 4]\nUsing Collections.unmodifiableList()Collections.unmodifiableList() returns a list which can’t be altered i.e. it can neither add or delete an element. Any attempt to modify the list will result in an UnsupportedOperationExample.Syntax:List<Integer> list = Collections\n .unmodifiableList(Arrays.asList(1, 2, 3));\nExample 1:import java.util.*; public class GFG { public static void main(String args[]) { // Creating the list List<Integer> list = Collections.unmodifiableList( Arrays.asList(1, 2, 3)); // Print the list System.out.println(\"List : \" + list.toString()); }}Output:List : [1, 2, 3]\nExample 2:import java.util.*; public class GFG { public static void main(String args[]) { try { // Creating the list List<Integer> list = Collections.unmodifiableList( Arrays.asList(1, 2, 3)); // Print the list System.out.println(\"List : \" + list.toString()); // Trying to modify the list System.out.println(\"Trying to modify the list\"); list.set(0, list.get(0)); } catch (Exception e) { System.out.println(\"Exception : \" + e); } }}Output:List : [1, 2, 3]\nTrying to modify the list\nException : java.lang.UnsupportedOperationException\nUsing Collections.singletonList()Collections.singletonList() returns an immutable list consisting of one element only.Syntax:List<Integer> list = Collections.singletonList(2);Example 1:import java.util.*; public class GFG { public static void main(String args[]) { // Creating the list List<Integer> list = Collections.singletonList(2); // Print the list System.out.println(\"List : \" + list.toString()); }}Output:List : [2]\n"
},
{
"code": null,
"e": 49392,
"s": 48625,
"text": "Using Collections.addAll()Collections class has a static method addAll() which can be used to initialize a list. Collections.addAll() take in any number of elements after it is specified with the Collection in which the elements are to be inserted.Syntax:List<Integer> list = Collections.EMPTY_LIST;\nCollections.addAll(list = new ArrayList<Integer>(), 1, 2, 3, 4);\nExamples:import java.util.*; public class GFG { public static void main(String args[]) { // Create an empty list List<Integer> list = new ArrayList<Integer>(); // Instantiating list using Collections.addAll() Collections.addAll(list, 1, 2, 3, 4); // Print the list System.out.println(\"List : \" + list.toString()); }}Output:List : [1, 2, 3, 4]\n"
},
{
"code": null,
"e": 49615,
"s": 49392,
"text": "Collections class has a static method addAll() which can be used to initialize a list. Collections.addAll() take in any number of elements after it is specified with the Collection in which the elements are to be inserted."
},
{
"code": null,
"e": 49623,
"s": 49615,
"text": "Syntax:"
},
{
"code": null,
"e": 49734,
"s": 49623,
"text": "List<Integer> list = Collections.EMPTY_LIST;\nCollections.addAll(list = new ArrayList<Integer>(), 1, 2, 3, 4);\n"
},
{
"code": null,
"e": 49744,
"s": 49734,
"text": "Examples:"
},
{
"code": "import java.util.*; public class GFG { public static void main(String args[]) { // Create an empty list List<Integer> list = new ArrayList<Integer>(); // Instantiating list using Collections.addAll() Collections.addAll(list, 1, 2, 3, 4); // Print the list System.out.println(\"List : \" + list.toString()); }}",
"e": 50110,
"s": 49744,
"text": null
},
{
"code": null,
"e": 50131,
"s": 50110,
"text": "List : [1, 2, 3, 4]\n"
},
{
"code": null,
"e": 51467,
"s": 50131,
"text": "Using Collections.unmodifiableList()Collections.unmodifiableList() returns a list which can’t be altered i.e. it can neither add or delete an element. Any attempt to modify the list will result in an UnsupportedOperationExample.Syntax:List<Integer> list = Collections\n .unmodifiableList(Arrays.asList(1, 2, 3));\nExample 1:import java.util.*; public class GFG { public static void main(String args[]) { // Creating the list List<Integer> list = Collections.unmodifiableList( Arrays.asList(1, 2, 3)); // Print the list System.out.println(\"List : \" + list.toString()); }}Output:List : [1, 2, 3]\nExample 2:import java.util.*; public class GFG { public static void main(String args[]) { try { // Creating the list List<Integer> list = Collections.unmodifiableList( Arrays.asList(1, 2, 3)); // Print the list System.out.println(\"List : \" + list.toString()); // Trying to modify the list System.out.println(\"Trying to modify the list\"); list.set(0, list.get(0)); } catch (Exception e) { System.out.println(\"Exception : \" + e); } }}Output:List : [1, 2, 3]\nTrying to modify the list\nException : java.lang.UnsupportedOperationException\n"
},
{
"code": null,
"e": 51660,
"s": 51467,
"text": "Collections.unmodifiableList() returns a list which can’t be altered i.e. it can neither add or delete an element. Any attempt to modify the list will result in an UnsupportedOperationExample."
},
{
"code": null,
"e": 51668,
"s": 51660,
"text": "Syntax:"
},
{
"code": null,
"e": 51753,
"s": 51668,
"text": "List<Integer> list = Collections\n .unmodifiableList(Arrays.asList(1, 2, 3));\n"
},
{
"code": null,
"e": 51764,
"s": 51753,
"text": "Example 1:"
},
{
"code": "import java.util.*; public class GFG { public static void main(String args[]) { // Creating the list List<Integer> list = Collections.unmodifiableList( Arrays.asList(1, 2, 3)); // Print the list System.out.println(\"List : \" + list.toString()); }}",
"e": 52064,
"s": 51764,
"text": null
},
{
"code": null,
"e": 52082,
"s": 52064,
"text": "List : [1, 2, 3]\n"
},
{
"code": null,
"e": 52093,
"s": 52082,
"text": "Example 2:"
},
{
"code": "import java.util.*; public class GFG { public static void main(String args[]) { try { // Creating the list List<Integer> list = Collections.unmodifiableList( Arrays.asList(1, 2, 3)); // Print the list System.out.println(\"List : \" + list.toString()); // Trying to modify the list System.out.println(\"Trying to modify the list\"); list.set(0, list.get(0)); } catch (Exception e) { System.out.println(\"Exception : \" + e); } }}",
"e": 52665,
"s": 52093,
"text": null
},
{
"code": null,
"e": 52761,
"s": 52665,
"text": "List : [1, 2, 3]\nTrying to modify the list\nException : java.lang.UnsupportedOperationException\n"
},
{
"code": null,
"e": 53228,
"s": 52761,
"text": "Using Collections.singletonList()Collections.singletonList() returns an immutable list consisting of one element only.Syntax:List<Integer> list = Collections.singletonList(2);Example 1:import java.util.*; public class GFG { public static void main(String args[]) { // Creating the list List<Integer> list = Collections.singletonList(2); // Print the list System.out.println(\"List : \" + list.toString()); }}Output:List : [2]\n"
},
{
"code": null,
"e": 53314,
"s": 53228,
"text": "Collections.singletonList() returns an immutable list consisting of one element only."
},
{
"code": null,
"e": 53322,
"s": 53314,
"text": "Syntax:"
},
{
"code": null,
"e": 53373,
"s": 53322,
"text": "List<Integer> list = Collections.singletonList(2);"
},
{
"code": null,
"e": 53384,
"s": 53373,
"text": "Example 1:"
},
{
"code": "import java.util.*; public class GFG { public static void main(String args[]) { // Creating the list List<Integer> list = Collections.singletonList(2); // Print the list System.out.println(\"List : \" + list.toString()); }}",
"e": 53648,
"s": 53384,
"text": null
},
{
"code": null,
"e": 53660,
"s": 53648,
"text": "List : [2]\n"
},
{
"code": null,
"e": 55777,
"s": 53660,
"text": "Using Java 8 StreamWith the introduction of Stream and functional programming in Java 8, now one can construct any stream of objects and then collect them as a list.Syntax:1. List<Integer> list \n = Stream.of(1, 2, 3)\n .collect(Collectors.toList());\n2. List<Integer> list \n = Stream.of(1, 2, 3)\n .collect(Collectors.toCollection(ArrayList::new));\n3. List<Integer> list \n = Stream.of(1, 2, 3, 4)\n .collect(Collectors.collectingAndThen(Collectors.toList(), \n Collections::unmodifiableList));\nExamples:import java.util.*;import java.util.stream.Collectors;import java.util.stream.Stream; public class GFG { public static void main(String args[]) { // Creating a List using Syntax 1 List<Integer> list1 = Stream.of(1, 2, 3) .collect(Collectors.toList()); // Printing the list System.out.println(\"List using Syntax 1: \" + list1.toString()); // Creating a List using Syntax 2 List<Integer> list2 = Stream .of(3, 2, 1) .collect( Collectors .toCollection(ArrayList::new)); // Printing the list System.out.println(\"List using Syntax 2: \" + list2.toString()); // Creating a List using Syntax 3 List<Integer> list3 = Stream .of(1, 2, 3, 4) .collect( Collectors .collectingAndThen( Collectors.toList(), Collections::unmodifiableList)); // Printing the list System.out.println(\"List using Syntax 3: \" + list3.toString()); }}Output:List using Syntax 1: [1, 2, 3]\nList using Syntax 2: [3, 2, 1]\nList using Syntax 3: [1, 2, 3, 4]\n"
},
{
"code": null,
"e": 55924,
"s": 55777,
"text": "With the introduction of Stream and functional programming in Java 8, now one can construct any stream of objects and then collect them as a list."
},
{
"code": null,
"e": 55932,
"s": 55924,
"text": "Syntax:"
},
{
"code": null,
"e": 56358,
"s": 55932,
"text": "1. List<Integer> list \n = Stream.of(1, 2, 3)\n .collect(Collectors.toList());\n2. List<Integer> list \n = Stream.of(1, 2, 3)\n .collect(Collectors.toCollection(ArrayList::new));\n3. List<Integer> list \n = Stream.of(1, 2, 3, 4)\n .collect(Collectors.collectingAndThen(Collectors.toList(), \n Collections::unmodifiableList));\n"
},
{
"code": null,
"e": 56368,
"s": 56358,
"text": "Examples:"
},
{
"code": "import java.util.*;import java.util.stream.Collectors;import java.util.stream.Stream; public class GFG { public static void main(String args[]) { // Creating a List using Syntax 1 List<Integer> list1 = Stream.of(1, 2, 3) .collect(Collectors.toList()); // Printing the list System.out.println(\"List using Syntax 1: \" + list1.toString()); // Creating a List using Syntax 2 List<Integer> list2 = Stream .of(3, 2, 1) .collect( Collectors .toCollection(ArrayList::new)); // Printing the list System.out.println(\"List using Syntax 2: \" + list2.toString()); // Creating a List using Syntax 3 List<Integer> list3 = Stream .of(1, 2, 3, 4) .collect( Collectors .collectingAndThen( Collectors.toList(), Collections::unmodifiableList)); // Printing the list System.out.println(\"List using Syntax 3: \" + list3.toString()); }}",
"e": 57776,
"s": 56368,
"text": null
},
{
"code": null,
"e": 57873,
"s": 57776,
"text": "List using Syntax 1: [1, 2, 3]\nList using Syntax 2: [3, 2, 1]\nList using Syntax 3: [1, 2, 3, 4]\n"
},
{
"code": null,
"e": 58433,
"s": 57873,
"text": "Using Java 9 List.of()Java 9 introduced List.of() method which takes in any number of arguments and constructs a compact and unmodifiable list out of them.Syntax:List<Integer> unmodifiableList = List.of(1, 2, 3);Examples:import java.util.List; public class GFG { public static void main(String args[]) { // Creating a list using List.of() List<Integer> unmodifiableList = List.of(1, 2, 3); // Printing the List System.out.println(\"List : \" + unmodifiableList.toString()); }}OUTPUT:[1, 2, 3]\n"
},
{
"code": null,
"e": 58567,
"s": 58433,
"text": "Java 9 introduced List.of() method which takes in any number of arguments and constructs a compact and unmodifiable list out of them."
},
{
"code": null,
"e": 58575,
"s": 58567,
"text": "Syntax:"
},
{
"code": null,
"e": 58626,
"s": 58575,
"text": "List<Integer> unmodifiableList = List.of(1, 2, 3);"
},
{
"code": null,
"e": 58636,
"s": 58626,
"text": "Examples:"
},
{
"code": "import java.util.List; public class GFG { public static void main(String args[]) { // Creating a list using List.of() List<Integer> unmodifiableList = List.of(1, 2, 3); // Printing the List System.out.println(\"List : \" + unmodifiableList.toString()); }}",
"e": 58958,
"s": 58636,
"text": null
},
{
"code": null,
"e": 58966,
"s": 58958,
"text": "OUTPUT:"
},
{
"code": null,
"e": 58977,
"s": 58966,
"text": "[1, 2, 3]\n"
},
{
"code": null,
"e": 58991,
"s": 58977,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 59011,
"s": 58991,
"text": "Java - util package"
},
{
"code": null,
"e": 59018,
"s": 59011,
"text": "Java 8"
},
{
"code": null,
"e": 59030,
"s": 59018,
"text": "java-basics"
},
{
"code": null,
"e": 59040,
"s": 59030,
"text": "java-list"
},
{
"code": null,
"e": 59059,
"s": 59040,
"text": "Java-List-Programs"
},
{
"code": null,
"e": 59064,
"s": 59059,
"text": "Java"
},
{
"code": null,
"e": 59078,
"s": 59064,
"text": "Java Programs"
},
{
"code": null,
"e": 59097,
"s": 59078,
"text": "Technical Scripter"
},
{
"code": null,
"e": 59102,
"s": 59097,
"text": "Java"
},
{
"code": null,
"e": 59200,
"s": 59102,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 59251,
"s": 59200,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 59281,
"s": 59251,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 59296,
"s": 59281,
"text": "Stream In Java"
},
{
"code": null,
"e": 59315,
"s": 59296,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 59346,
"s": 59315,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 59390,
"s": 59346,
"text": "Convert a String to Character Array in Java"
},
{
"code": null,
"e": 59416,
"s": 59390,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 59450,
"s": 59416,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 59497,
"s": 59450,
"text": "Implementing a Linked List in Java using Class"
}
] |
How to make a video call app in node.js ? - GeeksforGeeks
|
05 Jan, 2021
For making a video call app, It is required that each and every client send their video and audio stream to all the other clients. So for this purpose we are using Peer.js and for the communication between the clients and the server we are using WebSocket i.e. Socket.io.
Prerequisite:1. Node.js: It is an open-source JavaScript Back-End technology. It has a package manager called npm– Node package manager which installs different packages very easily.
2. Express.js: It is a node.js server framework.
3. Socket.io:It helps us to create a real-time bi-direction event-based communication between the server and the client.
4. Peer.js: It helps us to send and receive the audio and video streams of the other clients.
Setting up the Environment: This is the very first step, here we are creating and initializing a new repository.
$ mkdir VideoCallApp
$ cd VideoCallApp
$ npm init
Now, the next step is to install the required packages for our VideoCallApp.
Express : It is the server-based framework for node.js
ejs : It is a simple templating language that lets you generate HTML markup with plain JavaScript.
Socket.io : It manages the Websocket for event-based communication.
Nodemon (optional): It automatically restarts the server when you save your project files.
uuid module: This module is used to generate a unique id. This will be used in this project
Installing the required modules:
$ npm install express
$ npm install ejs
$ npm install socket.io
$ npm install nodemon
Now, we all set for the implementation part.
Implementation:
Step 1: Create a server file — server.js
JavaScript
// Importing express moduleconst express = require('express'); const app = express(); app.set("view engine", "ejs"); // Calling the public folderapp.use(express.static("public")); // Handling get requestapp.get("/" , (req,res)=>{ res.send("Welcome to GeeksforGeeks Video Call App"); }); // Listing the server server.listen(4000 , ()=>{ console.log("Server running on port 4000");)
Execution command for server.js
node server.js
Now, If you open the local host i.e. localhost:4000 You will see the output i.e. — Welcome to GeeksforGeeks Video Call App.
Now, For socket.io we need to write some more code. Here, we added code for socket.io and we just change app.listen() to server.listen() methods.
Now we are all set for the client side development.
Javascript
const server = require('http').Server(app);const io = require('socket.io')(server); server.listen(4000 , ()=>{ console.log("Server running on port 4000"););
Step2: Create two folders one is public and the second is views.
Project structure:
Now in views create an index.ejs file which contains all html code.
Here, we added three script files, first one is for peerjs, the second one is for socket.io and the last one is our main index.js file.
Index.ejs file
HTML
<!DOCTYPE html><html lang="en" dir="ltr"> <head> <meta charset="utf-8" /> <title>Video App</title> <style media="screen"> * { margin: 0; } #videoDiv { display: grid; grid-gap: 10px; height: 80%; position: relative; grid-template-columns: repeat(auto-fill, 300px); grid-auto-rows: 300px; } #footer { width: 100%; height: 50px; background-color: white; display: flex; justify-content: center; flex: 1; border-bottom: 1px solid grey; margin-top: 10px; } button { height: 30px; width: 80px; margin-top: 10px; text-align: center; border-radius: 10px; outline: none; border: none; text-decoration: none; background-color: red; cursor: pointer; } video { width: 100%; height: 100%; object-fit: cover; border: 2px solid white; } </style> <script type="text/javascript"> var roomID = "<%= RoomId %>" </script> <script src="https://unpkg.com/peerjs@1.3.1/dist/peerjs.min.js" defer> </script> <script src="socket.io/socket.io.js" defer> </script> <script src="index.js" charset="utf-8" defer> </script></head> <body> <div id="videoDiv"></div></body> </html>
Note — you can create your own UI, I created a simple one.
Now in the public folder create an index.js file for your index.ejs file and write some code.
const socket = io('/');
const peer = new Peer();
peer.on('open' , (id)=>{
socket.emit("newUser" , id);
});
So whenever the new user will get connected they will get a unique id through the peer.js and after that it emits a socket event for the server i.e newUser.
So to handle this event we need to add some more code in our server-side.
JavaScript
io.on('connection' , (socket)=>{ socket.on('newUser' , (id)=>{ socket.join('/'); socket.to('/').broadcast.emit("userJoined" , id); });});
Now when this event occurs the server will tell all the other clients that the new user is connected.
Now we are going to take users audio, video streams and send that stream to another client. For this, we are going to use WebRTC here.
Code to take video and audio of the user-
Javascript
navigator.mediaDevices.getUserMedia({ video:true, audio:true}).then((stream)=>{ // Some more code}).catch(err=>{ alert(err.message)})
Now we need to send the stream to all other clients, so let’s implement that part-
Here we have a peer.js method named as call. It will call the other client to send and receive streams.
Client 1: Client 1 will call client 2 as shown below.
Javascript
socket.on('userJoined' , id=>{ console.log("new user joined") // Calling other client and sending our stream const call = peer.call(id , myVideoStream); const vid = document.createElement('video'); call.on('error' , (err)=>{ alert(err); }) // Taking the stream of the other client // when they will send it. call.on('stream' , userStream=>{ // addVideo is a function which append // the video of the clients addVideo(vid , userStream); })
Client 2: let’s see how client 2 will respond to the client 1 call.
Javascript
peer.on('call' , call=>{ // Here client 2 is answering the call // and sending back their stream call.answer(stream); const vid = document.createElement('video'); // This event append the user stream. call.on('stream' , userStream=>{ addVideo(vid , userStream); }) call.on('error' , (err)=>{ alert(err) }) })
Now after sending and receiving the streams of both the clients the output will be –
OUTPUT
Note — You can deploy it on any platform you want, In my case I deployed it on heroku.com
For source code please click here, Also it is a basic one you can modify it as you want.
Node.js
Socket-programming
Technical Scripter 2020
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between dependencies, devDependencies and peerDependencies
How to connect Node.js with React.js ?
Node.js Export Module
Mongoose Populate() Method
Mongoose find() Function
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26293,
"s": 26265,
"text": "\n05 Jan, 2021"
},
{
"code": null,
"e": 26565,
"s": 26293,
"text": "For making a video call app, It is required that each and every client send their video and audio stream to all the other clients. So for this purpose we are using Peer.js and for the communication between the clients and the server we are using WebSocket i.e. Socket.io."
},
{
"code": null,
"e": 26748,
"s": 26565,
"text": "Prerequisite:1. Node.js: It is an open-source JavaScript Back-End technology. It has a package manager called npm– Node package manager which installs different packages very easily."
},
{
"code": null,
"e": 26797,
"s": 26748,
"text": "2. Express.js: It is a node.js server framework."
},
{
"code": null,
"e": 26918,
"s": 26797,
"text": "3. Socket.io:It helps us to create a real-time bi-direction event-based communication between the server and the client."
},
{
"code": null,
"e": 27012,
"s": 26918,
"text": "4. Peer.js: It helps us to send and receive the audio and video streams of the other clients."
},
{
"code": null,
"e": 27125,
"s": 27012,
"text": "Setting up the Environment: This is the very first step, here we are creating and initializing a new repository."
},
{
"code": null,
"e": 27176,
"s": 27125,
"text": "$ mkdir VideoCallApp \n$ cd VideoCallApp\n$ npm init"
},
{
"code": null,
"e": 27253,
"s": 27176,
"text": "Now, the next step is to install the required packages for our VideoCallApp."
},
{
"code": null,
"e": 27308,
"s": 27253,
"text": "Express : It is the server-based framework for node.js"
},
{
"code": null,
"e": 27407,
"s": 27308,
"text": "ejs : It is a simple templating language that lets you generate HTML markup with plain JavaScript."
},
{
"code": null,
"e": 27476,
"s": 27407,
"text": "Socket.io : It manages the Websocket for event-based communication. "
},
{
"code": null,
"e": 27567,
"s": 27476,
"text": "Nodemon (optional): It automatically restarts the server when you save your project files."
},
{
"code": null,
"e": 27660,
"s": 27567,
"text": "uuid module: This module is used to generate a unique id. This will be used in this project "
},
{
"code": null,
"e": 27693,
"s": 27660,
"text": "Installing the required modules:"
},
{
"code": null,
"e": 27779,
"s": 27693,
"text": "$ npm install express\n$ npm install ejs\n$ npm install socket.io\n$ npm install nodemon"
},
{
"code": null,
"e": 27824,
"s": 27779,
"text": "Now, we all set for the implementation part."
},
{
"code": null,
"e": 27840,
"s": 27824,
"text": "Implementation:"
},
{
"code": null,
"e": 27882,
"s": 27840,
"text": "Step 1: Create a server file — server.js "
},
{
"code": null,
"e": 27893,
"s": 27882,
"text": "JavaScript"
},
{
"code": "// Importing express moduleconst express = require('express'); const app = express(); app.set(\"view engine\", \"ejs\"); // Calling the public folderapp.use(express.static(\"public\")); // Handling get requestapp.get(\"/\" , (req,res)=>{ res.send(\"Welcome to GeeksforGeeks Video Call App\"); }); // Listing the server server.listen(4000 , ()=>{ console.log(\"Server running on port 4000\");) ",
"e": 28286,
"s": 27893,
"text": null
},
{
"code": null,
"e": 28318,
"s": 28286,
"text": "Execution command for server.js"
},
{
"code": null,
"e": 28333,
"s": 28318,
"text": "node server.js"
},
{
"code": null,
"e": 28457,
"s": 28333,
"text": "Now, If you open the local host i.e. localhost:4000 You will see the output i.e. — Welcome to GeeksforGeeks Video Call App."
},
{
"code": null,
"e": 28603,
"s": 28457,
"text": "Now, For socket.io we need to write some more code. Here, we added code for socket.io and we just change app.listen() to server.listen() methods."
},
{
"code": null,
"e": 28655,
"s": 28603,
"text": "Now we are all set for the client side development."
},
{
"code": null,
"e": 28666,
"s": 28655,
"text": "Javascript"
},
{
"code": "const server = require('http').Server(app);const io = require('socket.io')(server); server.listen(4000 , ()=>{ console.log(\"Server running on port 4000\"););",
"e": 28827,
"s": 28666,
"text": null
},
{
"code": null,
"e": 28892,
"s": 28827,
"text": "Step2: Create two folders one is public and the second is views."
},
{
"code": null,
"e": 28911,
"s": 28892,
"text": "Project structure:"
},
{
"code": null,
"e": 28979,
"s": 28911,
"text": "Now in views create an index.ejs file which contains all html code."
},
{
"code": null,
"e": 29115,
"s": 28979,
"text": "Here, we added three script files, first one is for peerjs, the second one is for socket.io and the last one is our main index.js file."
},
{
"code": null,
"e": 29130,
"s": 29115,
"text": "Index.ejs file"
},
{
"code": null,
"e": 29135,
"s": 29130,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\" dir=\"ltr\"> <head> <meta charset=\"utf-8\" /> <title>Video App</title> <style media=\"screen\"> * { margin: 0; } #videoDiv { display: grid; grid-gap: 10px; height: 80%; position: relative; grid-template-columns: repeat(auto-fill, 300px); grid-auto-rows: 300px; } #footer { width: 100%; height: 50px; background-color: white; display: flex; justify-content: center; flex: 1; border-bottom: 1px solid grey; margin-top: 10px; } button { height: 30px; width: 80px; margin-top: 10px; text-align: center; border-radius: 10px; outline: none; border: none; text-decoration: none; background-color: red; cursor: pointer; } video { width: 100%; height: 100%; object-fit: cover; border: 2px solid white; } </style> <script type=\"text/javascript\"> var roomID = \"<%= RoomId %>\" </script> <script src=\"https://unpkg.com/peerjs@1.3.1/dist/peerjs.min.js\" defer> </script> <script src=\"socket.io/socket.io.js\" defer> </script> <script src=\"index.js\" charset=\"utf-8\" defer> </script></head> <body> <div id=\"videoDiv\"></div></body> </html>",
"e": 30649,
"s": 29135,
"text": null
},
{
"code": null,
"e": 30708,
"s": 30649,
"text": "Note — you can create your own UI, I created a simple one."
},
{
"code": null,
"e": 30802,
"s": 30708,
"text": "Now in the public folder create an index.js file for your index.ejs file and write some code."
},
{
"code": null,
"e": 30914,
"s": 30802,
"text": "const socket = io('/');\nconst peer = new Peer();\n\npeer.on('open' , (id)=>{\n socket.emit(\"newUser\" , id);\n});"
},
{
"code": null,
"e": 31071,
"s": 30914,
"text": "So whenever the new user will get connected they will get a unique id through the peer.js and after that it emits a socket event for the server i.e newUser."
},
{
"code": null,
"e": 31145,
"s": 31071,
"text": "So to handle this event we need to add some more code in our server-side."
},
{
"code": null,
"e": 31156,
"s": 31145,
"text": "JavaScript"
},
{
"code": "io.on('connection' , (socket)=>{ socket.on('newUser' , (id)=>{ socket.join('/'); socket.to('/').broadcast.emit(\"userJoined\" , id); });});",
"e": 31314,
"s": 31156,
"text": null
},
{
"code": null,
"e": 31416,
"s": 31314,
"text": "Now when this event occurs the server will tell all the other clients that the new user is connected."
},
{
"code": null,
"e": 31551,
"s": 31416,
"text": "Now we are going to take users audio, video streams and send that stream to another client. For this, we are going to use WebRTC here."
},
{
"code": null,
"e": 31593,
"s": 31551,
"text": "Code to take video and audio of the user-"
},
{
"code": null,
"e": 31604,
"s": 31593,
"text": "Javascript"
},
{
"code": "navigator.mediaDevices.getUserMedia({ video:true, audio:true}).then((stream)=>{ // Some more code}).catch(err=>{ alert(err.message)})",
"e": 31750,
"s": 31604,
"text": null
},
{
"code": null,
"e": 31833,
"s": 31750,
"text": "Now we need to send the stream to all other clients, so let’s implement that part-"
},
{
"code": null,
"e": 31937,
"s": 31833,
"text": "Here we have a peer.js method named as call. It will call the other client to send and receive streams."
},
{
"code": null,
"e": 31991,
"s": 31937,
"text": "Client 1: Client 1 will call client 2 as shown below."
},
{
"code": null,
"e": 32002,
"s": 31991,
"text": "Javascript"
},
{
"code": "socket.on('userJoined' , id=>{ console.log(\"new user joined\") // Calling other client and sending our stream const call = peer.call(id , myVideoStream); const vid = document.createElement('video'); call.on('error' , (err)=>{ alert(err); }) // Taking the stream of the other client // when they will send it. call.on('stream' , userStream=>{ // addVideo is a function which append // the video of the clients addVideo(vid , userStream); })",
"e": 32470,
"s": 32002,
"text": null
},
{
"code": null,
"e": 32538,
"s": 32470,
"text": "Client 2: let’s see how client 2 will respond to the client 1 call."
},
{
"code": null,
"e": 32549,
"s": 32538,
"text": "Javascript"
},
{
"code": "peer.on('call' , call=>{ // Here client 2 is answering the call // and sending back their stream call.answer(stream); const vid = document.createElement('video'); // This event append the user stream. call.on('stream' , userStream=>{ addVideo(vid , userStream); }) call.on('error' , (err)=>{ alert(err) }) })",
"e": 32910,
"s": 32549,
"text": null
},
{
"code": null,
"e": 32996,
"s": 32910,
"text": "Now after sending and receiving the streams of both the clients the output will be – "
},
{
"code": null,
"e": 33003,
"s": 32996,
"text": "OUTPUT"
},
{
"code": null,
"e": 33093,
"s": 33003,
"text": "Note — You can deploy it on any platform you want, In my case I deployed it on heroku.com"
},
{
"code": null,
"e": 33182,
"s": 33093,
"text": "For source code please click here, Also it is a basic one you can modify it as you want."
},
{
"code": null,
"e": 33190,
"s": 33182,
"text": "Node.js"
},
{
"code": null,
"e": 33209,
"s": 33190,
"text": "Socket-programming"
},
{
"code": null,
"e": 33233,
"s": 33209,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 33241,
"s": 33233,
"text": "Node.js"
},
{
"code": null,
"e": 33260,
"s": 33241,
"text": "Technical Scripter"
},
{
"code": null,
"e": 33277,
"s": 33260,
"text": "Web Technologies"
},
{
"code": null,
"e": 33375,
"s": 33277,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33445,
"s": 33375,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 33484,
"s": 33445,
"text": "How to connect Node.js with React.js ?"
},
{
"code": null,
"e": 33506,
"s": 33484,
"text": "Node.js Export Module"
},
{
"code": null,
"e": 33533,
"s": 33506,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 33558,
"s": 33533,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 33598,
"s": 33558,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 33643,
"s": 33598,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 33686,
"s": 33643,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 33736,
"s": 33686,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
PLSQL | SIGN Function - GeeksforGeeks
|
25 Oct, 2019
The PLSQL SIGN function is used for returning a value which indicates the sign of a number. The SIGN function accepts one parameter which is the number whose sign needs to be known. The SIGN function returns a value of the numeric data type. This function takes as an argument any numeric data type as well as any non-numeric data type that can be implicitly converted to a numeric data type.
The possible values returned by the SIGN function are:
The SIGN function returns -1 if the number is smaller than 0.
The SIGN function returns 0 if the number is equal to 0.
The SIGN function returns 1 if the number is greater than 0.
Syntax:
SIGN (number)
Parameters Used:
number – It is used to specify the number whose sign needs to be tested.
Return Value:The SIGN function in PLSQL returns a numeric value.
Supported Versions of Oracle/PLSQL:
Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i
Oracle 12c
Oracle 11g
Oracle 10g
Oracle 9i
Oracle 8i
Example-1: Using positive numeric value as an argument in the SIGN function.
DECLARE
Test_Number1 number := 5;
BEGIN
dbms_output.put_line(SIGN(Test_Number1));
END;
Output:
1
Example-2: Using negative numeric value as an argument in the SIGN function.
DECLARE
Test_Number1 number := -5;
BEGIN
dbms_output.put_line(SIGN(Test_Number1));
END;
Output:
-1
Example-3: Using zero as an argument in the SIGN function.
DECLARE
Test_Number1 number := 0;
BEGIN
dbms_output.put_line(SIGN(Test_Number1));
END;
Output:
0
Example-4: Using a positive number with decimal value as an argument in the SIGN function.
DECLARE
Test_Number1 number := 0.0032;
BEGIN
dbms_output.put_line(SIGN(Test_Number1));
END;
Output:
1
Example-5: Using a negative number with decimal value as an argument in the SIGN function.
DECLARE
Test_Number1 number := - 0.0032;
BEGIN
dbms_output.put_line(SIGN(Test_Number1));
END;
Example-6: Using SIGN function with select query.
SELECT SIGN(-5) "Sign" FROM DUAL;
Output:
Sign
-1
Advantages:The SIGN function accepts any numeric datatype as well as any non-numeric datatype as an argument that can be implicitly converted to a numeric datatype.
SQL-PL/SQL
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?
SQL | Subquery
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL using Python
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
SQL Query to Compare Two Dates
|
[
{
"code": null,
"e": 25513,
"s": 25485,
"text": "\n25 Oct, 2019"
},
{
"code": null,
"e": 25906,
"s": 25513,
"text": "The PLSQL SIGN function is used for returning a value which indicates the sign of a number. The SIGN function accepts one parameter which is the number whose sign needs to be known. The SIGN function returns a value of the numeric data type. This function takes as an argument any numeric data type as well as any non-numeric data type that can be implicitly converted to a numeric data type."
},
{
"code": null,
"e": 25961,
"s": 25906,
"text": "The possible values returned by the SIGN function are:"
},
{
"code": null,
"e": 26023,
"s": 25961,
"text": "The SIGN function returns -1 if the number is smaller than 0."
},
{
"code": null,
"e": 26080,
"s": 26023,
"text": "The SIGN function returns 0 if the number is equal to 0."
},
{
"code": null,
"e": 26141,
"s": 26080,
"text": "The SIGN function returns 1 if the number is greater than 0."
},
{
"code": null,
"e": 26149,
"s": 26141,
"text": "Syntax:"
},
{
"code": null,
"e": 26163,
"s": 26149,
"text": "SIGN (number)"
},
{
"code": null,
"e": 26180,
"s": 26163,
"text": "Parameters Used:"
},
{
"code": null,
"e": 26253,
"s": 26180,
"text": "number – It is used to specify the number whose sign needs to be tested."
},
{
"code": null,
"e": 26318,
"s": 26253,
"text": "Return Value:The SIGN function in PLSQL returns a numeric value."
},
{
"code": null,
"e": 26354,
"s": 26318,
"text": "Supported Versions of Oracle/PLSQL:"
},
{
"code": null,
"e": 26403,
"s": 26354,
"text": "Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i"
},
{
"code": null,
"e": 26414,
"s": 26403,
"text": "Oracle 12c"
},
{
"code": null,
"e": 26425,
"s": 26414,
"text": "Oracle 11g"
},
{
"code": null,
"e": 26436,
"s": 26425,
"text": "Oracle 10g"
},
{
"code": null,
"e": 26446,
"s": 26436,
"text": "Oracle 9i"
},
{
"code": null,
"e": 26456,
"s": 26446,
"text": "Oracle 8i"
},
{
"code": null,
"e": 26533,
"s": 26456,
"text": "Example-1: Using positive numeric value as an argument in the SIGN function."
},
{
"code": null,
"e": 26638,
"s": 26533,
"text": "DECLARE \n Test_Number1 number := 5;\n \nBEGIN \n dbms_output.put_line(SIGN(Test_Number1)); \n \nEND; "
},
{
"code": null,
"e": 26646,
"s": 26638,
"text": "Output:"
},
{
"code": null,
"e": 26649,
"s": 26646,
"text": "1 "
},
{
"code": null,
"e": 26726,
"s": 26649,
"text": "Example-2: Using negative numeric value as an argument in the SIGN function."
},
{
"code": null,
"e": 26832,
"s": 26726,
"text": "DECLARE \n Test_Number1 number := -5;\n \nBEGIN \n dbms_output.put_line(SIGN(Test_Number1)); \n \nEND;\n"
},
{
"code": null,
"e": 26840,
"s": 26832,
"text": "Output:"
},
{
"code": null,
"e": 26844,
"s": 26840,
"text": "-1 "
},
{
"code": null,
"e": 26903,
"s": 26844,
"text": "Example-3: Using zero as an argument in the SIGN function."
},
{
"code": null,
"e": 27008,
"s": 26903,
"text": "DECLARE \n Test_Number1 number := 0;\n \nBEGIN \n dbms_output.put_line(SIGN(Test_Number1)); \n \nEND; "
},
{
"code": null,
"e": 27016,
"s": 27008,
"text": "Output:"
},
{
"code": null,
"e": 27019,
"s": 27016,
"text": "0 "
},
{
"code": null,
"e": 27110,
"s": 27019,
"text": "Example-4: Using a positive number with decimal value as an argument in the SIGN function."
},
{
"code": null,
"e": 27220,
"s": 27110,
"text": "DECLARE \n Test_Number1 number := 0.0032;\n \nBEGIN \n dbms_output.put_line(SIGN(Test_Number1)); \n \nEND; "
},
{
"code": null,
"e": 27228,
"s": 27220,
"text": "Output:"
},
{
"code": null,
"e": 27231,
"s": 27228,
"text": "1 "
},
{
"code": null,
"e": 27322,
"s": 27231,
"text": "Example-5: Using a negative number with decimal value as an argument in the SIGN function."
},
{
"code": null,
"e": 27434,
"s": 27322,
"text": "DECLARE \n Test_Number1 number := - 0.0032;\n \nBEGIN \n dbms_output.put_line(SIGN(Test_Number1)); \n \nEND; "
},
{
"code": null,
"e": 27484,
"s": 27434,
"text": "Example-6: Using SIGN function with select query."
},
{
"code": null,
"e": 27519,
"s": 27484,
"text": "SELECT SIGN(-5) \"Sign\" FROM DUAL; "
},
{
"code": null,
"e": 27527,
"s": 27519,
"text": "Output:"
},
{
"code": null,
"e": 27536,
"s": 27527,
"text": "Sign\n-1 "
},
{
"code": null,
"e": 27701,
"s": 27536,
"text": "Advantages:The SIGN function accepts any numeric datatype as well as any non-numeric datatype as an argument that can be implicitly converted to a numeric datatype."
},
{
"code": null,
"e": 27712,
"s": 27701,
"text": "SQL-PL/SQL"
},
{
"code": null,
"e": 27716,
"s": 27712,
"text": "SQL"
},
{
"code": null,
"e": 27720,
"s": 27716,
"text": "SQL"
},
{
"code": null,
"e": 27818,
"s": 27720,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27884,
"s": 27818,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 27899,
"s": 27884,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 27956,
"s": 27899,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 27988,
"s": 27956,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 28066,
"s": 27988,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 28102,
"s": 28066,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 28119,
"s": 28102,
"text": "SQL using Python"
},
{
"code": null,
"e": 28185,
"s": 28119,
"text": "How to Write a SQL Query For a Specific Date Range and Date Time?"
},
{
"code": null,
"e": 28247,
"s": 28185,
"text": "How to Select Data Between Two Dates and Times in SQL Server?"
}
] |
HTML <font> size Attribute - GeeksforGeeks
|
15 Dec, 2021
The HTML <font> size Attribute is used to specify the size of text which is present inside <font> element.
Syntax:
<font size="number">
Attribute Values: It contains a single value number that specifies the size of the text. The font size lies between 1 to 7. The default value of font size is 3.
Note: The <font> size attribute is not supported by HTML 5.
Example 1: This example illustrates the use of the font size property whose value ranges from 1 to 7 in HTML.
HTML
<!DOCTYPE html><html><head> <title>HTML font size Attribute</title></head> <body> <font size="1">GeeksforGeeks!</font><br /> <font size="2">GeeksforGeeks!</font><br /> <font size="3">GeeksforGeeks!</font><br /> <font size="4">GeeksforGeeks!</font><br /> <font size="5">GeeksforGeeks!</font><br /> <font size="6">GeeksforGeeks!</font><br /> <font size="7">GeeksforGeeks!</font></body></html>
Output:
<font> size attribute
Example 2: This example illustrates the use of the size attribute inside the <font> tag in HTML.
HTML
<!DOCTYPE html><html><head> <title>HTML font size Attribute</title></head> <body> <font size="7" face="verdana" color="green"> GeeksforGeeks! </font> <br> <hr> <font size="6" face="arial" color="#008000"> GeeksforGeeks! </font> <br> <hr> <font size="5" face="sans-serif" color="rgb(128, 128, 0)"> GeeksforGeeks! </font> <br> <hr> <font size="4" face="times new roman" color="#008000"> GeeksforGeeks! </font></body></html>
Output:
<font> tag with different color, type & size attribute
Example 3: In this example, we have used the font size attribute & set it to different values in order to display similar to the use of HTML heading & paragraph.
HTML
<!DOCTYPE html><html><body> <font size="6" face="sans-serif" color="green"> GeeksforGeeks </font> <br> <hr> <font size="3" face="Comic sans MS"> Learn Data Structures Online At Your Own Pace With The Best Of Faculty In The Industry. The Best Data Structures Course Available Online From Skilled And Experienced Faculty. </font></body></html>
Output:
<font> tag with different face & size attribute
Supported Browsers:
Google Chrome 93.0
Internet Explorer 11.0
Microsoft Edge 93.0
Firefox 92.0
Safari 14.1
Opera 79.0
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
bhaskargeeksforgeeks
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
Types of CSS (Cascading Style Sheet)
HTML | <img> align Attribute
How to position a div at the bottom of its container using CSS?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 25515,
"s": 25487,
"text": "\n15 Dec, 2021"
},
{
"code": null,
"e": 25622,
"s": 25515,
"text": "The HTML <font> size Attribute is used to specify the size of text which is present inside <font> element."
},
{
"code": null,
"e": 25630,
"s": 25622,
"text": "Syntax:"
},
{
"code": null,
"e": 25651,
"s": 25630,
"text": "<font size=\"number\">"
},
{
"code": null,
"e": 25812,
"s": 25651,
"text": "Attribute Values: It contains a single value number that specifies the size of the text. The font size lies between 1 to 7. The default value of font size is 3."
},
{
"code": null,
"e": 25872,
"s": 25812,
"text": "Note: The <font> size attribute is not supported by HTML 5."
},
{
"code": null,
"e": 25982,
"s": 25872,
"text": "Example 1: This example illustrates the use of the font size property whose value ranges from 1 to 7 in HTML."
},
{
"code": null,
"e": 25987,
"s": 25982,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>HTML font size Attribute</title></head> <body> <font size=\"1\">GeeksforGeeks!</font><br /> <font size=\"2\">GeeksforGeeks!</font><br /> <font size=\"3\">GeeksforGeeks!</font><br /> <font size=\"4\">GeeksforGeeks!</font><br /> <font size=\"5\">GeeksforGeeks!</font><br /> <font size=\"6\">GeeksforGeeks!</font><br /> <font size=\"7\">GeeksforGeeks!</font></body></html>",
"e": 26402,
"s": 25987,
"text": null
},
{
"code": null,
"e": 26410,
"s": 26402,
"text": "Output:"
},
{
"code": null,
"e": 26432,
"s": 26410,
"text": "<font> size attribute"
},
{
"code": null,
"e": 26529,
"s": 26432,
"text": "Example 2: This example illustrates the use of the size attribute inside the <font> tag in HTML."
},
{
"code": null,
"e": 26534,
"s": 26529,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>HTML font size Attribute</title></head> <body> <font size=\"7\" face=\"verdana\" color=\"green\"> GeeksforGeeks! </font> <br> <hr> <font size=\"6\" face=\"arial\" color=\"#008000\"> GeeksforGeeks! </font> <br> <hr> <font size=\"5\" face=\"sans-serif\" color=\"rgb(128, 128, 0)\"> GeeksforGeeks! </font> <br> <hr> <font size=\"4\" face=\"times new roman\" color=\"#008000\"> GeeksforGeeks! </font></body></html>",
"e": 27117,
"s": 26534,
"text": null
},
{
"code": null,
"e": 27125,
"s": 27117,
"text": "Output:"
},
{
"code": null,
"e": 27180,
"s": 27125,
"text": "<font> tag with different color, type & size attribute"
},
{
"code": null,
"e": 27342,
"s": 27180,
"text": "Example 3: In this example, we have used the font size attribute & set it to different values in order to display similar to the use of HTML heading & paragraph."
},
{
"code": null,
"e": 27347,
"s": 27342,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><body> <font size=\"6\" face=\"sans-serif\" color=\"green\"> GeeksforGeeks </font> <br> <hr> <font size=\"3\" face=\"Comic sans MS\"> Learn Data Structures Online At Your Own Pace With The Best Of Faculty In The Industry. The Best Data Structures Course Available Online From Skilled And Experienced Faculty. </font></body></html>",
"e": 27771,
"s": 27347,
"text": null
},
{
"code": null,
"e": 27779,
"s": 27771,
"text": "Output:"
},
{
"code": null,
"e": 27827,
"s": 27779,
"text": "<font> tag with different face & size attribute"
},
{
"code": null,
"e": 27847,
"s": 27827,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 27866,
"s": 27847,
"text": "Google Chrome 93.0"
},
{
"code": null,
"e": 27889,
"s": 27866,
"text": "Internet Explorer 11.0"
},
{
"code": null,
"e": 27909,
"s": 27889,
"text": "Microsoft Edge 93.0"
},
{
"code": null,
"e": 27922,
"s": 27909,
"text": "Firefox 92.0"
},
{
"code": null,
"e": 27934,
"s": 27922,
"text": "Safari 14.1"
},
{
"code": null,
"e": 27945,
"s": 27934,
"text": "Opera 79.0"
},
{
"code": null,
"e": 28082,
"s": 27945,
"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": 28103,
"s": 28082,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 28119,
"s": 28103,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 28124,
"s": 28119,
"text": "HTML"
},
{
"code": null,
"e": 28141,
"s": 28124,
"text": "Web Technologies"
},
{
"code": null,
"e": 28146,
"s": 28141,
"text": "HTML"
},
{
"code": null,
"e": 28244,
"s": 28146,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28268,
"s": 28244,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 28318,
"s": 28268,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 28355,
"s": 28318,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 28384,
"s": 28355,
"text": "HTML | <img> align Attribute"
},
{
"code": null,
"e": 28448,
"s": 28384,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 28488,
"s": 28448,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28521,
"s": 28488,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28566,
"s": 28521,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28609,
"s": 28566,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Keyword Cipher - GeeksforGeeks
|
18 Feb, 2022
A keyword cipher is a form of monoalphabetic substitution. A keyword is used as the key, and it determines the letter matchings of the cipher alphabet to the plain alphabet. Repeats of letters in the word are removed, then the cipher alphabet is generated with the keyword matching to A, B, C, etc. until the keyword is used up, whereupon the rest of the ciphertext letters are used in alphabetical order, excluding those already used in the key.
Encryption
The first line of input contains the keyword which you wish to enter. The second line of input contains the string which you have to encrypt. Plaintext: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z Encrypted: K R Y P T O S A B C D E F G H I J L M N Q U V W X ZWith KRYPTOS as the keyword, all As becoming Ks, all Bs becoming Rs, and so on. Encrypting the message “knowledge is power” using the keyword “Kryptos”: Encrypting the message: Knowledge is Power Encoded message: IlmWjbaEb GQ NmWbpExamples:
Input :
Keyword : secret
Message : Zombie Here
Output :
Ciphered String : ZLJEFT DTOT
Take the first example, we used "secret" keyword there.
Plain Text : A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
When "secret" keyword is used, the new encrypting text becomes :
Encrypting : S E C R T A B D F G H I J K L M N O P Q U V W X Y Z
This means 'A' means 'S', 'B' means 'E' and 'C' means 'C' and so on.
Lets encode the given message "Zombie Here"
ZOMBIE HERE becomes ZLJEFT DTOT
Input :
Keyword : Star War
Message : Attack at dawn
Output :
Ciphered String : SPPSAG SP RSVJ
Few points to be noted in this method:
All the messages are encoded in uppercase.
Whitespace, special character, and numbers do not take into consideration keywords although you can put them in there.
While encrypting the message, whitespace, special characters and numbers remain unaffected.
C++
Java
C#
Javascript
// CPP program for encoding the string// using classical cipher #include<bits/stdc++.h>using namespace std; // Function generates the encoded textstring encoder(string key){ string encoded = ""; // This array represents the // 26 letters of alphabets bool arr[26] = {0}; // This loop inserts the keyword // at the start of the encoded string for (int i=0; i<key.size(); i++) { if(key[i] >= 'A' && key[i] <= 'Z') { // To check whether the character is inserted // earlier in the encoded string or not if (arr[key[i]-65] == 0) { encoded += key[i]; arr[key[i]-65] = 1; } } else if (key[i] >= 'a' && key[i] <= 'z') { if (arr[key[i]-97] == 0) { encoded += key[i] - 32; arr[key[i]-97] = 1; } } } // This loop inserts the remaining // characters in the encoded string. for (int i=0; i<26; i++) { if(arr[i] == 0) { arr[i]=1; encoded += char(i + 65); } } return encoded;} // Function that generates encodes(cipher) the messagestring cipheredIt(string msg, string encoded){ string cipher=""; // This loop ciphered the message. // Spaces, special characters and numbers remain same. for (int i=0; i<msg.size(); i++) { if (msg[i] >='a' && msg[i] <='z') { int pos = msg[i] - 97; cipher += encoded[pos]; } else if (msg[i] >='A' && msg[i] <='Z') { int pos = msg[i] - 65; cipher += encoded[pos]; } else { cipher += msg[i]; } } return cipher;} // Driver codeint main(){ // Hold the Keyword string key; key = "Computer"; cout << "Keyword : " <<key << endl; // Function call to generate encoded text string encoded = encoder(key); // Message that need to encode string message = "GeeksforGeeks"; cout << "Message before Ciphering : " << message << endl; // Function call to print ciphered text cout << "Ciphered Text : " << cipheredIt(message,encoded) << endl; return 0;}
// Java program for encoding the string// using classical cipher class GFG{ // Function generates the encoded text static String encoder(char[] key) { String encoded = ""; // This array represents the // 26 letters of alphabets boolean[] arr = new boolean[26]; // This loop inserts the keyword // at the start of the encoded string for (int i = 0; i < key.length; i++) { if (key[i] >= 'A' && key[i] <= 'Z') { // To check whether the character is inserted // earlier in the encoded string or not if (arr[key[i] - 65] == false) { encoded += (char) key[i]; arr[key[i] - 65] = true; } } else if (key[i] >= 'a' && key[i] <= 'z') { if (arr[key[i] - 97] == false) { encoded += (char) (key[i] - 32); arr[key[i] - 97] = true; } } } // This loop inserts the remaining // characters in the encoded string. for (int i = 0; i < 26; i++) { if (arr[i] == false) { arr[i] = true; encoded += (char) (i + 65); } } return encoded; } // Function that generates encodes(cipher) the message static String cipheredIt(String msg, String encoded) { String cipher = ""; // This loop ciphered the message. // Spaces, special characters and numbers remain same. for (int i = 0; i < msg.length(); i++) { if (msg.charAt(i) >= 'a' && msg.charAt(i) <= 'z') { int pos = msg.charAt(i) - 97; cipher += encoded.charAt(pos); } else if (msg.charAt(i) >= 'A' && msg.charAt(i) <= 'Z') { int pos = msg.charAt(i) - 65; cipher += encoded.charAt(pos); } else { cipher += msg.charAt(i); } } return cipher; } // Driver code public static void main(String[] args) { // Hold the Keyword String key; key = "Computer"; System.out.println("Keyword : " + key); // Function call to generate encoded text String encoded = encoder(key.toCharArray()); // Message that need to encode String message = "GeeksforGeeks"; System.out.println("Message before Ciphering : " + message); // Function call to print ciphered text System.out.println("Ciphered Text : " + cipheredIt(message, encoded)); }} // This code is contributed by 29AjayKumar
// C# program for encoding the string// using classical cipherusing System; class GFG{ // Function generates the encoded text static String encoder(char[] key) { String encoded = ""; // This array represents the // 26 letters of alphabets Boolean[] arr = new Boolean[26]; // This loop inserts the keyword // at the start of the encoded string for (int i = 0; i < key.Length; i++) { if (key[i] >= 'A' && key[i] <= 'Z') { // To check whether the character is inserted // earlier in the encoded string or not if (arr[key[i] - 65] == false) { encoded += (char) key[i]; arr[key[i] - 65] = true; } } else if (key[i] >= 'a' && key[i] <= 'z') { if (arr[key[i] - 97] == false) { encoded += (char) (key[i] - 32); arr[key[i] - 97] = true; } } } // This loop inserts the remaining // characters in the encoded string. for (int i = 0; i < 26; i++) { if (arr[i] == false) { arr[i] = true; encoded += (char) (i + 65); } } return encoded; } // Function that generates encodes(cipher) the message static String cipheredIt(String msg, String encoded) { String cipher = ""; // This loop ciphered the message. // Spaces, special characters and numbers remain same. for (int i = 0; i < msg.Length; i++) { if (msg[i] >= 'a' && msg[i] <= 'z') { int pos = msg[i] - 97; cipher += encoded[pos]; } else if (msg[i] >= 'A' && msg[i] <= 'Z') { int pos = msg[i] - 65; cipher += encoded[pos]; } else { cipher += msg[i]; } } return cipher; } // Driver code public static void Main(String[] args) { // Hold the Keyword String key; key = "Computer"; Console.WriteLine("Keyword : " + key); // Function call to generate encoded text String encoded = encoder(key.ToCharArray()); // Message that need to encode String message = "GeeksforGeeks"; Console.WriteLine("Message before Ciphering : " + message); // Function call to print ciphered text Console.WriteLine("Ciphered Text : " + cipheredIt(message, encoded)); }} /* This code contributed by PrinciRaj1992 */
<script> // JavaScript program for encoding the string// using classical cipher // Function generates the encoded textfunction encoder(key){ let encoded = ""; // This array represents the // 26 letters of alphabets let arr = new Array(26); for(let i=0;i<26;i++) { arr[i]=false; } // This loop inserts the keyword // at the start of the encoded string for (let i = 0; i < key.length; i++) { if (key[i].charCodeAt(0) >= 'A'.charCodeAt(0) && key[i].charCodeAt(0) <= 'Z'.charCodeAt(0)) { // To check whether the character is inserted // earlier in the encoded string or not if (arr[key[i].charCodeAt(0) - 65] == false) { encoded += ( key[i]); arr[key[i].charCodeAt(0) - 65] = true; } } else if (key[i].charCodeAt(0) >= 'a'.charCodeAt(0) && key[i].charCodeAt(0) <= 'z'.charCodeAt(0)) { if (arr[key[i].charCodeAt(0) - 97] == false) { encoded += String.fromCharCode(key[i].charCodeAt(0) - 32); arr[key[i].charCodeAt(0) - 97] = true; } } } // This loop inserts the remaining // characters in the encoded string. for (let i = 0; i < 26; i++) { if (arr[i] == false) { arr[i] = true; encoded += String.fromCharCode(i + 65); } } return encoded;} // Function that generates encodes(cipher) the messagefunction cipheredIt(msg,encoded){ let cipher = ""; // This loop ciphered the message. // Spaces, special characters and numbers remain same. for (let i = 0; i < msg.length; i++) { if (msg[i] >= 'a' && msg[i] <= 'z') { let pos = msg[i].charCodeAt(0) - 97; cipher += encoded[pos]; } else if (msg[i] >= 'A' && msg[i] <= 'Z') { let pos = msg[i].charCodeAt(0) - 65; cipher += encoded[pos]; } else { cipher += msg[i]; } } return cipher;} // Driver code// Hold the Keywordlet key;key = "Computer";document.write("Keyword : " + key+"<br>"); // Function call to generate encoded textlet encoded = encoder(key.split("")); // Message that need to encodelet message = "GeeksforGeeks";document.write("Message before Ciphering : " + message+"<br>"); // Function call to print ciphered textdocument.write("Ciphered Text : " + cipheredIt(message, encoded)); // This code is contributed by rag2127 </script>
Output:
Keyword : Computer
Message before Ciphering : GeeksforGeeks
Ciphered Text : EUUDNTILEUUDN
Decryption
To decode the message you check the position of the given message in encrypting text with the plain text.Plaintext: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z Encrypted: K R Y P T O S A B C D E F G H I J L M N Q U V W X ZMessage: PTYBIATLEP Deciphered Text: DECIPHEREDNow, how do we generate the deciphered string? We search for ‘P’ in Encrypted Text and compare its position with plain text letter and generate that letter. So ‘P’ becomes ‘D’, ‘T’ becomes ‘E’, ‘Y’ becomes ‘C’, and so on.Examples:
Input :
Keyword : secret
Message : zljeft dtOT
Output :
Deciphered String : ZOMBIE HERE
Input :
Keyword : joker0O7hack123
Message : QjTijl
Output :
Deciphered String : BATMAN
CPP
// CPP program for decoding the string// which generate using classical cipher #include<bits/stdc++.h>using namespace std; // Original Set of lettersstring plaintext = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // Function generates the encoded textstring encoder(string key){ string encoded = ""; bool arr[26] = {0}; // This loop inserts the keyword // at the start of the encoded string for (int i=0; i<key.size(); i++) { if(key[i] >= 'A' && key[i] <= 'Z') { // To check whether the character is inserted // earlier in the encoded string or not if (arr[key[i]-65] == 0) { encoded += key[i]; arr[key[i]-65] = 1; } } else if (key[i] >= 'a' && key[i] <= 'z') { if (arr[key[i]-97] == 0) { encoded += key[i] - 32; arr[key[i]-97] = 1; } } } // This loop inserts the remaining // characters in the encoded string. for (int i=0; i<26; i++) { if(arr[i] == 0) { arr[i]=1; encoded += char(i + 65); } } return encoded;} // This function will decode the messagestring decipheredIt(string msg, string encoded){ // Hold the position of every character (A-Z) // from encoded string map <char,int> enc; for(int i=0; i<encoded.size(); i++) { enc[encoded[i]]=i; } string decipher=""; // This loop deciphered the message. // Spaces, special characters and numbers remain same. for (int i=0; i<msg.size(); i++) { if (msg[i] >='a' && msg[i] <='z') { int pos = enc[msg[i]-32]; decipher += plaintext[pos]; } else if(msg[i] >='A' && msg[i] <='Z') { int pos = enc[msg[i]]; decipher += plaintext[pos]; } else { decipher += msg[i]; } } return decipher;} // Driver codeint main(){ // Hold the Keyword string key; key = "Computer"; cout << "Keyword : "<< key << endl; // Function call to generate encoded text string encoded = encoder(key); // Message that need to decode string message = "EUUDN TIL EUUDN"; cout << "Message before Deciphering : " << message << endl; // Function call to print deciphered text cout << "Deciphered Text : " << decipheredIt(message,encoded) << endl; return 0;}
Output:
Keyword : Computer
Message before Deciphering : EUUDN TIL EUUDN
Deciphered Text : GEEKS FOR GEEKS
You can improve this Classical Cipher: Keyword also. Here we are only taking A-Z in plain text. You can take uppercase, lowercase, and numbers also into consideration.Ways to attack a keyword cipher: The best ways to attack a keyword cipher without knowing the keyword are through the known-plaintext attack, frequency analysis, and discovery of the keyword (often a cryptanalyst will combine all three techniques). Keyword discovery allows immediate decryption since the table can be made immediately.This article is contributed by Sachin Bisht. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
29AjayKumar
princiraj1992
rag2127
kumaripunam984122
simranarora5sos
cryptography
Strings
Strings
cryptography
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Check whether two strings are anagram of each other
Top 50 String Coding Problems for Interviews
Length of the longest substring without repeating characters
Reverse words in a given string
How to split a string in C/C++, Python and Java?
Remove duplicates from a given string
Print all the duplicates in the input string
stringstream in C++ and its applications
|
[
{
"code": null,
"e": 25991,
"s": 25963,
"text": "\n18 Feb, 2022"
},
{
"code": null,
"e": 26440,
"s": 25991,
"text": "A keyword cipher is a form of monoalphabetic substitution. A keyword is used as the key, and it determines the letter matchings of the cipher alphabet to the plain alphabet. Repeats of letters in the word are removed, then the cipher alphabet is generated with the keyword matching to A, B, C, etc. until the keyword is used up, whereupon the rest of the ciphertext letters are used in alphabetical order, excluding those already used in the key. "
},
{
"code": null,
"e": 26451,
"s": 26440,
"text": "Encryption"
},
{
"code": null,
"e": 26961,
"s": 26451,
"text": "The first line of input contains the keyword which you wish to enter. The second line of input contains the string which you have to encrypt. Plaintext: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z Encrypted: K R Y P T O S A B C D E F G H I J L M N Q U V W X ZWith KRYPTOS as the keyword, all As becoming Ks, all Bs becoming Rs, and so on. Encrypting the message “knowledge is power” using the keyword “Kryptos”: Encrypting the message: Knowledge is Power Encoded message: IlmWjbaEb GQ NmWbpExamples: "
},
{
"code": null,
"e": 27539,
"s": 26961,
"text": "Input :\nKeyword : secret\nMessage : Zombie Here\nOutput :\nCiphered String : ZLJEFT DTOT\n\nTake the first example, we used \"secret\" keyword there.\nPlain Text : A B C D E F G H I J K L M N O P Q R S T U V W X Y Z\nWhen \"secret\" keyword is used, the new encrypting text becomes :\nEncrypting : S E C R T A B D F G H I J K L M N O P Q U V W X Y Z\nThis means 'A' means 'S', 'B' means 'E' and 'C' means 'C' and so on.\nLets encode the given message \"Zombie Here\"\nZOMBIE HERE becomes ZLJEFT DTOT\n\nInput :\nKeyword : Star War\nMessage : Attack at dawn\nOutput :\nCiphered String : SPPSAG SP RSVJ"
},
{
"code": null,
"e": 27580,
"s": 27539,
"text": "Few points to be noted in this method: "
},
{
"code": null,
"e": 27623,
"s": 27580,
"text": "All the messages are encoded in uppercase."
},
{
"code": null,
"e": 27742,
"s": 27623,
"text": "Whitespace, special character, and numbers do not take into consideration keywords although you can put them in there."
},
{
"code": null,
"e": 27834,
"s": 27742,
"text": "While encrypting the message, whitespace, special characters and numbers remain unaffected."
},
{
"code": null,
"e": 27840,
"s": 27836,
"text": "C++"
},
{
"code": null,
"e": 27845,
"s": 27840,
"text": "Java"
},
{
"code": null,
"e": 27848,
"s": 27845,
"text": "C#"
},
{
"code": null,
"e": 27859,
"s": 27848,
"text": "Javascript"
},
{
"code": "// CPP program for encoding the string// using classical cipher #include<bits/stdc++.h>using namespace std; // Function generates the encoded textstring encoder(string key){ string encoded = \"\"; // This array represents the // 26 letters of alphabets bool arr[26] = {0}; // This loop inserts the keyword // at the start of the encoded string for (int i=0; i<key.size(); i++) { if(key[i] >= 'A' && key[i] <= 'Z') { // To check whether the character is inserted // earlier in the encoded string or not if (arr[key[i]-65] == 0) { encoded += key[i]; arr[key[i]-65] = 1; } } else if (key[i] >= 'a' && key[i] <= 'z') { if (arr[key[i]-97] == 0) { encoded += key[i] - 32; arr[key[i]-97] = 1; } } } // This loop inserts the remaining // characters in the encoded string. for (int i=0; i<26; i++) { if(arr[i] == 0) { arr[i]=1; encoded += char(i + 65); } } return encoded;} // Function that generates encodes(cipher) the messagestring cipheredIt(string msg, string encoded){ string cipher=\"\"; // This loop ciphered the message. // Spaces, special characters and numbers remain same. for (int i=0; i<msg.size(); i++) { if (msg[i] >='a' && msg[i] <='z') { int pos = msg[i] - 97; cipher += encoded[pos]; } else if (msg[i] >='A' && msg[i] <='Z') { int pos = msg[i] - 65; cipher += encoded[pos]; } else { cipher += msg[i]; } } return cipher;} // Driver codeint main(){ // Hold the Keyword string key; key = \"Computer\"; cout << \"Keyword : \" <<key << endl; // Function call to generate encoded text string encoded = encoder(key); // Message that need to encode string message = \"GeeksforGeeks\"; cout << \"Message before Ciphering : \" << message << endl; // Function call to print ciphered text cout << \"Ciphered Text : \" << cipheredIt(message,encoded) << endl; return 0;}",
"e": 30072,
"s": 27859,
"text": null
},
{
"code": "// Java program for encoding the string// using classical cipher class GFG{ // Function generates the encoded text static String encoder(char[] key) { String encoded = \"\"; // This array represents the // 26 letters of alphabets boolean[] arr = new boolean[26]; // This loop inserts the keyword // at the start of the encoded string for (int i = 0; i < key.length; i++) { if (key[i] >= 'A' && key[i] <= 'Z') { // To check whether the character is inserted // earlier in the encoded string or not if (arr[key[i] - 65] == false) { encoded += (char) key[i]; arr[key[i] - 65] = true; } } else if (key[i] >= 'a' && key[i] <= 'z') { if (arr[key[i] - 97] == false) { encoded += (char) (key[i] - 32); arr[key[i] - 97] = true; } } } // This loop inserts the remaining // characters in the encoded string. for (int i = 0; i < 26; i++) { if (arr[i] == false) { arr[i] = true; encoded += (char) (i + 65); } } return encoded; } // Function that generates encodes(cipher) the message static String cipheredIt(String msg, String encoded) { String cipher = \"\"; // This loop ciphered the message. // Spaces, special characters and numbers remain same. for (int i = 0; i < msg.length(); i++) { if (msg.charAt(i) >= 'a' && msg.charAt(i) <= 'z') { int pos = msg.charAt(i) - 97; cipher += encoded.charAt(pos); } else if (msg.charAt(i) >= 'A' && msg.charAt(i) <= 'Z') { int pos = msg.charAt(i) - 65; cipher += encoded.charAt(pos); } else { cipher += msg.charAt(i); } } return cipher; } // Driver code public static void main(String[] args) { // Hold the Keyword String key; key = \"Computer\"; System.out.println(\"Keyword : \" + key); // Function call to generate encoded text String encoded = encoder(key.toCharArray()); // Message that need to encode String message = \"GeeksforGeeks\"; System.out.println(\"Message before Ciphering : \" + message); // Function call to print ciphered text System.out.println(\"Ciphered Text : \" + cipheredIt(message, encoded)); }} // This code is contributed by 29AjayKumar",
"e": 32850,
"s": 30072,
"text": null
},
{
"code": "// C# program for encoding the string// using classical cipherusing System; class GFG{ // Function generates the encoded text static String encoder(char[] key) { String encoded = \"\"; // This array represents the // 26 letters of alphabets Boolean[] arr = new Boolean[26]; // This loop inserts the keyword // at the start of the encoded string for (int i = 0; i < key.Length; i++) { if (key[i] >= 'A' && key[i] <= 'Z') { // To check whether the character is inserted // earlier in the encoded string or not if (arr[key[i] - 65] == false) { encoded += (char) key[i]; arr[key[i] - 65] = true; } } else if (key[i] >= 'a' && key[i] <= 'z') { if (arr[key[i] - 97] == false) { encoded += (char) (key[i] - 32); arr[key[i] - 97] = true; } } } // This loop inserts the remaining // characters in the encoded string. for (int i = 0; i < 26; i++) { if (arr[i] == false) { arr[i] = true; encoded += (char) (i + 65); } } return encoded; } // Function that generates encodes(cipher) the message static String cipheredIt(String msg, String encoded) { String cipher = \"\"; // This loop ciphered the message. // Spaces, special characters and numbers remain same. for (int i = 0; i < msg.Length; i++) { if (msg[i] >= 'a' && msg[i] <= 'z') { int pos = msg[i] - 97; cipher += encoded[pos]; } else if (msg[i] >= 'A' && msg[i] <= 'Z') { int pos = msg[i] - 65; cipher += encoded[pos]; } else { cipher += msg[i]; } } return cipher; } // Driver code public static void Main(String[] args) { // Hold the Keyword String key; key = \"Computer\"; Console.WriteLine(\"Keyword : \" + key); // Function call to generate encoded text String encoded = encoder(key.ToCharArray()); // Message that need to encode String message = \"GeeksforGeeks\"; Console.WriteLine(\"Message before Ciphering : \" + message); // Function call to print ciphered text Console.WriteLine(\"Ciphered Text : \" + cipheredIt(message, encoded)); }} /* This code contributed by PrinciRaj1992 */",
"e": 35577,
"s": 32850,
"text": null
},
{
"code": "<script> // JavaScript program for encoding the string// using classical cipher // Function generates the encoded textfunction encoder(key){ let encoded = \"\"; // This array represents the // 26 letters of alphabets let arr = new Array(26); for(let i=0;i<26;i++) { arr[i]=false; } // This loop inserts the keyword // at the start of the encoded string for (let i = 0; i < key.length; i++) { if (key[i].charCodeAt(0) >= 'A'.charCodeAt(0) && key[i].charCodeAt(0) <= 'Z'.charCodeAt(0)) { // To check whether the character is inserted // earlier in the encoded string or not if (arr[key[i].charCodeAt(0) - 65] == false) { encoded += ( key[i]); arr[key[i].charCodeAt(0) - 65] = true; } } else if (key[i].charCodeAt(0) >= 'a'.charCodeAt(0) && key[i].charCodeAt(0) <= 'z'.charCodeAt(0)) { if (arr[key[i].charCodeAt(0) - 97] == false) { encoded += String.fromCharCode(key[i].charCodeAt(0) - 32); arr[key[i].charCodeAt(0) - 97] = true; } } } // This loop inserts the remaining // characters in the encoded string. for (let i = 0; i < 26; i++) { if (arr[i] == false) { arr[i] = true; encoded += String.fromCharCode(i + 65); } } return encoded;} // Function that generates encodes(cipher) the messagefunction cipheredIt(msg,encoded){ let cipher = \"\"; // This loop ciphered the message. // Spaces, special characters and numbers remain same. for (let i = 0; i < msg.length; i++) { if (msg[i] >= 'a' && msg[i] <= 'z') { let pos = msg[i].charCodeAt(0) - 97; cipher += encoded[pos]; } else if (msg[i] >= 'A' && msg[i] <= 'Z') { let pos = msg[i].charCodeAt(0) - 65; cipher += encoded[pos]; } else { cipher += msg[i]; } } return cipher;} // Driver code// Hold the Keywordlet key;key = \"Computer\";document.write(\"Keyword : \" + key+\"<br>\"); // Function call to generate encoded textlet encoded = encoder(key.split(\"\")); // Message that need to encodelet message = \"GeeksforGeeks\";document.write(\"Message before Ciphering : \" + message+\"<br>\"); // Function call to print ciphered textdocument.write(\"Ciphered Text : \" + cipheredIt(message, encoded)); // This code is contributed by rag2127 </script>",
"e": 38459,
"s": 35577,
"text": null
},
{
"code": null,
"e": 38469,
"s": 38459,
"text": "Output: "
},
{
"code": null,
"e": 38559,
"s": 38469,
"text": "Keyword : Computer\nMessage before Ciphering : GeeksforGeeks\nCiphered Text : EUUDNTILEUUDN"
},
{
"code": null,
"e": 38572,
"s": 38561,
"text": "Decryption"
},
{
"code": null,
"e": 39082,
"s": 38572,
"text": "To decode the message you check the position of the given message in encrypting text with the plain text.Plaintext: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z Encrypted: K R Y P T O S A B C D E F G H I J L M N Q U V W X ZMessage: PTYBIATLEP Deciphered Text: DECIPHEREDNow, how do we generate the deciphered string? We search for ‘P’ in Encrypted Text and compare its position with plain text letter and generate that letter. So ‘P’ becomes ‘D’, ‘T’ becomes ‘E’, ‘Y’ becomes ‘C’, and so on.Examples: "
},
{
"code": null,
"e": 39258,
"s": 39082,
"text": "Input :\nKeyword : secret\nMessage : zljeft dtOT\nOutput :\nDeciphered String : ZOMBIE HERE\n\nInput :\nKeyword : joker0O7hack123\nMessage : QjTijl\nOutput :\nDeciphered String : BATMAN"
},
{
"code": null,
"e": 39264,
"s": 39260,
"text": "CPP"
},
{
"code": "// CPP program for decoding the string// which generate using classical cipher #include<bits/stdc++.h>using namespace std; // Original Set of lettersstring plaintext = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"; // Function generates the encoded textstring encoder(string key){ string encoded = \"\"; bool arr[26] = {0}; // This loop inserts the keyword // at the start of the encoded string for (int i=0; i<key.size(); i++) { if(key[i] >= 'A' && key[i] <= 'Z') { // To check whether the character is inserted // earlier in the encoded string or not if (arr[key[i]-65] == 0) { encoded += key[i]; arr[key[i]-65] = 1; } } else if (key[i] >= 'a' && key[i] <= 'z') { if (arr[key[i]-97] == 0) { encoded += key[i] - 32; arr[key[i]-97] = 1; } } } // This loop inserts the remaining // characters in the encoded string. for (int i=0; i<26; i++) { if(arr[i] == 0) { arr[i]=1; encoded += char(i + 65); } } return encoded;} // This function will decode the messagestring decipheredIt(string msg, string encoded){ // Hold the position of every character (A-Z) // from encoded string map <char,int> enc; for(int i=0; i<encoded.size(); i++) { enc[encoded[i]]=i; } string decipher=\"\"; // This loop deciphered the message. // Spaces, special characters and numbers remain same. for (int i=0; i<msg.size(); i++) { if (msg[i] >='a' && msg[i] <='z') { int pos = enc[msg[i]-32]; decipher += plaintext[pos]; } else if(msg[i] >='A' && msg[i] <='Z') { int pos = enc[msg[i]]; decipher += plaintext[pos]; } else { decipher += msg[i]; } } return decipher;} // Driver codeint main(){ // Hold the Keyword string key; key = \"Computer\"; cout << \"Keyword : \"<< key << endl; // Function call to generate encoded text string encoded = encoder(key); // Message that need to decode string message = \"EUUDN TIL EUUDN\"; cout << \"Message before Deciphering : \" << message << endl; // Function call to print deciphered text cout << \"Deciphered Text : \" << decipheredIt(message,encoded) << endl; return 0;}",
"e": 41695,
"s": 39264,
"text": null
},
{
"code": null,
"e": 41705,
"s": 41695,
"text": "Output: "
},
{
"code": null,
"e": 41803,
"s": 41705,
"text": "Keyword : Computer\nMessage before Deciphering : EUUDN TIL EUUDN\nDeciphered Text : GEEKS FOR GEEKS"
},
{
"code": null,
"e": 42726,
"s": 41803,
"text": "You can improve this Classical Cipher: Keyword also. Here we are only taking A-Z in plain text. You can take uppercase, lowercase, and numbers also into consideration.Ways to attack a keyword cipher: The best ways to attack a keyword cipher without knowing the keyword are through the known-plaintext attack, frequency analysis, and discovery of the keyword (often a cryptanalyst will combine all three techniques). Keyword discovery allows immediate decryption since the table can be made immediately.This article is contributed by Sachin Bisht. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 42738,
"s": 42726,
"text": "29AjayKumar"
},
{
"code": null,
"e": 42752,
"s": 42738,
"text": "princiraj1992"
},
{
"code": null,
"e": 42760,
"s": 42752,
"text": "rag2127"
},
{
"code": null,
"e": 42778,
"s": 42760,
"text": "kumaripunam984122"
},
{
"code": null,
"e": 42794,
"s": 42778,
"text": "simranarora5sos"
},
{
"code": null,
"e": 42807,
"s": 42794,
"text": "cryptography"
},
{
"code": null,
"e": 42815,
"s": 42807,
"text": "Strings"
},
{
"code": null,
"e": 42823,
"s": 42815,
"text": "Strings"
},
{
"code": null,
"e": 42836,
"s": 42823,
"text": "cryptography"
},
{
"code": null,
"e": 42934,
"s": 42836,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42987,
"s": 42934,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 43023,
"s": 42987,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 43075,
"s": 43023,
"text": "Check whether two strings are anagram of each other"
},
{
"code": null,
"e": 43120,
"s": 43075,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 43181,
"s": 43120,
"text": "Length of the longest substring without repeating characters"
},
{
"code": null,
"e": 43213,
"s": 43181,
"text": "Reverse words in a given string"
},
{
"code": null,
"e": 43262,
"s": 43213,
"text": "How to split a string in C/C++, Python and Java?"
},
{
"code": null,
"e": 43300,
"s": 43262,
"text": "Remove duplicates from a given string"
},
{
"code": null,
"e": 43345,
"s": 43300,
"text": "Print all the duplicates in the input string"
}
] |
Laravel | Route::resource vs Route::controller - GeeksforGeeks
|
18 Apr, 2022
In Laravel, the Route actions can be controlled by any of the following two methods, either by using Route::resource method or by using Route::controller method. But both of them have their differences. Route::resource: The Route::resource method is a RESTful Controller that generates all the basic routes required for an application and can be easily handled using the controller class. It takes two arguments, where first is the base incoming request URI (Uniform Resource Identifier) and second is the class name of the controller which is used to handle the request. With this method, we get route names and path defined by default with 7 different actions which are required for any application. Note: To get the list of routes created, we have to use the command ‘PHP artisan route: list’ in the command line. Example:
routes.php
Route::resource(‘gfg’, ‘GeeksforGeeksController’);
Output:
Route::controller: The Route::controller method is an Implicit Controller which also takes two arguments and are same as Route::resource method i.e. first is the base incoming request URI (Uniform Resource Identifier) and second is the class name of the controller which is used to handle the request. With this method, we have a little flexibility in how we define our route names. There are no route names defined by default as there were with Route::resource method. Note: To get the list of routes created, you have to use the command ‘PHP artisan route: list’ in the command line. Example:
routes.php:
Route::controller(‘gfg’, ‘GeeksforGeeksController’);
GeeksforGeeksController.php: When no method is defined in the controller class file, then we get the output as shown below:
class GeeksforGeeksController extends Controller
{
// Handle request
}
Output:
GeeksforGeeksController.php: When we define get and post method in the controller class file, then we get the output as shown below.
class GeeksforGeeksController extends Controller
{
public function getGeek()
{
// Handle get request
}
public function postGeek($id)
{
// Handle post request
}
}
Output:
Before specifying either of the routes, you have to create the controller class which you want to use in the route. You can do that using a simple artisan command that is ‘PHP artisan make: controller GeeksforGeeksController’ i.e. ‘PHP artisan make: controller ’. The Route:Controller method had its support till Laravel 5.1 and is no longer supported by the versions after that. So, in the later versions of Laravel, we use Route::resource method.
sumitgumber28
Laravel
Picked
PHP
Technical Scripter
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Comparing two dates in PHP
How to receive JSON POST with PHP ?
Split a comma delimited string into an array in PHP
Download file from URL using PHP
How to get parameters from a URL string in PHP?
|
[
{
"code": null,
"e": 26703,
"s": 26675,
"text": "\n18 Apr, 2022"
},
{
"code": null,
"e": 27529,
"s": 26703,
"text": "In Laravel, the Route actions can be controlled by any of the following two methods, either by using Route::resource method or by using Route::controller method. But both of them have their differences. Route::resource: The Route::resource method is a RESTful Controller that generates all the basic routes required for an application and can be easily handled using the controller class. It takes two arguments, where first is the base incoming request URI (Uniform Resource Identifier) and second is the class name of the controller which is used to handle the request. With this method, we get route names and path defined by default with 7 different actions which are required for any application. Note: To get the list of routes created, we have to use the command ‘PHP artisan route: list’ in the command line. Example:"
},
{
"code": null,
"e": 27540,
"s": 27529,
"text": "routes.php"
},
{
"code": null,
"e": 27591,
"s": 27540,
"text": "Route::resource(‘gfg’, ‘GeeksforGeeksController’);"
},
{
"code": null,
"e": 27600,
"s": 27591,
"text": "Output: "
},
{
"code": null,
"e": 28195,
"s": 27600,
"text": "Route::controller: The Route::controller method is an Implicit Controller which also takes two arguments and are same as Route::resource method i.e. first is the base incoming request URI (Uniform Resource Identifier) and second is the class name of the controller which is used to handle the request. With this method, we have a little flexibility in how we define our route names. There are no route names defined by default as there were with Route::resource method. Note: To get the list of routes created, you have to use the command ‘PHP artisan route: list’ in the command line. Example:"
},
{
"code": null,
"e": 28207,
"s": 28195,
"text": "routes.php:"
},
{
"code": null,
"e": 28260,
"s": 28207,
"text": "Route::controller(‘gfg’, ‘GeeksforGeeksController’);"
},
{
"code": null,
"e": 28384,
"s": 28260,
"text": "GeeksforGeeksController.php: When no method is defined in the controller class file, then we get the output as shown below:"
},
{
"code": null,
"e": 28457,
"s": 28384,
"text": "class GeeksforGeeksController extends Controller\n{\n // Handle request\n}"
},
{
"code": null,
"e": 28466,
"s": 28457,
"text": "Output: "
},
{
"code": null,
"e": 28599,
"s": 28466,
"text": "GeeksforGeeksController.php: When we define get and post method in the controller class file, then we get the output as shown below."
},
{
"code": null,
"e": 28781,
"s": 28599,
"text": "class GeeksforGeeksController extends Controller\n{\n public function getGeek()\n {\n // Handle get request\n }\n public function postGeek($id)\n {\n // Handle post request\n }\n}"
},
{
"code": null,
"e": 28790,
"s": 28781,
"text": "Output: "
},
{
"code": null,
"e": 29239,
"s": 28790,
"text": "Before specifying either of the routes, you have to create the controller class which you want to use in the route. You can do that using a simple artisan command that is ‘PHP artisan make: controller GeeksforGeeksController’ i.e. ‘PHP artisan make: controller ’. The Route:Controller method had its support till Laravel 5.1 and is no longer supported by the versions after that. So, in the later versions of Laravel, we use Route::resource method."
},
{
"code": null,
"e": 29253,
"s": 29239,
"text": "sumitgumber28"
},
{
"code": null,
"e": 29261,
"s": 29253,
"text": "Laravel"
},
{
"code": null,
"e": 29268,
"s": 29261,
"text": "Picked"
},
{
"code": null,
"e": 29272,
"s": 29268,
"text": "PHP"
},
{
"code": null,
"e": 29291,
"s": 29272,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29295,
"s": 29291,
"text": "PHP"
},
{
"code": null,
"e": 29393,
"s": 29295,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29443,
"s": 29393,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 29483,
"s": 29443,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 29544,
"s": 29483,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 29594,
"s": 29544,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 29639,
"s": 29594,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 29666,
"s": 29639,
"text": "Comparing two dates in PHP"
},
{
"code": null,
"e": 29702,
"s": 29666,
"text": "How to receive JSON POST with PHP ?"
},
{
"code": null,
"e": 29754,
"s": 29702,
"text": "Split a comma delimited string into an array in PHP"
},
{
"code": null,
"e": 29787,
"s": 29754,
"text": "Download file from URL using PHP"
}
] |
Difference Between '+' and 'append' in Python - GeeksforGeeks
|
10 May, 2020
Using ‘+’ operator to add an element in the list in Python: The use of the ‘+’ operator causes Python to access each element of that first list. When ‘+’ is used a new list is created with space for one more element. Then all the elements from the old list must be copied to the new list and the new element is added at the end of this list.
Example:
sample_list =[]n = 10 for i in range(n): # i refers to new element sample_list = sample_list+[i] print(sample_list)
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
The ‘+’ operator refers to the accessor method and does not modify the original list.
In this, sample_list doesn’t change itself. This type of addition of element in sample_list creates a new list from the elements in the two lists.
The assignment of sample_list to this new list updates PythonList object so it now refers to the new list.
Have you wondered, how it works as the size of the Python List grows? Let us see with the explanation.
For every ith iteration, there will have to be i elements copied from the original list to form a new list. Considering the time taken to access an element from a list to be constant. So, the complexity or amount of time it takes to append n elements to the Python List i.e. sample_list we would have to add up all the list accesses and multiply by the amount of time it takes to access a list element plus the time it takes to store a list element. To count the total number of access and store operations we must start with the number of access and store operations for copying the list the first time an element is appended. That’s one element copied. The second append requires two copy operations. The third append requires three copy operations. So, we have the following number of list elements being copied.Therefore, time complexity=O()
Using .append() method i.e. an efficient approach: The .append() method on lists changes the code to use a mutator method to alter the list by appending just one more element.
Example:
sample_list =[]n = 10 for i in range(n): # i refers to new element sample_list.append(i) print(sample_list)
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
It turns out that adding one more element to an already existing list is very efficient in Python. In fact, adding a new item to a list is an O(1) operation.
So overall complexity to append n elements is
1+.....(n-2) times...+1=O(n)
Note: Proof that .append() method has O(1) complexity to add new element is given by the accounting method to find the amortized complexity of append.
python-list
python-list-functions
Difference Between
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference Between Method Overloading and Method Overriding in Java
Comparison between Adjacency List and Adjacency Matrix representation of Graph
Difference between Synchronous and Asynchronous Transmission
Difference between LAN, MAN and WAN
Difference between Prim's and Kruskal's algorithm for MST
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 24493,
"s": 24465,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 24835,
"s": 24493,
"text": "Using ‘+’ operator to add an element in the list in Python: The use of the ‘+’ operator causes Python to access each element of that first list. When ‘+’ is used a new list is created with space for one more element. Then all the elements from the old list must be copied to the new list and the new element is added at the end of this list."
},
{
"code": null,
"e": 24844,
"s": 24835,
"text": "Example:"
},
{
"code": "sample_list =[]n = 10 for i in range(n): # i refers to new element sample_list = sample_list+[i] print(sample_list)",
"e": 24974,
"s": 24844,
"text": null
},
{
"code": null,
"e": 24982,
"s": 24974,
"text": "Output:"
},
{
"code": null,
"e": 25013,
"s": 24982,
"text": "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
},
{
"code": null,
"e": 25099,
"s": 25013,
"text": "The ‘+’ operator refers to the accessor method and does not modify the original list."
},
{
"code": null,
"e": 25246,
"s": 25099,
"text": "In this, sample_list doesn’t change itself. This type of addition of element in sample_list creates a new list from the elements in the two lists."
},
{
"code": null,
"e": 25353,
"s": 25246,
"text": "The assignment of sample_list to this new list updates PythonList object so it now refers to the new list."
},
{
"code": null,
"e": 25456,
"s": 25353,
"text": "Have you wondered, how it works as the size of the Python List grows? Let us see with the explanation."
},
{
"code": null,
"e": 26302,
"s": 25456,
"text": "For every ith iteration, there will have to be i elements copied from the original list to form a new list. Considering the time taken to access an element from a list to be constant. So, the complexity or amount of time it takes to append n elements to the Python List i.e. sample_list we would have to add up all the list accesses and multiply by the amount of time it takes to access a list element plus the time it takes to store a list element. To count the total number of access and store operations we must start with the number of access and store operations for copying the list the first time an element is appended. That’s one element copied. The second append requires two copy operations. The third append requires three copy operations. So, we have the following number of list elements being copied.Therefore, time complexity=O()"
},
{
"code": null,
"e": 26478,
"s": 26302,
"text": "Using .append() method i.e. an efficient approach: The .append() method on lists changes the code to use a mutator method to alter the list by appending just one more element."
},
{
"code": null,
"e": 26487,
"s": 26478,
"text": "Example:"
},
{
"code": "sample_list =[]n = 10 for i in range(n): # i refers to new element sample_list.append(i) print(sample_list)",
"e": 26604,
"s": 26487,
"text": null
},
{
"code": null,
"e": 26612,
"s": 26604,
"text": "Output:"
},
{
"code": null,
"e": 26644,
"s": 26612,
"text": "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n"
},
{
"code": null,
"e": 26802,
"s": 26644,
"text": "It turns out that adding one more element to an already existing list is very efficient in Python. In fact, adding a new item to a list is an O(1) operation."
},
{
"code": null,
"e": 26848,
"s": 26802,
"text": "So overall complexity to append n elements is"
},
{
"code": null,
"e": 26877,
"s": 26848,
"text": "1+.....(n-2) times...+1=O(n)"
},
{
"code": null,
"e": 27028,
"s": 26877,
"text": "Note: Proof that .append() method has O(1) complexity to add new element is given by the accounting method to find the amortized complexity of append."
},
{
"code": null,
"e": 27040,
"s": 27028,
"text": "python-list"
},
{
"code": null,
"e": 27062,
"s": 27040,
"text": "python-list-functions"
},
{
"code": null,
"e": 27081,
"s": 27062,
"text": "Difference Between"
},
{
"code": null,
"e": 27088,
"s": 27081,
"text": "Python"
},
{
"code": null,
"e": 27100,
"s": 27088,
"text": "python-list"
},
{
"code": null,
"e": 27198,
"s": 27100,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27207,
"s": 27198,
"text": "Comments"
},
{
"code": null,
"e": 27220,
"s": 27207,
"text": "Old Comments"
},
{
"code": null,
"e": 27288,
"s": 27220,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 27367,
"s": 27288,
"text": "Comparison between Adjacency List and Adjacency Matrix representation of Graph"
},
{
"code": null,
"e": 27428,
"s": 27367,
"text": "Difference between Synchronous and Asynchronous Transmission"
},
{
"code": null,
"e": 27464,
"s": 27428,
"text": "Difference between LAN, MAN and WAN"
},
{
"code": null,
"e": 27522,
"s": 27464,
"text": "Difference between Prim's and Kruskal's algorithm for MST"
},
{
"code": null,
"e": 27550,
"s": 27522,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 27600,
"s": 27550,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 27622,
"s": 27600,
"text": "Python map() function"
}
] |
How to use PowerShell Help commands?
|
To get help for the particular command, you can use Get-Help (alias: help) cmdlet with the command that you need help.
For example,
help Get-Service
Once you run this command, you will get the description of NAME, SYNOPSIS, SYNTAX, DESCRIPTION, RELATED LINKS, and REMARKS.
Multiple parameters that support help as shown below
-Full − Detailed help with parameter explanation and examples.
-Full − Detailed help with parameter explanation and examples.
help Get-Service -Full
-Detailed − Detailed help of parameters and doesn’t include the examples.
-Detailed − Detailed help of parameters and doesn’t include the examples.
help Get-Service -Detailed
-Examples − Only help related to examples will be displayed on the PowerShell screen.
-Examples − Only help related to examples will be displayed on the PowerShell screen.
help Get-Service -Examples
-Online − Help contents for the cmdlet will be searched online on the Microsoft website.
-Online − Help contents for the cmdlet will be searched online on the Microsoft website.
help Get-Service -Online
When you install or update PowerShell version or install a new operating system that comes with the PowerShell installed then you need to make sure to update the help content from Microsoft website and that can be done using Update-Help command and that is recommended once in a month because some help contents get outdated and MS continuously updates their help content.
Some help for cmdlets is not visible if the outdated help resides in your system at that time you need to update the help content.
When -ShowWindow parameter is specified, help will be displayed in the separate window for that specific command. For example,
help Get-Service -ShowWindow
Here, in the Settings button, there are options to filter out specific items.
If you need any specific section(s) related help the select that setting(s).
If you need help with the parameters in command line then use -Parameter and command name. For example,
help Get-Service -Parameter ComputerName
PS C:\Users\Chirag.Nagarekar> help Get-Service -Parameter ComputerName -ComputerName <System.String[]>
Gets the services running on the specified computers. The default is the local computer.
Type the NetBIOS name, an IP address, or a fully qualified domain name (FQDN)
of a remote computer. To specify the local computer, type the
computer name, a dot (.), or localhost.
This parameter does not rely on Windows PowerShell remoting. You can use the
ComputerName parameter of Get-Service even if your computer is not configured to run remote commands.
Required? false
Position? named
Default value None
Accept pipeline input? True (ByPropertyName)
Accept wildcard characters? false
If you need to display all the parameters then use * instead of the parameter name.
help Get-Service -Parameter *
Similarly, if you need help related to only example sections in command line then use -Examples in command.
help Get-Service -Examples
|
[
{
"code": null,
"e": 1182,
"s": 1062,
"text": "To get help for the particular command, you can use Get-Help (alias: help) cmdlet with the command that you need help."
},
{
"code": null,
"e": 1195,
"s": 1182,
"text": "For example,"
},
{
"code": null,
"e": 1212,
"s": 1195,
"text": "help Get-Service"
},
{
"code": null,
"e": 1336,
"s": 1212,
"text": "Once you run this command, you will get the description of NAME, SYNOPSIS, SYNTAX, DESCRIPTION, RELATED LINKS, and REMARKS."
},
{
"code": null,
"e": 1389,
"s": 1336,
"text": "Multiple parameters that support help as shown below"
},
{
"code": null,
"e": 1452,
"s": 1389,
"text": "-Full − Detailed help with parameter explanation and examples."
},
{
"code": null,
"e": 1515,
"s": 1452,
"text": "-Full − Detailed help with parameter explanation and examples."
},
{
"code": null,
"e": 1538,
"s": 1515,
"text": "help Get-Service -Full"
},
{
"code": null,
"e": 1612,
"s": 1538,
"text": "-Detailed − Detailed help of parameters and doesn’t include the examples."
},
{
"code": null,
"e": 1686,
"s": 1612,
"text": "-Detailed − Detailed help of parameters and doesn’t include the examples."
},
{
"code": null,
"e": 1713,
"s": 1686,
"text": "help Get-Service -Detailed"
},
{
"code": null,
"e": 1799,
"s": 1713,
"text": "-Examples − Only help related to examples will be displayed on the PowerShell screen."
},
{
"code": null,
"e": 1885,
"s": 1799,
"text": "-Examples − Only help related to examples will be displayed on the PowerShell screen."
},
{
"code": null,
"e": 1913,
"s": 1885,
"text": "help Get-Service -Examples\n"
},
{
"code": null,
"e": 2002,
"s": 1913,
"text": "-Online − Help contents for the cmdlet will be searched online on the Microsoft website."
},
{
"code": null,
"e": 2091,
"s": 2002,
"text": "-Online − Help contents for the cmdlet will be searched online on the Microsoft website."
},
{
"code": null,
"e": 2116,
"s": 2091,
"text": "help Get-Service -Online"
},
{
"code": null,
"e": 2489,
"s": 2116,
"text": "When you install or update PowerShell version or install a new operating system that comes with the PowerShell installed then you need to make sure to update the help content from Microsoft website and that can be done using Update-Help command and that is recommended once in a month because some help contents get outdated and MS continuously updates their help content."
},
{
"code": null,
"e": 2620,
"s": 2489,
"text": "Some help for cmdlets is not visible if the outdated help resides in your system at that time you need to update the help content."
},
{
"code": null,
"e": 2747,
"s": 2620,
"text": "When -ShowWindow parameter is specified, help will be displayed in the separate window for that specific command. For example,"
},
{
"code": null,
"e": 2776,
"s": 2747,
"text": "help Get-Service -ShowWindow"
},
{
"code": null,
"e": 2854,
"s": 2776,
"text": "Here, in the Settings button, there are options to filter out specific items."
},
{
"code": null,
"e": 2931,
"s": 2854,
"text": "If you need any specific section(s) related help the select that setting(s)."
},
{
"code": null,
"e": 3035,
"s": 2931,
"text": "If you need help with the parameters in command line then use -Parameter and command name. For example,"
},
{
"code": null,
"e": 3076,
"s": 3035,
"text": "help Get-Service -Parameter ComputerName"
},
{
"code": null,
"e": 3759,
"s": 3076,
"text": "PS C:\\Users\\Chirag.Nagarekar> help Get-Service -Parameter ComputerName -ComputerName <System.String[]>\nGets the services running on the specified computers. The default is the local computer.\nType the NetBIOS name, an IP address, or a fully qualified domain name (FQDN)\nof a remote computer. To specify the local computer, type the\ncomputer name, a dot (.), or localhost.\n\nThis parameter does not rely on Windows PowerShell remoting. You can use the\nComputerName parameter of Get-Service even if your computer is not configured to run remote commands.\n\nRequired? false\nPosition? named\nDefault value None\nAccept pipeline input? True (ByPropertyName)\nAccept wildcard characters? false"
},
{
"code": null,
"e": 3843,
"s": 3759,
"text": "If you need to display all the parameters then use * instead of the parameter name."
},
{
"code": null,
"e": 3873,
"s": 3843,
"text": "help Get-Service -Parameter *"
},
{
"code": null,
"e": 3981,
"s": 3873,
"text": "Similarly, if you need help related to only example sections in command line then use -Examples in command."
},
{
"code": null,
"e": 4008,
"s": 3981,
"text": "help Get-Service -Examples"
}
] |
How to Change Apache Default Web Root Folder to a New Location on Ubuntu 16.04
|
In this article, we will learn how to change the Apache default web root folder to a new location. By default, the Apache web root or Document root folder location is at /var/www/html.
These type of changes will be useful for security reason or having the space issue due to data size, we want to change the document root folder to another location or mount point. This will be helpful if we have multiple instances and we want to keep the data for each website into their own volumes or folders.
An Ubuntu 16.04 server with a user with Sudo permissions on the machine.
Apache2 web server installed on the machine
A new mount location or the new folder location for moving the Site information or files.
As we already have knowledge that, the default location of the Apache web server is /var/www/html, or if you have a different setup with multiple sites with multiple document roots for different sites.
If we have a multiple site which configured and enabled in the Virtual Host of the Apache, we can search for the document root in the /etc/apache2/sites-enabled folder.
Below is the command to find the folder name for all the multiple sites published in the server.
$ grep –R “DocumentRoot” /etc/apache2/sites-enabled
Since I have only one site, enable the output will be like this –
sites-enabled/000-default.conf DocumentRoot /var/www/html
Using the rsync command we will copy all the files to a new folder location where we want to move the default document root folder of the Apache web server.
For example, in our environment the new web root document folder will be ‘/mnt/newdatavol’
$ sudo rysnc –av /var/www/html /mnt/newdatavol
Apache uses two types of configuration files, one is global and another is site-specific configurations, as we are working with the existing installation. We will modify the virtual host files which are found using the grep command.
By default, we have to change two virtual host configuration files which come with Apache 000-default.conf and default-ssl.conf.
$ sudo vi /etc/apache2/sites-enabled/000-default.conf
<VirtualHost *:80>
# The ServerName directive sets the request scheme, hostname and port that
# the server uses to identify itself. This is used when creating
# redirection URLs. In the context of virtual hosts, the ServerName
# specifies what hostname must appear in the request's Host: header to
# match this virtual host. For the default virtual host (this file) this
# value is not decisive as it is used as a last resort host regardless.
# However, you must set it for any further virtual host explicitly.
#ServerName www.example.com
ServerAdmin webmaster@localhost
DocumentRoot /mnt/newdatavol
# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the loglevel for particular
# modules, e.g.
#LogLevel info ssl:warn
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
# For most configuration files from conf-available/, which are
# enabled or disabled at a global level, it is possible to
# include a line for only one particular virtual host. For example the
# following line enables the CGI configuration for this host only
# after it has been globally disabled with "a2disconf".
#Include conf-available/serve-cgi-bin.conf
</VirtualHost>
We save the file and now we will change the default folder location for the Apache web server for SSL port below to see the command to edit the default-ssl.conf
$ sudo vi /etc/apache2/sites-available/default-ssl.conf
<IfModule mod_ssl.c>
<VirtualHost _default_:443>
ServerAdmin webmaster@localhost
DocumentRoot /mnt/newdatavol
# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the loglevel for particular
# modules, e.g.
#LogLevel info ssl:warn
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
# For most configuration files from conf-available/, which are
# enabled or disabled at a global level, it is possible to
# include a line for only one particular virtual host. For example the
# following line enables the CGI configuration for this host only
# after it has been globally disabled with "a2disconf".
#Include conf-available/serve-cgi-bin.conf
# SSL Engine Switch:
# Enable/Disable SSL for this
....
..
..
</VirtualHost>
Once we change the configuration changes to the Default document root, we need to restart the Apache server to make the changes effect. Before that we will check for the syntax errors
$ sudo apachectl configtest
Syntax OK
As we can see the message Syntax OK, now we can go ahead and restart the server to make changes effective.
$ sudo systemctl restart apache2
In the above article we have learned how to change the default Document location for the Apache server on Ubuntu 16.04. This will be easy to take backup of the sites which we published without any system default files and they are useful when we have multiple sites or client website data in a different location. We can also use other network storage devices such as NAS and SAN to store the date safely.
|
[
{
"code": null,
"e": 1247,
"s": 1062,
"text": "In this article, we will learn how to change the Apache default web root folder to a new location. By default, the Apache web root or Document root folder location is at /var/www/html."
},
{
"code": null,
"e": 1559,
"s": 1247,
"text": "These type of changes will be useful for security reason or having the space issue due to data size, we want to change the document root folder to another location or mount point. This will be helpful if we have multiple instances and we want to keep the data for each website into their own volumes or folders."
},
{
"code": null,
"e": 1632,
"s": 1559,
"text": "An Ubuntu 16.04 server with a user with Sudo permissions on the machine."
},
{
"code": null,
"e": 1676,
"s": 1632,
"text": "Apache2 web server installed on the machine"
},
{
"code": null,
"e": 1766,
"s": 1676,
"text": "A new mount location or the new folder location for moving the Site information or files."
},
{
"code": null,
"e": 1968,
"s": 1766,
"text": "As we already have knowledge that, the default location of the Apache web server is /var/www/html, or if you have a different setup with multiple sites with multiple document roots for different sites."
},
{
"code": null,
"e": 2137,
"s": 1968,
"text": "If we have a multiple site which configured and enabled in the Virtual Host of the Apache, we can search for the document root in the /etc/apache2/sites-enabled folder."
},
{
"code": null,
"e": 2234,
"s": 2137,
"text": "Below is the command to find the folder name for all the multiple sites published in the server."
},
{
"code": null,
"e": 2286,
"s": 2234,
"text": "$ grep –R “DocumentRoot” /etc/apache2/sites-enabled"
},
{
"code": null,
"e": 2352,
"s": 2286,
"text": "Since I have only one site, enable the output will be like this –"
},
{
"code": null,
"e": 2410,
"s": 2352,
"text": "sites-enabled/000-default.conf DocumentRoot /var/www/html"
},
{
"code": null,
"e": 2567,
"s": 2410,
"text": "Using the rsync command we will copy all the files to a new folder location where we want to move the default document root folder of the Apache web server."
},
{
"code": null,
"e": 2658,
"s": 2567,
"text": "For example, in our environment the new web root document folder will be ‘/mnt/newdatavol’"
},
{
"code": null,
"e": 2705,
"s": 2658,
"text": "$ sudo rysnc –av /var/www/html /mnt/newdatavol"
},
{
"code": null,
"e": 2938,
"s": 2705,
"text": "Apache uses two types of configuration files, one is global and another is site-specific configurations, as we are working with the existing installation. We will modify the virtual host files which are found using the grep command."
},
{
"code": null,
"e": 3067,
"s": 2938,
"text": "By default, we have to change two virtual host configuration files which come with Apache 000-default.conf and default-ssl.conf."
},
{
"code": null,
"e": 4451,
"s": 3067,
"text": "$ sudo vi /etc/apache2/sites-enabled/000-default.conf\n<VirtualHost *:80>\n # The ServerName directive sets the request scheme, hostname and port that\n # the server uses to identify itself. This is used when creating\n # redirection URLs. In the context of virtual hosts, the ServerName\n # specifies what hostname must appear in the request's Host: header to\n # match this virtual host. For the default virtual host (this file) this\n # value is not decisive as it is used as a last resort host regardless.\n # However, you must set it for any further virtual host explicitly.\n #ServerName www.example.com\n ServerAdmin webmaster@localhost\n DocumentRoot /mnt/newdatavol\n # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,\n # error, crit, alert, emerg.\n # It is also possible to configure the loglevel for particular\n # modules, e.g.\n #LogLevel info ssl:warn\n ErrorLog ${APACHE_LOG_DIR}/error.log\n CustomLog ${APACHE_LOG_DIR}/access.log combined\n # For most configuration files from conf-available/, which are\n # enabled or disabled at a global level, it is possible to\n # include a line for only one particular virtual host. For example the\n # following line enables the CGI configuration for this host only\n # after it has been globally disabled with \"a2disconf\".\n #Include conf-available/serve-cgi-bin.conf\n</VirtualHost>"
},
{
"code": null,
"e": 4612,
"s": 4451,
"text": "We save the file and now we will change the default folder location for the Apache web server for SSL port below to see the command to edit the default-ssl.conf"
},
{
"code": null,
"e": 5561,
"s": 4612,
"text": "$ sudo vi /etc/apache2/sites-available/default-ssl.conf\n<IfModule mod_ssl.c>\n<VirtualHost _default_:443>\n ServerAdmin webmaster@localhost\n DocumentRoot /mnt/newdatavol\n # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,\n # error, crit, alert, emerg.\n # It is also possible to configure the loglevel for particular\n # modules, e.g.\n #LogLevel info ssl:warn\n ErrorLog ${APACHE_LOG_DIR}/error.log\n CustomLog ${APACHE_LOG_DIR}/access.log combined\n # For most configuration files from conf-available/, which are\n # enabled or disabled at a global level, it is possible to\n # include a line for only one particular virtual host. For example the\n # following line enables the CGI configuration for this host only\n # after it has been globally disabled with \"a2disconf\".\n #Include conf-available/serve-cgi-bin.conf\n # SSL Engine Switch:\n # Enable/Disable SSL for this\n ....\n ..\n ..\n</VirtualHost>"
},
{
"code": null,
"e": 5745,
"s": 5561,
"text": "Once we change the configuration changes to the Default document root, we need to restart the Apache server to make the changes effect. Before that we will check for the syntax errors"
},
{
"code": null,
"e": 5783,
"s": 5745,
"text": "$ sudo apachectl configtest\nSyntax OK"
},
{
"code": null,
"e": 5890,
"s": 5783,
"text": "As we can see the message Syntax OK, now we can go ahead and restart the server to make changes effective."
},
{
"code": null,
"e": 5923,
"s": 5890,
"text": "$ sudo systemctl restart apache2"
},
{
"code": null,
"e": 6329,
"s": 5923,
"text": "In the above article we have learned how to change the default Document location for the Apache server on Ubuntu 16.04. This will be easy to take backup of the sites which we published without any system default files and they are useful when we have multiple sites or client website data in a different location. We can also use other network storage devices such as NAS and SAN to store the date safely."
}
] |
Solidity - View Functions
|
View functions ensure that they will not modify the state. A function can be declared as view. The following statements if present in the function are considered modifying the state and compiler will throw warning in such cases.
Modifying state variables.
Modifying state variables.
Emitting events.
Emitting events.
Creating other contracts.
Creating other contracts.
Using selfdestruct.
Using selfdestruct.
Sending Ether via calls.
Sending Ether via calls.
Calling any function which is not marked view or pure.
Calling any function which is not marked view or pure.
Using low-level calls.
Using low-level calls.
Using inline assembly containing certain opcodes.
Using inline assembly containing certain opcodes.
Getter method are by default view functions.
See the example below using a view function.
pragma solidity ^0.5.0;
contract Test {
function getResult() public view returns(uint product, uint sum){
uint a = 1; // local variable
uint b = 2;
product = a * b;
sum = a + b;
}
}
Run the above program using steps provided in Solidity First Application chapter.
0: uint256: product 2
1: uint256: sum 3
38 Lectures
4.5 hours
Abhilash Nelson
62 Lectures
8.5 hours
Frahaan Hussain
31 Lectures
3.5 hours
Swapnil Kole
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2784,
"s": 2555,
"text": "View functions ensure that they will not modify the state. A function can be declared as view. The following statements if present in the function are considered modifying the state and compiler will throw warning in such cases."
},
{
"code": null,
"e": 2811,
"s": 2784,
"text": "Modifying state variables."
},
{
"code": null,
"e": 2838,
"s": 2811,
"text": "Modifying state variables."
},
{
"code": null,
"e": 2855,
"s": 2838,
"text": "Emitting events."
},
{
"code": null,
"e": 2872,
"s": 2855,
"text": "Emitting events."
},
{
"code": null,
"e": 2898,
"s": 2872,
"text": "Creating other contracts."
},
{
"code": null,
"e": 2924,
"s": 2898,
"text": "Creating other contracts."
},
{
"code": null,
"e": 2944,
"s": 2924,
"text": "Using selfdestruct."
},
{
"code": null,
"e": 2964,
"s": 2944,
"text": "Using selfdestruct."
},
{
"code": null,
"e": 2989,
"s": 2964,
"text": "Sending Ether via calls."
},
{
"code": null,
"e": 3014,
"s": 2989,
"text": "Sending Ether via calls."
},
{
"code": null,
"e": 3069,
"s": 3014,
"text": "Calling any function which is not marked view or pure."
},
{
"code": null,
"e": 3124,
"s": 3069,
"text": "Calling any function which is not marked view or pure."
},
{
"code": null,
"e": 3147,
"s": 3124,
"text": "Using low-level calls."
},
{
"code": null,
"e": 3170,
"s": 3147,
"text": "Using low-level calls."
},
{
"code": null,
"e": 3220,
"s": 3170,
"text": "Using inline assembly containing certain opcodes."
},
{
"code": null,
"e": 3270,
"s": 3220,
"text": "Using inline assembly containing certain opcodes."
},
{
"code": null,
"e": 3315,
"s": 3270,
"text": "Getter method are by default view functions."
},
{
"code": null,
"e": 3360,
"s": 3315,
"text": "See the example below using a view function."
},
{
"code": null,
"e": 3574,
"s": 3360,
"text": "pragma solidity ^0.5.0;\n\ncontract Test {\n function getResult() public view returns(uint product, uint sum){\n uint a = 1; // local variable\n uint b = 2;\n product = a * b;\n sum = a + b; \n }\n}"
},
{
"code": null,
"e": 3656,
"s": 3574,
"text": "Run the above program using steps provided in Solidity First Application chapter."
},
{
"code": null,
"e": 3697,
"s": 3656,
"text": "0: uint256: product 2\n1: uint256: sum 3\n"
},
{
"code": null,
"e": 3732,
"s": 3697,
"text": "\n 38 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3749,
"s": 3732,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3784,
"s": 3749,
"text": "\n 62 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3801,
"s": 3784,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3836,
"s": 3801,
"text": "\n 31 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3850,
"s": 3836,
"text": " Swapnil Kole"
},
{
"code": null,
"e": 3857,
"s": 3850,
"text": " Print"
},
{
"code": null,
"e": 3868,
"s": 3857,
"text": " Add Notes"
}
] |
How to Speedup Pandas with with One-Line change using Modin ? - GeeksforGeeks
|
15 Mar, 2021
In this article, we are going to see how to increase the speed of computation of the pandas using modin library. Modin is a python library very similar to pandas (almost identical in terms of syntax) capable of handling a huge dataset that cannot fit into RAM in one go. Pandas are good enough in terms of speed of execution for datasets in size of in MB’s and few GB’s but when we are dealing with really large datasets speed to process the data becomes the bottleneck.
Pandas library was designed to work on single-core and therefore with modern age compute power every personal laptop comes with now at least 2 cores and Modin just exploits this opportunity of executing the operations on all available cores thus speeding up the whole process.
To install Modin and all it’s dependencies use any of the below pip commands.
pip install modin[ray]
Or,
pip install modin[dask]
Or,
pip install modin[all]
To limit the number of CPUs to use we can add the below 2 lines of code in your script
import os
# this specifies the number of
# CPUs to use.
os.environ["MODIN_CPUS"] = "2"
Example 1: Dataframe Append Operation:
Append() operations are very common in pandas and in the code below here we have demonstrated this by running it 10 times using both pandas and Modin and timed it against each other to see the speedup difference. Clearly, Modin beats pandas as it uses all the cores available on my system. Also using the time module to measure the operations speed to compare with each other, and it turns out that Modin is 25x Times faster than pandas in this case.
Code:
Python3
import pandas as pdimport modin.pandas as mpdimport time start = time.time() # Creating a Custom Dataframedata = {'Name': ['Tom', 'nick', 'krish', 'jack', 'ash', 'singh', 'shilpa', 'nav'], 'Age': [20, 21, 19, 18, 6, 12, 18, 20]} df = pd.DataFrame(data) # Appending the dataframe to itself 10 times.for _ in range(10): df = df.append(df) end = time.time()print(f"Pandas Appending Time :{end-start}") start = time.time()modin_df = mpd.DataFrame(data) # Appending the dataframe to itself 10 times.for _ in range(10): modin_df = modin_df.append(modin_df) end = time.time()print(f"Modin Appending Time :{end-start}")
Output:
Pandas Appending Time :0.682852745056152
Modin Appending Time :0.027661800384521484
Example 2: Modin is 4.4x Times faster than pandas.
Here we are using a CSV file of size 602 MB which can be downloaded from this link. Also renamed the file as demo.csv to keep it short. In the code below here we used fillna() method which goes through the entire DataFrame and fills all NaN values with the desired value in my example it’s 0.
Code:
Python3
import pandas as pdimport modin.pandas as mpd # Reading demo.csv file into pandas dfdf = pd.read_csv("demo.csv") s = time.time()df = df.fillna(value=0) e = time.time()print(f"Pandas fillna Time: {e-s}) # Reading demo.csv file into modin dfmodin_df = mpd.read_csv("demo.csv")s = time.time() modin_df = modin_df.fillna(value=0)e = time.time()print(f"Modin fillna Time: {e - s})
Output:
Pandas fillna Time: 1.2 sec
Modin fillna Time: 0.27 sec
python-modules
Python-pandas
Python
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": "\n15 Mar, 2021"
},
{
"code": null,
"e": 24372,
"s": 23901,
"text": "In this article, we are going to see how to increase the speed of computation of the pandas using modin library. Modin is a python library very similar to pandas (almost identical in terms of syntax) capable of handling a huge dataset that cannot fit into RAM in one go. Pandas are good enough in terms of speed of execution for datasets in size of in MB’s and few GB’s but when we are dealing with really large datasets speed to process the data becomes the bottleneck."
},
{
"code": null,
"e": 24649,
"s": 24372,
"text": "Pandas library was designed to work on single-core and therefore with modern age compute power every personal laptop comes with now at least 2 cores and Modin just exploits this opportunity of executing the operations on all available cores thus speeding up the whole process."
},
{
"code": null,
"e": 24727,
"s": 24649,
"text": "To install Modin and all it’s dependencies use any of the below pip commands."
},
{
"code": null,
"e": 24751,
"s": 24727,
"text": "pip install modin[ray] "
},
{
"code": null,
"e": 24755,
"s": 24751,
"text": "Or,"
},
{
"code": null,
"e": 24780,
"s": 24755,
"text": "pip install modin[dask] "
},
{
"code": null,
"e": 24784,
"s": 24780,
"text": "Or,"
},
{
"code": null,
"e": 24808,
"s": 24784,
"text": "pip install modin[all] "
},
{
"code": null,
"e": 24895,
"s": 24808,
"text": "To limit the number of CPUs to use we can add the below 2 lines of code in your script"
},
{
"code": null,
"e": 24984,
"s": 24895,
"text": "import os\n\n# this specifies the number of\n# CPUs to use. \nos.environ[\"MODIN_CPUS\"] = \"2\""
},
{
"code": null,
"e": 25023,
"s": 24984,
"text": "Example 1: Dataframe Append Operation:"
},
{
"code": null,
"e": 25474,
"s": 25023,
"text": "Append() operations are very common in pandas and in the code below here we have demonstrated this by running it 10 times using both pandas and Modin and timed it against each other to see the speedup difference. Clearly, Modin beats pandas as it uses all the cores available on my system. Also using the time module to measure the operations speed to compare with each other, and it turns out that Modin is 25x Times faster than pandas in this case."
},
{
"code": null,
"e": 25480,
"s": 25474,
"text": "Code:"
},
{
"code": null,
"e": 25488,
"s": 25480,
"text": "Python3"
},
{
"code": "import pandas as pdimport modin.pandas as mpdimport time start = time.time() # Creating a Custom Dataframedata = {'Name': ['Tom', 'nick', 'krish', 'jack', 'ash', 'singh', 'shilpa', 'nav'], 'Age': [20, 21, 19, 18, 6, 12, 18, 20]} df = pd.DataFrame(data) # Appending the dataframe to itself 10 times.for _ in range(10): df = df.append(df) end = time.time()print(f\"Pandas Appending Time :{end-start}\") start = time.time()modin_df = mpd.DataFrame(data) # Appending the dataframe to itself 10 times.for _ in range(10): modin_df = modin_df.append(modin_df) end = time.time()print(f\"Modin Appending Time :{end-start}\")",
"e": 26155,
"s": 25488,
"text": null
},
{
"code": null,
"e": 26163,
"s": 26155,
"text": "Output:"
},
{
"code": null,
"e": 26247,
"s": 26163,
"text": "Pandas Appending Time :0.682852745056152\nModin Appending Time :0.027661800384521484"
},
{
"code": null,
"e": 26298,
"s": 26247,
"text": "Example 2: Modin is 4.4x Times faster than pandas."
},
{
"code": null,
"e": 26591,
"s": 26298,
"text": "Here we are using a CSV file of size 602 MB which can be downloaded from this link. Also renamed the file as demo.csv to keep it short. In the code below here we used fillna() method which goes through the entire DataFrame and fills all NaN values with the desired value in my example it’s 0."
},
{
"code": null,
"e": 26597,
"s": 26591,
"text": "Code:"
},
{
"code": null,
"e": 26605,
"s": 26597,
"text": "Python3"
},
{
"code": "import pandas as pdimport modin.pandas as mpd # Reading demo.csv file into pandas dfdf = pd.read_csv(\"demo.csv\") s = time.time()df = df.fillna(value=0) e = time.time()print(f\"Pandas fillna Time: {e-s}) # Reading demo.csv file into modin dfmodin_df = mpd.read_csv(\"demo.csv\")s = time.time() modin_df = modin_df.fillna(value=0)e = time.time()print(f\"Modin fillna Time: {e - s})",
"e": 26992,
"s": 26605,
"text": null
},
{
"code": null,
"e": 27000,
"s": 26992,
"text": "Output:"
},
{
"code": null,
"e": 27056,
"s": 27000,
"text": "Pandas fillna Time: 1.2 sec\nModin fillna Time: 0.27 sec"
},
{
"code": null,
"e": 27071,
"s": 27056,
"text": "python-modules"
},
{
"code": null,
"e": 27085,
"s": 27071,
"text": "Python-pandas"
},
{
"code": null,
"e": 27092,
"s": 27085,
"text": "Python"
},
{
"code": null,
"e": 27190,
"s": 27092,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27199,
"s": 27190,
"text": "Comments"
},
{
"code": null,
"e": 27212,
"s": 27199,
"text": "Old Comments"
},
{
"code": null,
"e": 27244,
"s": 27212,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27300,
"s": 27244,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27342,
"s": 27300,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27384,
"s": 27342,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27420,
"s": 27384,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 27442,
"s": 27420,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27481,
"s": 27442,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27508,
"s": 27481,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27539,
"s": 27508,
"text": "Python | os.path.join() method"
}
] |
Salesforce Interview Experience | Set 1 (For SDE-1)
|
28 Jun, 2021
I have recently attended an interview with Salesforce Hyderabad, for SDE-I position. There are 5 rounds in total, all are technical.
I. Programming Round: 1. Find the diameter of a binary treeHere the diameter is maximum number of nodes possible in the tree, formed by two leaf nodes. It can pass through the root or need not be.
2. Rotate an m by m matrix by 90 degrees.
i/p: {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}}
o/p: {{13, 9, 5, 1},
{14, 10, 6, 2},
{15, 11, 7, 3},
{16, 12, 8, 4}}
3. Given an array containing positive and negative numbers, find all the sub arrays in it, whose sum is equal to zero.
Solution: Maintain hashmap and insert the sum till now for every element and its index position –> HashMap For each element, check the following 3 cases: a) whether the element is “zero” ==> start and end indices both are “current index” b) whether the sum is “zero” ==> start index is 0 and end index is “current index” c) whether the sum is already present ==> start index is “map.get(sum)+1”, end index is “current index”
II. Technical Round 1:
1. Given a time in hours and minutes, find the angle between hours and minutes pointers in analog clock.
2. Given two arrays of equal size. First Array represents in the arrival timings of trains and second array represents the departure timings of the same trains. Now with the above two arrays data, give the number of platforms required to accommodate the trains.
3. Given an array containing integers, in which the elements are repeated multiple times. Now sort the array wrt the frequency of numbers.
eg: i/p: 2, 4, 5, 2, 1, 9, 3, 2, 2, 5, 1, 5
o/p: 2, 2, 2, 2, 5, 5, 5, 1, 1, 4, 3, 9
4. Write code for Deadlock in Multi Threading.
III. Technical Round 2:
Given a url containing the domain name and product it, like:www.amazon.in/pid=1234 By passing this url to utility functions, you can get all information about it. getProductName(url) –> Gives you the product name getProductPrice(url) –> Gives you the price of the product getRelatedProducts(url) –> Other products related to the current product, in which also user might be interested.
Now given a product url, print the information about it completely, including all its related products. What is the data structure that you will consider to represent the above product data and write class structure for the same.
IV. Presentation Round:
A technical topic will be given and you have to speak on it in front of a group of 5-6 people.You will be given 1 hour of time to prepare, a system with internet. You can present the topic either on board or with ppt also. The aim of this round is to check the candidates learning capability on a new topic, his presentation skills.
The topic given to me is “Apache Flink”
Since I got mixed response for this round, they conducted another technical round.
V. Technical Round 3:
1. Design an LRU(Least Recently Used) Cache. What is Cache and define LRU Cache? What data structure do you use and what is the time complexity?
Solution: Take one hashmap and linked list HashMap contains the key as data and value as its address in the linked list Linked list will maintain the elements in their usage order, with the last used item at the start of the list.
This way the least recently used is at the end of the list always.
2. Explain about HashMap internal implementation and write code for the same.
If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
All Practice Problems for Salesforce !
Salesforce
Interview Experiences
Salesforce
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 186,
"s": 52,
"text": "I have recently attended an interview with Salesforce Hyderabad, for SDE-I position. There are 5 rounds in total, all are technical. "
},
{
"code": null,
"e": 384,
"s": 186,
"text": "I. Programming Round: 1. Find the diameter of a binary treeHere the diameter is maximum number of nodes possible in the tree, formed by two leaf nodes. It can pass through the root or need not be. "
},
{
"code": null,
"e": 426,
"s": 384,
"text": "2. Rotate an m by m matrix by 90 degrees."
},
{
"code": null,
"e": 613,
"s": 426,
"text": "i/p: {{1, 2, 3, 4},\n {5, 6, 7, 8},\n {9, 10, 11, 12},\n {13, 14, 15, 16}}\n \no/p: {{13, 9, 5, 1},\n {14, 10, 6, 2},\n {15, 11, 7, 3},\n {16, 12, 8, 4}}\n"
},
{
"code": null,
"e": 733,
"s": 613,
"text": "3. Given an array containing positive and negative numbers, find all the sub arrays in it, whose sum is equal to zero. "
},
{
"code": null,
"e": 1159,
"s": 733,
"text": "Solution: Maintain hashmap and insert the sum till now for every element and its index position –> HashMap For each element, check the following 3 cases: a) whether the element is “zero” ==> start and end indices both are “current index” b) whether the sum is “zero” ==> start index is 0 and end index is “current index” c) whether the sum is already present ==> start index is “map.get(sum)+1”, end index is “current index” "
},
{
"code": null,
"e": 1183,
"s": 1159,
"text": "II. Technical Round 1: "
},
{
"code": null,
"e": 1289,
"s": 1183,
"text": "1. Given a time in hours and minutes, find the angle between hours and minutes pointers in analog clock. "
},
{
"code": null,
"e": 1552,
"s": 1289,
"text": "2. Given two arrays of equal size. First Array represents in the arrival timings of trains and second array represents the departure timings of the same trains. Now with the above two arrays data, give the number of platforms required to accommodate the trains. "
},
{
"code": null,
"e": 1692,
"s": 1552,
"text": "3. Given an array containing integers, in which the elements are repeated multiple times. Now sort the array wrt the frequency of numbers. "
},
{
"code": null,
"e": 1784,
"s": 1692,
"text": "eg: i/p: 2, 4, 5, 2, 1, 9, 3, 2, 2, 5, 1, 5\n o/p: 2, 2, 2, 2, 5, 5, 5, 1, 1, 4, 3, 9\n"
},
{
"code": null,
"e": 1832,
"s": 1784,
"text": "4. Write code for Deadlock in Multi Threading. "
},
{
"code": null,
"e": 1857,
"s": 1832,
"text": "III. Technical Round 2: "
},
{
"code": null,
"e": 2244,
"s": 1857,
"text": "Given a url containing the domain name and product it, like:www.amazon.in/pid=1234 By passing this url to utility functions, you can get all information about it. getProductName(url) –> Gives you the product name getProductPrice(url) –> Gives you the price of the product getRelatedProducts(url) –> Other products related to the current product, in which also user might be interested. "
},
{
"code": null,
"e": 2475,
"s": 2244,
"text": "Now given a product url, print the information about it completely, including all its related products. What is the data structure that you will consider to represent the above product data and write class structure for the same. "
},
{
"code": null,
"e": 2500,
"s": 2475,
"text": "IV. Presentation Round: "
},
{
"code": null,
"e": 2834,
"s": 2500,
"text": "A technical topic will be given and you have to speak on it in front of a group of 5-6 people.You will be given 1 hour of time to prepare, a system with internet. You can present the topic either on board or with ppt also. The aim of this round is to check the candidates learning capability on a new topic, his presentation skills. "
},
{
"code": null,
"e": 2875,
"s": 2834,
"text": "The topic given to me is “Apache Flink” "
},
{
"code": null,
"e": 2959,
"s": 2875,
"text": "Since I got mixed response for this round, they conducted another technical round. "
},
{
"code": null,
"e": 2982,
"s": 2959,
"text": "V. Technical Round 3: "
},
{
"code": null,
"e": 3128,
"s": 2982,
"text": "1. Design an LRU(Least Recently Used) Cache. What is Cache and define LRU Cache? What data structure do you use and what is the time complexity? "
},
{
"code": null,
"e": 3360,
"s": 3128,
"text": "Solution: Take one hashmap and linked list HashMap contains the key as data and value as its address in the linked list Linked list will maintain the elements in their usage order, with the last used item at the start of the list. "
},
{
"code": null,
"e": 3428,
"s": 3360,
"text": "This way the least recently used is at the end of the list always. "
},
{
"code": null,
"e": 3507,
"s": 3428,
"text": "2. Explain about HashMap internal implementation and write code for the same. "
},
{
"code": null,
"e": 3730,
"s": 3507,
"text": "If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 3772,
"s": 3732,
"text": "All Practice Problems for Salesforce ! "
},
{
"code": null,
"e": 3787,
"s": 3776,
"text": "Salesforce"
},
{
"code": null,
"e": 3809,
"s": 3787,
"text": "Interview Experiences"
},
{
"code": null,
"e": 3820,
"s": 3809,
"text": "Salesforce"
}
] |
jQuery | resize() with Examples
|
13 Feb, 2019
The resize() method is an inbuilt method in jQuery which is used when the browser window change its size.
Syntax:
$(selector).resize(function)
Parameter: This method accepts single parameter function which is optional. It is used to specify the function to run when the resize event is called.
Return Value: This method returns the selected element with increases its size.
Below example illustrates the resize() method in jQuery:
Example:
<!DOCTYPE html><html> <head> <title>The resize method</title> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <!-- jQuery code to show the working of this method --> <script> x = 0; $(document).ready(function() { $(window).resize(function() { $("p").text(x += 1); }); }); </script> <style> div { width: 150px; height: 100px; padding: 20px; border: 2px solid green; font-size: 20px; } </style> </head> <body> <div> <!-- press "ctrl" and "+" key together and see the effect --> Welcome to GfG! <br> <p>0</p> times. </div> </body></html>
Output:Before click anything.After clicking 2 times “ctrl” and “+” key together in keyboard.
jQuery-Events
JavaScript
JQuery
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to add options to a select element using jQuery?
How to fetch data from JSON file and display in HTML table using jQuery ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Feb, 2019"
},
{
"code": null,
"e": 134,
"s": 28,
"text": "The resize() method is an inbuilt method in jQuery which is used when the browser window change its size."
},
{
"code": null,
"e": 142,
"s": 134,
"text": "Syntax:"
},
{
"code": null,
"e": 171,
"s": 142,
"text": "$(selector).resize(function)"
},
{
"code": null,
"e": 322,
"s": 171,
"text": "Parameter: This method accepts single parameter function which is optional. It is used to specify the function to run when the resize event is called."
},
{
"code": null,
"e": 402,
"s": 322,
"text": "Return Value: This method returns the selected element with increases its size."
},
{
"code": null,
"e": 459,
"s": 402,
"text": "Below example illustrates the resize() method in jQuery:"
},
{
"code": null,
"e": 468,
"s": 459,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>The resize method</title> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <!-- jQuery code to show the working of this method --> <script> x = 0; $(document).ready(function() { $(window).resize(function() { $(\"p\").text(x += 1); }); }); </script> <style> div { width: 150px; height: 100px; padding: 20px; border: 2px solid green; font-size: 20px; } </style> </head> <body> <div> <!-- press \"ctrl\" and \"+\" key together and see the effect --> Welcome to GfG! <br> <p>0</p> times. </div> </body></html>",
"e": 1397,
"s": 468,
"text": null
},
{
"code": null,
"e": 1490,
"s": 1397,
"text": "Output:Before click anything.After clicking 2 times “ctrl” and “+” key together in keyboard."
},
{
"code": null,
"e": 1504,
"s": 1490,
"text": "jQuery-Events"
},
{
"code": null,
"e": 1515,
"s": 1504,
"text": "JavaScript"
},
{
"code": null,
"e": 1522,
"s": 1515,
"text": "JQuery"
},
{
"code": null,
"e": 1620,
"s": 1522,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1681,
"s": 1620,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1753,
"s": 1681,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 1793,
"s": 1753,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1834,
"s": 1793,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 1886,
"s": 1834,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 1932,
"s": 1886,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 1961,
"s": 1932,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 2024,
"s": 1961,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 2077,
"s": 2024,
"text": "How to add options to a select element using jQuery?"
}
] |
XAML - DataGrid
|
A DataGrid represents a control that displays data in a customizable grid. It provides a flexible way to display a collection of data in rows and columns. The hierarchical inheritance of DataGrid class is as follows −
AlternatingRowBackground
Gets or sets the background brush for use on alternating rows.
AreRowDetailsFrozen
Gets or sets a value that indicates whether the row details can scroll horizontally.
AutoGenerateColumns
Gets or sets a value that indicates whether the columns are created automatically.
CanUserAddRows
Gets or sets a value that indicates whether the user can add new rows to the DataGrid.
CanUserDeleteRows
Gets or sets a value that indicates whether the user can delete rows from the DataGrid.
CanUserReorderColumns
Gets or sets a value that indicates whether the user can change the column display order by dragging column headers with the mouse.
CanUserResizeColumns
Gets or sets a value that indicates whether the user can adjust the width of columns by using the mouse.
CanUserResizeRows
Gets or sets a value that indicates whether the user can adjust the height of rows by using the mouse.
CanUserSortColumns
Gets or sets a value that indicates whether the user can sort columns by clicking the column header.
ColumnHeaderHeight
Gets or sets the height of the column headers row.
ColumnHeaderStyle
Gets or sets the style applied to all column headers in the DataGrid.
Columns
Gets a collection that contains all the columns in the DataGrid.
ColumnWidth
Gets or sets the standard width and sizing mode of columns and headers in the DataGrid.
CurrentCell
Gets or sets the cell that has focus.
CurrentColumn
Gets or sets the column that contains the current cell.
CurrentItem
Gets the data item bound to the row that contains the current cell.
FrozenColumnCount
Gets or sets the number of non-scrolling columns.
HorizontalScrollBarVisibility
Gets or sets a value that indicates how horizontal scroll bars are displayed in the DataGrid.
IsReadOnly
Gets or sets a value that indicates whether the user can edit values in the DataGrid.
RowBackground
Gets or sets the default brush for the row background.
RowHeight
Gets or sets the suggested height for all rows.
SelectedCells
Gets the list of cells that are currently selected.
BeginEdit
Invokes the BeginEdit command, which will place the current cell or row into edit mode.
CancelEdit
Invokes the CancelEditCommand command for the cell or row currently in edit mode.
ClearDetailsVisibilityForItem
Clears the DetailsVisibility property for the DataGridRow that represents the specified data item.
ColumnFromDisplayIndex
Gets the DataGridColumn at the specified index.
CommitEdit
Invokes the CommitEditCommand command for the cell or row currently in edit mode.
GenerateColumns
Generates columns for the specified properties of an object.
GetDetailsVisibilityForItem
Gets the DetailsVisibility property for the DataGridRow that represents the specified data item.
OnApplyTemplate
When overridden in a derived class, is invoked whenever application code or internal processes call ApplyTemplate. (Overrides FrameworkElement.OnApplyTemplate())
ScrollIntoView
Scrolls the DataGrid vertically to display the row for the specified data item.
SelectAllCells
Selects all the cells in the DataGrid.
SetDetailsVisibilityForItem
Sets the value of the DetailsVisibility property for the DataGridRow that contains the specified object.
UnselectAllCells
Unselects all the cells in the DataGrid.
AddingNewItem
Occurs before a new item is added to the DataGrid.
AutoGeneratedColumns
Occurs when auto generation of all columns is completed.
AutoGeneratingColumn
Occurs when an individual column is auto-generated.
BeginningEdit
Occurs before a row or cell enters edit mode.
CellEditEnding
Occurs before a cell edit is committed or canceled.
ColumnDisplayIndexChanged
Occurs when the DisplayIndex property on one of the columns changes.
ColumnHeaderDragCompleted
Occurs when the user releases a column header after dragging it by using the mouse.
ColumnHeaderDragDelta
Occurs every time the mouse position changes while the user drags a column header.
ColumnHeaderDragStarted
Occurs when the user begins dragging a column header by using the mouse.
ColumnReordered
Occurs when a column moves to a new position in the display order.
ColumnReordering
Occurs before a column moves to a new position in the display order.
CopyingRowClipboardContent
Occurs after the default row content is prepared.
CurrentCellChanged
Occurs when the value of the CurrentCell property has changed.
InitializingNewItem
Occurs when a new item is created.
LoadingRow
Occurs after a DataGridRow is instantiated, so that you can customize it before it is used.
LoadingRowDetails
Occurs when a new row details template is applied to a row.
PreparingCellForEdit
Occurs when a cell enters edit mode.
RowDetailsVisibilityChanged
Occurs when the visibility of a row details element changes.
RowEditEnding
Occurs before a row edit is committed or canceled.
SelectedCellsChanged
Occurs when the SelectedCells collection changes.
Sorting
Occurs when a column is being sorted.
UnloadingRow
Occurs when a DataGridRow object becomes available for reuse.
UnloadingRowDetails
Occurs when a row details element becomes available for reuse.
The following example shows how to display data in a DataGrid. Here is the XAML code to create two checkboxes with some properties and events.
<Window x:Class = "DataGrid.MainWindow"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:core = "clr-namespace:System;assembly = mscorlib"
xmlns:local = "clr-namespace:DataGrid"
Title = "MainWindow" Height = "350" Width = "525">
<Window.Resources>
<ObjectDataProvider x:Key = "myEnum" MethodName = "GetValues"
ObjectType = "{x:Type core:Enum}">
<ObjectDataProvider.MethodParameters>
<x:TypeExtension Type = "local:Party" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
<Grid>
<DataGrid Name = "dataGrid" AlternatingRowBackground = "LightBlue"
AlternationCount = "2" AutoGenerateColumns = "False">
<DataGrid.Columns>
<DataGridTextColumn Header = "Name" Binding = "{Binding Name}" />
<DataGridTextColumn Header = "Title" Binding = "{Binding Title}" >
<DataGridCheckBoxColumn Header = "ReElected?" Binding = "{Binding WasReElected}"/>
<DataGridComboBoxColumn Header = "Party"
SelectedItemBinding = "{Binding Affiliation}"
ItemsSource = "{Binding Source = {StaticResource myEnum}}" />
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
Here is the implementation in C# for two different classes.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace DataGrid {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent(); dataGrid.ItemsSource = Employee.GetEmployees();
}
}
public enum Party {
Indepentent, Federalist, DemocratRepublican,
}
}
Here is another Employee class implementation in C#.
public class Employee : INotifyPropertyChanged {
private string name; public string Name {
get { return name; }
set {
name = value; RaiseProperChanged();
}
}
private string title; public string Title {
get { return title; }
set {
title = value;
RaiseProperChanged();
}
}
private bool wasReElected;
public bool WasReElected {
get { return wasReElected; }
set {
wasReElected = value; RaiseProperChanged();
}
}
private Party affiliation; public Party Affiliation {
get { return affiliation; }
set {
affiliation = value; RaiseProperChanged();
}
}
public static ObservableCollection<Employee> GetEmployees() {
var employees = new ObservableCollection<Employee>();
employees.Add(new Employee() {
Name = "Ali", Title = "Minister", WasReElected = true,
Affiliation = Party.Indepentent });
employees.Add(new Employee() {
Name = "Ahmed", Title = "CM", WasReElected = false,
Affiliation = Party.Federalist });
employees.Add(new Employee() {
Name = "Amjad", Title = "PM", WasReElected = true,
Affiliation = Party.DemocratRepublican });
employees.Add(new Employee() {
Name = "Waqas", Title = "Minister", WasReElected = false,
Affiliation = Party.Indepentent });
employees.Add(new Employee() {
Name = "Bilal", Title = "Minister", WasReElected = true,
Affiliation = Party.Federalist });
employees.Add(new Employee() {
Name = "Waqar", Title = "Minister", WasReElected = false,
Affiliation = Party.DemocratRepublican });
return employees;
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaiseProperChanged( [CallerMemberName] string caller = "") {
if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs(caller));
}
}
}
When you compile and execute the above code, it will produce the following output −
We recommend you to execute the above example code and experiment with some other properties and events.
|
[
{
"code": null,
"e": 2275,
"s": 2057,
"text": "A DataGrid represents a control that displays data in a customizable grid. It provides a flexible way to display a collection of data in rows and columns. The hierarchical inheritance of DataGrid class is as follows −"
},
{
"code": null,
"e": 2300,
"s": 2275,
"text": "AlternatingRowBackground"
},
{
"code": null,
"e": 2363,
"s": 2300,
"text": "Gets or sets the background brush for use on alternating rows."
},
{
"code": null,
"e": 2383,
"s": 2363,
"text": "AreRowDetailsFrozen"
},
{
"code": null,
"e": 2468,
"s": 2383,
"text": "Gets or sets a value that indicates whether the row details can scroll horizontally."
},
{
"code": null,
"e": 2488,
"s": 2468,
"text": "AutoGenerateColumns"
},
{
"code": null,
"e": 2571,
"s": 2488,
"text": "Gets or sets a value that indicates whether the columns are created automatically."
},
{
"code": null,
"e": 2586,
"s": 2571,
"text": "CanUserAddRows"
},
{
"code": null,
"e": 2673,
"s": 2586,
"text": "Gets or sets a value that indicates whether the user can add new rows to the DataGrid."
},
{
"code": null,
"e": 2691,
"s": 2673,
"text": "CanUserDeleteRows"
},
{
"code": null,
"e": 2779,
"s": 2691,
"text": "Gets or sets a value that indicates whether the user can delete rows from the DataGrid."
},
{
"code": null,
"e": 2801,
"s": 2779,
"text": "CanUserReorderColumns"
},
{
"code": null,
"e": 2933,
"s": 2801,
"text": "Gets or sets a value that indicates whether the user can change the column display order by dragging column headers with the mouse."
},
{
"code": null,
"e": 2954,
"s": 2933,
"text": "CanUserResizeColumns"
},
{
"code": null,
"e": 3059,
"s": 2954,
"text": "Gets or sets a value that indicates whether the user can adjust the width of columns by using the mouse."
},
{
"code": null,
"e": 3077,
"s": 3059,
"text": "CanUserResizeRows"
},
{
"code": null,
"e": 3180,
"s": 3077,
"text": "Gets or sets a value that indicates whether the user can adjust the height of rows by using the mouse."
},
{
"code": null,
"e": 3199,
"s": 3180,
"text": "CanUserSortColumns"
},
{
"code": null,
"e": 3300,
"s": 3199,
"text": "Gets or sets a value that indicates whether the user can sort columns by clicking the column header."
},
{
"code": null,
"e": 3319,
"s": 3300,
"text": "ColumnHeaderHeight"
},
{
"code": null,
"e": 3370,
"s": 3319,
"text": "Gets or sets the height of the column headers row."
},
{
"code": null,
"e": 3388,
"s": 3370,
"text": "ColumnHeaderStyle"
},
{
"code": null,
"e": 3458,
"s": 3388,
"text": "Gets or sets the style applied to all column headers in the DataGrid."
},
{
"code": null,
"e": 3466,
"s": 3458,
"text": "Columns"
},
{
"code": null,
"e": 3531,
"s": 3466,
"text": "Gets a collection that contains all the columns in the DataGrid."
},
{
"code": null,
"e": 3543,
"s": 3531,
"text": "ColumnWidth"
},
{
"code": null,
"e": 3631,
"s": 3543,
"text": "Gets or sets the standard width and sizing mode of columns and headers in the DataGrid."
},
{
"code": null,
"e": 3643,
"s": 3631,
"text": "CurrentCell"
},
{
"code": null,
"e": 3681,
"s": 3643,
"text": "Gets or sets the cell that has focus."
},
{
"code": null,
"e": 3695,
"s": 3681,
"text": "CurrentColumn"
},
{
"code": null,
"e": 3751,
"s": 3695,
"text": "Gets or sets the column that contains the current cell."
},
{
"code": null,
"e": 3763,
"s": 3751,
"text": "CurrentItem"
},
{
"code": null,
"e": 3831,
"s": 3763,
"text": "Gets the data item bound to the row that contains the current cell."
},
{
"code": null,
"e": 3849,
"s": 3831,
"text": "FrozenColumnCount"
},
{
"code": null,
"e": 3899,
"s": 3849,
"text": "Gets or sets the number of non-scrolling columns."
},
{
"code": null,
"e": 3929,
"s": 3899,
"text": "HorizontalScrollBarVisibility"
},
{
"code": null,
"e": 4023,
"s": 3929,
"text": "Gets or sets a value that indicates how horizontal scroll bars are displayed in the DataGrid."
},
{
"code": null,
"e": 4034,
"s": 4023,
"text": "IsReadOnly"
},
{
"code": null,
"e": 4120,
"s": 4034,
"text": "Gets or sets a value that indicates whether the user can edit values in the DataGrid."
},
{
"code": null,
"e": 4134,
"s": 4120,
"text": "RowBackground"
},
{
"code": null,
"e": 4189,
"s": 4134,
"text": "Gets or sets the default brush for the row background."
},
{
"code": null,
"e": 4199,
"s": 4189,
"text": "RowHeight"
},
{
"code": null,
"e": 4247,
"s": 4199,
"text": "Gets or sets the suggested height for all rows."
},
{
"code": null,
"e": 4261,
"s": 4247,
"text": "SelectedCells"
},
{
"code": null,
"e": 4313,
"s": 4261,
"text": "Gets the list of cells that are currently selected."
},
{
"code": null,
"e": 4323,
"s": 4313,
"text": "BeginEdit"
},
{
"code": null,
"e": 4411,
"s": 4323,
"text": "Invokes the BeginEdit command, which will place the current cell or row into edit mode."
},
{
"code": null,
"e": 4422,
"s": 4411,
"text": "CancelEdit"
},
{
"code": null,
"e": 4504,
"s": 4422,
"text": "Invokes the CancelEditCommand command for the cell or row currently in edit mode."
},
{
"code": null,
"e": 4534,
"s": 4504,
"text": "ClearDetailsVisibilityForItem"
},
{
"code": null,
"e": 4633,
"s": 4534,
"text": "Clears the DetailsVisibility property for the DataGridRow that represents the specified data item."
},
{
"code": null,
"e": 4656,
"s": 4633,
"text": "ColumnFromDisplayIndex"
},
{
"code": null,
"e": 4704,
"s": 4656,
"text": "Gets the DataGridColumn at the specified index."
},
{
"code": null,
"e": 4715,
"s": 4704,
"text": "CommitEdit"
},
{
"code": null,
"e": 4797,
"s": 4715,
"text": "Invokes the CommitEditCommand command for the cell or row currently in edit mode."
},
{
"code": null,
"e": 4813,
"s": 4797,
"text": "GenerateColumns"
},
{
"code": null,
"e": 4874,
"s": 4813,
"text": "Generates columns for the specified properties of an object."
},
{
"code": null,
"e": 4902,
"s": 4874,
"text": "GetDetailsVisibilityForItem"
},
{
"code": null,
"e": 4999,
"s": 4902,
"text": "Gets the DetailsVisibility property for the DataGridRow that represents the specified data item."
},
{
"code": null,
"e": 5015,
"s": 4999,
"text": "OnApplyTemplate"
},
{
"code": null,
"e": 5177,
"s": 5015,
"text": "When overridden in a derived class, is invoked whenever application code or internal processes call ApplyTemplate. (Overrides FrameworkElement.OnApplyTemplate())"
},
{
"code": null,
"e": 5192,
"s": 5177,
"text": "ScrollIntoView"
},
{
"code": null,
"e": 5272,
"s": 5192,
"text": "Scrolls the DataGrid vertically to display the row for the specified data item."
},
{
"code": null,
"e": 5287,
"s": 5272,
"text": "SelectAllCells"
},
{
"code": null,
"e": 5326,
"s": 5287,
"text": "Selects all the cells in the DataGrid."
},
{
"code": null,
"e": 5354,
"s": 5326,
"text": "SetDetailsVisibilityForItem"
},
{
"code": null,
"e": 5459,
"s": 5354,
"text": "Sets the value of the DetailsVisibility property for the DataGridRow that contains the specified object."
},
{
"code": null,
"e": 5476,
"s": 5459,
"text": "UnselectAllCells"
},
{
"code": null,
"e": 5517,
"s": 5476,
"text": "Unselects all the cells in the DataGrid."
},
{
"code": null,
"e": 5531,
"s": 5517,
"text": "AddingNewItem"
},
{
"code": null,
"e": 5582,
"s": 5531,
"text": "Occurs before a new item is added to the DataGrid."
},
{
"code": null,
"e": 5603,
"s": 5582,
"text": "AutoGeneratedColumns"
},
{
"code": null,
"e": 5660,
"s": 5603,
"text": "Occurs when auto generation of all columns is completed."
},
{
"code": null,
"e": 5681,
"s": 5660,
"text": "AutoGeneratingColumn"
},
{
"code": null,
"e": 5733,
"s": 5681,
"text": "Occurs when an individual column is auto-generated."
},
{
"code": null,
"e": 5747,
"s": 5733,
"text": "BeginningEdit"
},
{
"code": null,
"e": 5793,
"s": 5747,
"text": "Occurs before a row or cell enters edit mode."
},
{
"code": null,
"e": 5808,
"s": 5793,
"text": "CellEditEnding"
},
{
"code": null,
"e": 5860,
"s": 5808,
"text": "Occurs before a cell edit is committed or canceled."
},
{
"code": null,
"e": 5886,
"s": 5860,
"text": "ColumnDisplayIndexChanged"
},
{
"code": null,
"e": 5955,
"s": 5886,
"text": "Occurs when the DisplayIndex property on one of the columns changes."
},
{
"code": null,
"e": 5981,
"s": 5955,
"text": "ColumnHeaderDragCompleted"
},
{
"code": null,
"e": 6065,
"s": 5981,
"text": "Occurs when the user releases a column header after dragging it by using the mouse."
},
{
"code": null,
"e": 6087,
"s": 6065,
"text": "ColumnHeaderDragDelta"
},
{
"code": null,
"e": 6170,
"s": 6087,
"text": "Occurs every time the mouse position changes while the user drags a column header."
},
{
"code": null,
"e": 6194,
"s": 6170,
"text": "ColumnHeaderDragStarted"
},
{
"code": null,
"e": 6267,
"s": 6194,
"text": "Occurs when the user begins dragging a column header by using the mouse."
},
{
"code": null,
"e": 6283,
"s": 6267,
"text": "ColumnReordered"
},
{
"code": null,
"e": 6350,
"s": 6283,
"text": "Occurs when a column moves to a new position in the display order."
},
{
"code": null,
"e": 6367,
"s": 6350,
"text": "ColumnReordering"
},
{
"code": null,
"e": 6436,
"s": 6367,
"text": "Occurs before a column moves to a new position in the display order."
},
{
"code": null,
"e": 6463,
"s": 6436,
"text": "CopyingRowClipboardContent"
},
{
"code": null,
"e": 6513,
"s": 6463,
"text": "Occurs after the default row content is prepared."
},
{
"code": null,
"e": 6532,
"s": 6513,
"text": "CurrentCellChanged"
},
{
"code": null,
"e": 6595,
"s": 6532,
"text": "Occurs when the value of the CurrentCell property has changed."
},
{
"code": null,
"e": 6615,
"s": 6595,
"text": "InitializingNewItem"
},
{
"code": null,
"e": 6650,
"s": 6615,
"text": "Occurs when a new item is created."
},
{
"code": null,
"e": 6661,
"s": 6650,
"text": "LoadingRow"
},
{
"code": null,
"e": 6753,
"s": 6661,
"text": "Occurs after a DataGridRow is instantiated, so that you can customize it before it is used."
},
{
"code": null,
"e": 6771,
"s": 6753,
"text": "LoadingRowDetails"
},
{
"code": null,
"e": 6831,
"s": 6771,
"text": "Occurs when a new row details template is applied to a row."
},
{
"code": null,
"e": 6852,
"s": 6831,
"text": "PreparingCellForEdit"
},
{
"code": null,
"e": 6889,
"s": 6852,
"text": "Occurs when a cell enters edit mode."
},
{
"code": null,
"e": 6917,
"s": 6889,
"text": "RowDetailsVisibilityChanged"
},
{
"code": null,
"e": 6978,
"s": 6917,
"text": "Occurs when the visibility of a row details element changes."
},
{
"code": null,
"e": 6992,
"s": 6978,
"text": "RowEditEnding"
},
{
"code": null,
"e": 7043,
"s": 6992,
"text": "Occurs before a row edit is committed or canceled."
},
{
"code": null,
"e": 7064,
"s": 7043,
"text": "SelectedCellsChanged"
},
{
"code": null,
"e": 7114,
"s": 7064,
"text": "Occurs when the SelectedCells collection changes."
},
{
"code": null,
"e": 7122,
"s": 7114,
"text": "Sorting"
},
{
"code": null,
"e": 7160,
"s": 7122,
"text": "Occurs when a column is being sorted."
},
{
"code": null,
"e": 7173,
"s": 7160,
"text": "UnloadingRow"
},
{
"code": null,
"e": 7235,
"s": 7173,
"text": "Occurs when a DataGridRow object becomes available for reuse."
},
{
"code": null,
"e": 7255,
"s": 7235,
"text": "UnloadingRowDetails"
},
{
"code": null,
"e": 7318,
"s": 7255,
"text": "Occurs when a row details element becomes available for reuse."
},
{
"code": null,
"e": 7461,
"s": 7318,
"text": "The following example shows how to display data in a DataGrid. Here is the XAML code to create two checkboxes with some properties and events."
},
{
"code": null,
"e": 8841,
"s": 7461,
"text": "<Window x:Class = \"DataGrid.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:core = \"clr-namespace:System;assembly = mscorlib\" \n xmlns:local = \"clr-namespace:DataGrid\" \n Title = \"MainWindow\" Height = \"350\" Width = \"525\"> \n\t\n <Window.Resources> \n <ObjectDataProvider x:Key = \"myEnum\" MethodName = \"GetValues\" \n ObjectType = \"{x:Type core:Enum}\"> \n\t\t\t\n <ObjectDataProvider.MethodParameters> \n <x:TypeExtension Type = \"local:Party\" /> \n </ObjectDataProvider.MethodParameters> \n\t\t</ObjectDataProvider> \n </Window.Resources> \n\t\n <Grid> \n <DataGrid Name = \"dataGrid\" AlternatingRowBackground = \"LightBlue\" \n AlternationCount = \"2\" AutoGenerateColumns = \"False\">\n\t\t\t\n <DataGrid.Columns> \n <DataGridTextColumn Header = \"Name\" Binding = \"{Binding Name}\" />\n <DataGridTextColumn Header = \"Title\" Binding = \"{Binding Title}\" >\n <DataGridCheckBoxColumn Header = \"ReElected?\" Binding = \"{Binding WasReElected}\"/> \n\t\t\t\t\n <DataGridComboBoxColumn Header = \"Party\"\n SelectedItemBinding = \"{Binding Affiliation}\" \n ItemsSource = \"{Binding Source = {StaticResource myEnum}}\" /> \n </DataGrid.Columns> \n </DataGrid>\n </Grid> \n\t\n</Window>"
},
{
"code": null,
"e": 8901,
"s": 8841,
"text": "Here is the implementation in C# for two different classes."
},
{
"code": null,
"e": 9660,
"s": 8901,
"text": "using System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Text; \nusing System.Threading.Tasks;\n \nusing System.Windows; \nusing System.Windows.Controls; \nusing System.Windows.Data; \nusing System.Windows.Documents; \nusing System.Windows.Input; \nusing System.Windows.Media; \nusing System.Windows.Media.Imaging; \nusing System.Windows.Navigation; \nusing System.Windows.Shapes;\n\nnamespace DataGrid { \n /// <summary> \n /// Interaction logic for MainWindow.xaml \n /// </summary>\n\t\n public partial class MainWindow : Window { \n public MainWindow() { \n InitializeComponent(); dataGrid.ItemsSource = Employee.GetEmployees(); \n }\n } \n\tpublic enum Party { \n Indepentent, Federalist, DemocratRepublican, \n } \n}"
},
{
"code": null,
"e": 9713,
"s": 9660,
"text": "Here is another Employee class implementation in C#."
},
{
"code": null,
"e": 11751,
"s": 9713,
"text": "public class Employee : INotifyPropertyChanged { \n private string name; public string Name { \n get { return name; } \n set { \n name = value; RaiseProperChanged(); \n } \n }\n\tprivate string title; public string Title { \n get { return title; } \n\t\tset { \n title = value; \n RaiseProperChanged();\n } \n }\n\tprivate bool wasReElected;\n\tpublic bool WasReElected { \n get { return wasReElected; } \n set { \n wasReElected = value; RaiseProperChanged(); \n } \n }\n\tprivate Party affiliation; public Party Affiliation {\n get { return affiliation; }\n\t\tset { \n affiliation = value; RaiseProperChanged(); \n } \n }\n\tpublic static ObservableCollection<Employee> GetEmployees() {\n var employees = new ObservableCollection<Employee>(); \n employees.Add(new Employee() {\n Name = \"Ali\", Title = \"Minister\", WasReElected = true, \n Affiliation = Party.Indepentent }); \n\t\t\t\n employees.Add(new Employee() { \n Name = \"Ahmed\", Title = \"CM\", WasReElected = false, \n Affiliation = Party.Federalist }); \n\t\t\t\n employees.Add(new Employee() { \n Name = \"Amjad\", Title = \"PM\", WasReElected = true, \n Affiliation = Party.DemocratRepublican });\n\t\t\t\n employees.Add(new Employee() { \n Name = \"Waqas\", Title = \"Minister\", WasReElected = false, \n Affiliation = Party.Indepentent }); \n\t\t\t\n employees.Add(new Employee() { \n Name = \"Bilal\", Title = \"Minister\", WasReElected = true, \n Affiliation = Party.Federalist });\n\t\t\t\n employees.Add(new Employee() { \n Name = \"Waqar\", Title = \"Minister\", WasReElected = false,\n Affiliation = Party.DemocratRepublican }); \n\t\t\t\n return employees; \n }\n public event PropertyChangedEventHandler PropertyChanged;\n\t\n private void RaiseProperChanged( [CallerMemberName] string caller = \"\") { \n if (PropertyChanged != null) { \n PropertyChanged(this, new PropertyChangedEventArgs(caller)); \n } \n } \n}"
},
{
"code": null,
"e": 11835,
"s": 11751,
"text": "When you compile and execute the above code, it will produce the following output −"
}
] |
How to get parameters from a URL string in PHP?
|
28 Feb, 2022
The parameters from a URL string can be be retrieved in PHP using parse_url() and parse_str() functions.
Note: Page URL and the parameters are separated by the ? character.
parse_url() Function: The parse_url() function is used to return the components of a URL by parsing it. It parse an URL and return an associative array which contains its various components.
Syntax:
parse_url( $url, $component = -1 )
parse_str() Function: The parse_str() function is used to parse a query string into variables. The string passed to this function for parsing is in the format of a query string passed via a URL.
Syntax:
parse_str( $string, $array )
Approach: Parse the URL string using parse_url() function which will return an associative array that contains its (passed URL) various components. The query of the array returned by parse_url() function which contains a query string of URL.
Below examples uses parse_url() and parse_str() function to get the parameters from URL string.
Example 1:
PHP
<?php // Initialize URL to the variable$url = 'https://www.geeksforgeeks.org?name=Tonny'; // Use parse_url() function to parse the URL // and return an associative array which// contains its various components$url_components = parse_url($url); // Use parse_str() function to parse the// string passed via URLparse_str($url_components['query'], $params); // Display resultecho ' Hi '.$params['name']; ?>
Hi Tonny
Example 2:
PHP
<?php // Initialize URL to the variable$url = 'https://www.geeksforgeeks.org/register?name=Amit&email=amit1998@gmail.com'; // Use parse_url() function to parse the URL // and return an associative array which// contains its various components$url_components = parse_url($url); // Use parse_str() function to parse the// string passed via URLparse_str($url_components['query'], $params); // Display resultecho ' Hi '.$params['name'].' your emailID is '.$params['email']; ?>
Hi Amit your emailID is amit1998@gmail.com
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
gabaa406
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
How to call PHP function on the click of a Button ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Feb, 2022"
},
{
"code": null,
"e": 133,
"s": 28,
"text": "The parameters from a URL string can be be retrieved in PHP using parse_url() and parse_str() functions."
},
{
"code": null,
"e": 201,
"s": 133,
"text": "Note: Page URL and the parameters are separated by the ? character."
},
{
"code": null,
"e": 392,
"s": 201,
"text": "parse_url() Function: The parse_url() function is used to return the components of a URL by parsing it. It parse an URL and return an associative array which contains its various components."
},
{
"code": null,
"e": 401,
"s": 392,
"text": "Syntax: "
},
{
"code": null,
"e": 436,
"s": 401,
"text": "parse_url( $url, $component = -1 )"
},
{
"code": null,
"e": 631,
"s": 436,
"text": "parse_str() Function: The parse_str() function is used to parse a query string into variables. The string passed to this function for parsing is in the format of a query string passed via a URL."
},
{
"code": null,
"e": 641,
"s": 631,
"text": "Syntax: "
},
{
"code": null,
"e": 670,
"s": 641,
"text": "parse_str( $string, $array )"
},
{
"code": null,
"e": 912,
"s": 670,
"text": "Approach: Parse the URL string using parse_url() function which will return an associative array that contains its (passed URL) various components. The query of the array returned by parse_url() function which contains a query string of URL."
},
{
"code": null,
"e": 1009,
"s": 912,
"text": "Below examples uses parse_url() and parse_str() function to get the parameters from URL string. "
},
{
"code": null,
"e": 1022,
"s": 1009,
"text": "Example 1: "
},
{
"code": null,
"e": 1026,
"s": 1022,
"text": "PHP"
},
{
"code": "<?php // Initialize URL to the variable$url = 'https://www.geeksforgeeks.org?name=Tonny'; // Use parse_url() function to parse the URL // and return an associative array which// contains its various components$url_components = parse_url($url); // Use parse_str() function to parse the// string passed via URLparse_str($url_components['query'], $params); // Display resultecho ' Hi '.$params['name']; ?>",
"e": 1442,
"s": 1026,
"text": null
},
{
"code": null,
"e": 1451,
"s": 1442,
"text": "Hi Tonny"
},
{
"code": null,
"e": 1465,
"s": 1453,
"text": "Example 2: "
},
{
"code": null,
"e": 1469,
"s": 1465,
"text": "PHP"
},
{
"code": "<?php // Initialize URL to the variable$url = 'https://www.geeksforgeeks.org/register?name=Amit&email=amit1998@gmail.com'; // Use parse_url() function to parse the URL // and return an associative array which// contains its various components$url_components = parse_url($url); // Use parse_str() function to parse the// string passed via URLparse_str($url_components['query'], $params); // Display resultecho ' Hi '.$params['name'].' your emailID is '.$params['email']; ?>",
"e": 1955,
"s": 1469,
"text": null
},
{
"code": null,
"e": 1998,
"s": 1955,
"text": "Hi Amit your emailID is amit1998@gmail.com"
},
{
"code": null,
"e": 2169,
"s": 2000,
"text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples."
},
{
"code": null,
"e": 2178,
"s": 2169,
"text": "gabaa406"
},
{
"code": null,
"e": 2185,
"s": 2178,
"text": "Picked"
},
{
"code": null,
"e": 2189,
"s": 2185,
"text": "PHP"
},
{
"code": null,
"e": 2202,
"s": 2189,
"text": "PHP Programs"
},
{
"code": null,
"e": 2219,
"s": 2202,
"text": "Web Technologies"
},
{
"code": null,
"e": 2246,
"s": 2219,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2250,
"s": 2246,
"text": "PHP"
},
{
"code": null,
"e": 2348,
"s": 2250,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2398,
"s": 2348,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 2438,
"s": 2398,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 2499,
"s": 2438,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 2549,
"s": 2499,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 2594,
"s": 2549,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 2644,
"s": 2594,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 2684,
"s": 2644,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 2745,
"s": 2684,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 2795,
"s": 2745,
"text": "How to check whether an array is empty using PHP?"
}
] |
Why companies like Amazon, Microsoft, Google focuses on Data Structures and Algorithms : Answered
|
06 May, 2022
If you’re preparing for a tech interview of any big tech company like Adobe, Amazon, Microsoft, Google, etc. – most probably, you would have known about the importance of Data Structures and Algorithms to crack these interviews. Yes, most of the interviews for technical roles in these companies are focused on measuring the Data Structures and Algorithms knowledge of the candidates.
So the question arises: Why do Product Based Companies place so much emphasis on Data Structures and Algorithms?
Software Product Based Companies normally create products that are related to software. So it stands to reason that they require quality Software Developers to handle the development process for the software. The pay-scale of Software Developers has increased a lot in recent times globally. According to the report by Glassdoor, the average base pay of Software Developers in India is found to be around 12 Lakhs per annum. The average base of software developers ranges from Rs. 4,00,000 to Rs 20,00,000 per year (With Product Based Companies occupying the higher end of the spectrum).
Image Courtesy: Glassdoor
However, there is an acute shortage of well-qualified Software developers in India. As per various standard reports, less than 10% of engineers are actually employable in software-related jobs. That is where Data Structures and Algorithms come in. They are so important in Product Based Companies’ interviews as they are the hallmark of any good Software Developer.
In addition to that, there are multiple reasons why Product Based Companies place so much emphasis on Data Structures and Algorithms as stated below:
Data Structures and Algorithms demonstrate the problem-solving ability of a candidate. There is no room to craft elaborate stories and this means that either the candidate can solve the problem or they can’t.Questions based on Data Structures and Algorithms can be scaled up or down according to the knowledge level of the candidate. This means that a variety of candidates can be tested using roughly the same problems.Data Structures and Algorithms are used to test the analytical skills of the candidates as they are a useful tool to pick out the underlying algorithms in real-world problems and solve them efficiently.Data Structures and Algorithms are the fundamentals of Software Development. They remain the same no matter what new technology is used and that puts the focus on the problem rather than the technology in the interview process.
Data Structures and Algorithms demonstrate the problem-solving ability of a candidate. There is no room to craft elaborate stories and this means that either the candidate can solve the problem or they can’t.
Questions based on Data Structures and Algorithms can be scaled up or down according to the knowledge level of the candidate. This means that a variety of candidates can be tested using roughly the same problems.
Data Structures and Algorithms are used to test the analytical skills of the candidates as they are a useful tool to pick out the underlying algorithms in real-world problems and solve them efficiently.
Data Structures and Algorithms are the fundamentals of Software Development. They remain the same no matter what new technology is used and that puts the focus on the problem rather than the technology in the interview process.
Now as we have established that Data Structures and Algorithms are important for interviews in Product Based Companies, let’s focus on learning them.
Bad programmers worry about the code. Good programmers worry about data structures and their relationships.
While learning Data Structures and Algorithms, it is best to start small with simple topics and then move on to more and more advanced topics. Some of the basic data structures are Arrays, Linked Lists, Stacks, Queues, etc. while some of the basic algorithms are Sorting, Searching, etc.
Some of the major problems that can appear while learning Data Structures and Algorithms are:
Lack of guidance: There is no clear guidance while learning Data Structures and Algorithms. There are numerous topics within these umbrella terms with no specific guidelines about which topics would be more useful for different Product Based Companies. This situation can be quite confusing, especially for a beginner.
No idea from where to start learning: Even if the necessary topics in Data Structures and Algorithms are known, the sheer amount of them leads to a lot of confusion. Most beginners have no idea from where to start learning or even what chronological order to follow while learning.
To solve the above problems, we at GeeksforGeeks have designed a number of online courses to learn Data Structures and Algorithms at affordable prices. One of the latest courses created by us is the Complete Interview Preparation course. This course covers Data Structures and Algorithms along with other subjects in order to completely prepare you for placements in your dream company. To learn more about it, read on . . .
The Complete Interview Preparation Course is specifically designed for the students and working professionals to help them out in landing their dream job by providing them all the required stuff like premium lectures, theory notes, practice tests, assessment tests, etc. in a single place. In this course, along with Data Structures & Algorithms, you’ll get prepared for other required subjects also like Computer Science Core Subjects, Programming Language, Reasoning & Aptitude, etc. Also, we know that the placement preparation requires some extensive research process and smart learning as not every subject holds the same weightage in the interview – hence, this Complete Interview Preparation Course is extensively curated keeping this factor in mind.
Some of the prominent features of the Complete Interview Preparation course are listed below:
Around 200+ algorithmic coding problems will be provided
Track-based learning & Weekly assessment tests
Premium Video Lectures recorded by Sandeep Jain (CEO & Founder, GeeksforGeeks) and other industry experts.
Subject-wise Theoretical content & Objective Questions compiled by subject experts
Lifetime access to the Course will be provided
Course Completion Certificate & Internship Opportunities at GeeksforGeeks
College Students will get the year-wise weekly plan for the course
Free Access to ‘Get Hired Premium’ at GeeksforGeeks Job Portal
Dedicated TAs for the Doubt Assistance (Optional)
This course is originally priced at INR 9,999, but it is available at an offer price of INR 6,999. Also, if you want to add on the doubt assistance facility in this course, you’ll be required to pay an additional amount of INR 2,999 only. The Doubt Assistance facility will be valid for the complete 1 year from the registration.
In case you wish to focus exclusively on Data Structures and Algorithms, you can opt for our latest online course to learn Data Structures and Algorithms named – DSA Self Paced Course, which covers everything about Data Structures and Algorithms from the Basic level to the Advanced level. It offers a wealth of programming challenges that you may face at your next job interview. The course focuses mainly on Data Structure & Algorithms as it the key to selection in top product-based companies.
Some of the Key Features of the Course are:
Well-organized tutorials on Data-Structures and Algorithms prepared by the experts
Premium video lectures by Mr. Sandeep Jain, Founder, and C.E.O of GeeksforGeeks.
Weekly Assessment Tests with Video Solutions.
Course Completion Certificate & Internship Opportunities at GeeksforGeeks
Lifetime access to the Course
The price of the self-paced online DSA course is INR 2,799. Also, if you want to add on the doubt assistance facility in this course, you’ll be required to pay an additional amount of INR 1,499 only. The Doubt Assistance facility will be valid for the complete 6 months from the registration.
Do you want to get live online classes on Data Structures & Algorithm to learn and master it...?? If yes, then we’ve Geeks Classes – Live Session course for you. It will be an interview centric extensive online (live) program to build and enhance your DSA skills. The course is designed in such a manner that it will help you to improve your problem-solving and coding skills by enhancing your understanding of Data Structures & Algorithms. The primary goal of this course is to help you in the preparation for the Coding interviews of companies like Amazon, Microsoft, Uber, etc. As it will be an online live class – you can attend this class from any geographical location and can ask your doubts or queries as well to the instructor similar to an offline classroom program.
Some of the prominent features of this course are provided below:
Doubt Solving Assistance (TA’s)
Limited Batch strength
Course Completion Certificate
6 months access to recorded Live lectures of this course
Other than that, you will also get complimentary access to the course content of the DSA Course.
madhur912
Amazon
GFG-Course
GFG-Update
Google
interview-preparation
Microsoft
placement preparation
Algorithms
Data Structures
Amazon
Microsoft
Google
Data Structures
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 May, 2022"
},
{
"code": null,
"e": 442,
"s": 54,
"text": "If you’re preparing for a tech interview of any big tech company like Adobe, Amazon, Microsoft, Google, etc. – most probably, you would have known about the importance of Data Structures and Algorithms to crack these interviews. Yes, most of the interviews for technical roles in these companies are focused on measuring the Data Structures and Algorithms knowledge of the candidates. "
},
{
"code": null,
"e": 555,
"s": 442,
"text": "So the question arises: Why do Product Based Companies place so much emphasis on Data Structures and Algorithms?"
},
{
"code": null,
"e": 1144,
"s": 555,
"text": "Software Product Based Companies normally create products that are related to software. So it stands to reason that they require quality Software Developers to handle the development process for the software. The pay-scale of Software Developers has increased a lot in recent times globally. According to the report by Glassdoor, the average base pay of Software Developers in India is found to be around 12 Lakhs per annum. The average base of software developers ranges from Rs. 4,00,000 to Rs 20,00,000 per year (With Product Based Companies occupying the higher end of the spectrum). "
},
{
"code": null,
"e": 1170,
"s": 1144,
"text": "Image Courtesy: Glassdoor"
},
{
"code": null,
"e": 1537,
"s": 1170,
"text": "However, there is an acute shortage of well-qualified Software developers in India. As per various standard reports, less than 10% of engineers are actually employable in software-related jobs. That is where Data Structures and Algorithms come in. They are so important in Product Based Companies’ interviews as they are the hallmark of any good Software Developer. "
},
{
"code": null,
"e": 1688,
"s": 1537,
"text": "In addition to that, there are multiple reasons why Product Based Companies place so much emphasis on Data Structures and Algorithms as stated below: "
},
{
"code": null,
"e": 2538,
"s": 1688,
"text": "Data Structures and Algorithms demonstrate the problem-solving ability of a candidate. There is no room to craft elaborate stories and this means that either the candidate can solve the problem or they can’t.Questions based on Data Structures and Algorithms can be scaled up or down according to the knowledge level of the candidate. This means that a variety of candidates can be tested using roughly the same problems.Data Structures and Algorithms are used to test the analytical skills of the candidates as they are a useful tool to pick out the underlying algorithms in real-world problems and solve them efficiently.Data Structures and Algorithms are the fundamentals of Software Development. They remain the same no matter what new technology is used and that puts the focus on the problem rather than the technology in the interview process."
},
{
"code": null,
"e": 2747,
"s": 2538,
"text": "Data Structures and Algorithms demonstrate the problem-solving ability of a candidate. There is no room to craft elaborate stories and this means that either the candidate can solve the problem or they can’t."
},
{
"code": null,
"e": 2960,
"s": 2747,
"text": "Questions based on Data Structures and Algorithms can be scaled up or down according to the knowledge level of the candidate. This means that a variety of candidates can be tested using roughly the same problems."
},
{
"code": null,
"e": 3163,
"s": 2960,
"text": "Data Structures and Algorithms are used to test the analytical skills of the candidates as they are a useful tool to pick out the underlying algorithms in real-world problems and solve them efficiently."
},
{
"code": null,
"e": 3391,
"s": 3163,
"text": "Data Structures and Algorithms are the fundamentals of Software Development. They remain the same no matter what new technology is used and that puts the focus on the problem rather than the technology in the interview process."
},
{
"code": null,
"e": 3542,
"s": 3391,
"text": "Now as we have established that Data Structures and Algorithms are important for interviews in Product Based Companies, let’s focus on learning them. "
},
{
"code": null,
"e": 3652,
"s": 3542,
"text": "Bad programmers worry about the code. Good programmers worry about data structures and their relationships. "
},
{
"code": null,
"e": 3941,
"s": 3652,
"text": "While learning Data Structures and Algorithms, it is best to start small with simple topics and then move on to more and more advanced topics. Some of the basic data structures are Arrays, Linked Lists, Stacks, Queues, etc. while some of the basic algorithms are Sorting, Searching, etc. "
},
{
"code": null,
"e": 4036,
"s": 3941,
"text": "Some of the major problems that can appear while learning Data Structures and Algorithms are: "
},
{
"code": null,
"e": 4355,
"s": 4036,
"text": "Lack of guidance: There is no clear guidance while learning Data Structures and Algorithms. There are numerous topics within these umbrella terms with no specific guidelines about which topics would be more useful for different Product Based Companies. This situation can be quite confusing, especially for a beginner."
},
{
"code": null,
"e": 4637,
"s": 4355,
"text": "No idea from where to start learning: Even if the necessary topics in Data Structures and Algorithms are known, the sheer amount of them leads to a lot of confusion. Most beginners have no idea from where to start learning or even what chronological order to follow while learning."
},
{
"code": null,
"e": 5063,
"s": 4637,
"text": "To solve the above problems, we at GeeksforGeeks have designed a number of online courses to learn Data Structures and Algorithms at affordable prices. One of the latest courses created by us is the Complete Interview Preparation course. This course covers Data Structures and Algorithms along with other subjects in order to completely prepare you for placements in your dream company. To learn more about it, read on . . ."
},
{
"code": null,
"e": 5823,
"s": 5063,
"text": "The Complete Interview Preparation Course is specifically designed for the students and working professionals to help them out in landing their dream job by providing them all the required stuff like premium lectures, theory notes, practice tests, assessment tests, etc. in a single place. In this course, along with Data Structures & Algorithms, you’ll get prepared for other required subjects also like Computer Science Core Subjects, Programming Language, Reasoning & Aptitude, etc. Also, we know that the placement preparation requires some extensive research process and smart learning as not every subject holds the same weightage in the interview – hence, this Complete Interview Preparation Course is extensively curated keeping this factor in mind. "
},
{
"code": null,
"e": 5918,
"s": 5823,
"text": "Some of the prominent features of the Complete Interview Preparation course are listed below: "
},
{
"code": null,
"e": 5975,
"s": 5918,
"text": "Around 200+ algorithmic coding problems will be provided"
},
{
"code": null,
"e": 6022,
"s": 5975,
"text": "Track-based learning & Weekly assessment tests"
},
{
"code": null,
"e": 6129,
"s": 6022,
"text": "Premium Video Lectures recorded by Sandeep Jain (CEO & Founder, GeeksforGeeks) and other industry experts."
},
{
"code": null,
"e": 6212,
"s": 6129,
"text": "Subject-wise Theoretical content & Objective Questions compiled by subject experts"
},
{
"code": null,
"e": 6259,
"s": 6212,
"text": "Lifetime access to the Course will be provided"
},
{
"code": null,
"e": 6333,
"s": 6259,
"text": "Course Completion Certificate & Internship Opportunities at GeeksforGeeks"
},
{
"code": null,
"e": 6400,
"s": 6333,
"text": "College Students will get the year-wise weekly plan for the course"
},
{
"code": null,
"e": 6463,
"s": 6400,
"text": "Free Access to ‘Get Hired Premium’ at GeeksforGeeks Job Portal"
},
{
"code": null,
"e": 6513,
"s": 6463,
"text": "Dedicated TAs for the Doubt Assistance (Optional)"
},
{
"code": null,
"e": 6843,
"s": 6513,
"text": "This course is originally priced at INR 9,999, but it is available at an offer price of INR 6,999. Also, if you want to add on the doubt assistance facility in this course, you’ll be required to pay an additional amount of INR 2,999 only. The Doubt Assistance facility will be valid for the complete 1 year from the registration."
},
{
"code": null,
"e": 7341,
"s": 6843,
"text": "In case you wish to focus exclusively on Data Structures and Algorithms, you can opt for our latest online course to learn Data Structures and Algorithms named – DSA Self Paced Course, which covers everything about Data Structures and Algorithms from the Basic level to the Advanced level. It offers a wealth of programming challenges that you may face at your next job interview. The course focuses mainly on Data Structure & Algorithms as it the key to selection in top product-based companies. "
},
{
"code": null,
"e": 7386,
"s": 7341,
"text": "Some of the Key Features of the Course are: "
},
{
"code": null,
"e": 7469,
"s": 7386,
"text": "Well-organized tutorials on Data-Structures and Algorithms prepared by the experts"
},
{
"code": null,
"e": 7550,
"s": 7469,
"text": "Premium video lectures by Mr. Sandeep Jain, Founder, and C.E.O of GeeksforGeeks."
},
{
"code": null,
"e": 7596,
"s": 7550,
"text": "Weekly Assessment Tests with Video Solutions."
},
{
"code": null,
"e": 7670,
"s": 7596,
"text": "Course Completion Certificate & Internship Opportunities at GeeksforGeeks"
},
{
"code": null,
"e": 7700,
"s": 7670,
"text": "Lifetime access to the Course"
},
{
"code": null,
"e": 7993,
"s": 7700,
"text": "The price of the self-paced online DSA course is INR 2,799. Also, if you want to add on the doubt assistance facility in this course, you’ll be required to pay an additional amount of INR 1,499 only. The Doubt Assistance facility will be valid for the complete 6 months from the registration."
},
{
"code": null,
"e": 8770,
"s": 7993,
"text": "Do you want to get live online classes on Data Structures & Algorithm to learn and master it...?? If yes, then we’ve Geeks Classes – Live Session course for you. It will be an interview centric extensive online (live) program to build and enhance your DSA skills. The course is designed in such a manner that it will help you to improve your problem-solving and coding skills by enhancing your understanding of Data Structures & Algorithms. The primary goal of this course is to help you in the preparation for the Coding interviews of companies like Amazon, Microsoft, Uber, etc. As it will be an online live class – you can attend this class from any geographical location and can ask your doubts or queries as well to the instructor similar to an offline classroom program."
},
{
"code": null,
"e": 8836,
"s": 8770,
"text": "Some of the prominent features of this course are provided below:"
},
{
"code": null,
"e": 8868,
"s": 8836,
"text": "Doubt Solving Assistance (TA’s)"
},
{
"code": null,
"e": 8891,
"s": 8868,
"text": "Limited Batch strength"
},
{
"code": null,
"e": 8921,
"s": 8891,
"text": "Course Completion Certificate"
},
{
"code": null,
"e": 8978,
"s": 8921,
"text": "6 months access to recorded Live lectures of this course"
},
{
"code": null,
"e": 9075,
"s": 8978,
"text": "Other than that, you will also get complimentary access to the course content of the DSA Course."
},
{
"code": null,
"e": 9085,
"s": 9075,
"text": "madhur912"
},
{
"code": null,
"e": 9092,
"s": 9085,
"text": "Amazon"
},
{
"code": null,
"e": 9103,
"s": 9092,
"text": "GFG-Course"
},
{
"code": null,
"e": 9114,
"s": 9103,
"text": "GFG-Update"
},
{
"code": null,
"e": 9121,
"s": 9114,
"text": "Google"
},
{
"code": null,
"e": 9143,
"s": 9121,
"text": "interview-preparation"
},
{
"code": null,
"e": 9153,
"s": 9143,
"text": "Microsoft"
},
{
"code": null,
"e": 9175,
"s": 9153,
"text": "placement preparation"
},
{
"code": null,
"e": 9186,
"s": 9175,
"text": "Algorithms"
},
{
"code": null,
"e": 9202,
"s": 9186,
"text": "Data Structures"
},
{
"code": null,
"e": 9209,
"s": 9202,
"text": "Amazon"
},
{
"code": null,
"e": 9219,
"s": 9209,
"text": "Microsoft"
},
{
"code": null,
"e": 9226,
"s": 9219,
"text": "Google"
},
{
"code": null,
"e": 9242,
"s": 9226,
"text": "Data Structures"
},
{
"code": null,
"e": 9253,
"s": 9242,
"text": "Algorithms"
}
] |
Reduce string by removing outermost parenthesis from each primitive substring
|
28 May, 2022
Given a string S of valid parentheses “(“ and “)”, the task is to print the string obtained by removing the outermost parentheses of every primitive substring from S.
A valid parentheses substring S is primitive if it is non-empty, and cannot be split into two or more non-empty substrings which are also a valid parentheses.
Examples:
Input: S = “(()())(())()” Output: ()()() Explanation: The input string is “(()())(())()” can be decomposed into primitive substrings “(()())” + “(())”+”()”. After removing outermost parentheses of each priiimitive substrings, the string obtained is “()()” + “()” = “()()()”
Input: S = “((()())(())(()(())))” Output: ()()()()(())
Approach: Follow the steps below to solve the problem:
Initialize a variable count to store the number of opening parentheses, i.e. ‘(‘.Add every ‘(‘ to the result if count is greater than 0, i.e. add all ‘(‘ after the first ‘(‘ of a primitive substring is encountered.Add every ‘)’ to the result if count is greater than 0, i.e. add all ‘)’ before the last ‘)’ of a primitive substring is encountered.Finally, print the resultant string obtained.
Initialize a variable count to store the number of opening parentheses, i.e. ‘(‘.
Add every ‘(‘ to the result if count is greater than 0, i.e. add all ‘(‘ after the first ‘(‘ of a primitive substring is encountered.
Add every ‘)’ to the result if count is greater than 0, i.e. add all ‘)’ before the last ‘)’ of a primitive substring is encountered.
Finally, print the resultant string obtained.
Below is the implementation of the above approach-
C++
Java
Python3
C#
Javascript
// C++ program to implement the// above approach#include <bits/stdc++.h>using namespace std; // Function to remove the outermost// parentheses of every primitive// substring from the given stringstring removeOuterParentheses(string S){ // Stores the resultant string string res; // Stores the count of // opened parentheses int count = 0; // Traverse the string for (char c : S) { // If opening parenthesis is // encountered and their // count exceeds 0 if (c == '(' && count++ > 0) // Include the character res += c; // If closing parenthesis is // encountered and their // count is less than count // of opening parentheses if (c == ')' && count-- > 1) // Include the character res += c; } // Return the resultant string return res;} // Driver Codeint main(){ string S = "(()())(())()"; cout << removeOuterParentheses(S);}
// Java program to implement the// above approachimport java.io.*;class GFG{ // Function to remove the outermost// parentheses of every primitive// substring from the given stringstatic String removeOuterParentheses(String S){ // Stores the resultant // string String res = ""; // Stores the count of // opened parentheses int count = 0; // Traverse the string for (int c = 0; c < S.length(); c++) { // If opening parenthesis is // encountered and their // count exceeds 0 if (S.charAt(c) == '(' && count++ > 0) // Include the character res += S.charAt(c); // If closing parenthesis is // encountered and their // count is less than count // of opening parentheses if (S.charAt(c) == ')' && count-- > 1) // Include the character res += S.charAt(c); } // Return the resultant string return res;} // Driver Codepublic static void main(String[] args){ String S = "(()())(())()"; System.out.print(removeOuterParentheses(S));}} // This code is contributed by Chitranayal
# Python3 program to implement the# above approach # Function to remove the outermost# parentheses of every primitive# substring from the given stringdef removeOuterParentheses(S): # Stores the resultant string res = "" # Stores the count of # opened parentheses count = 0 # Traverse the string for c in S: # If opening parenthesis is # encountered and their # count exceeds 0 if (c == '(' and count > 0): # Include the character res += c # If closing parenthesis is # encountered and their # count is less than count # of opening parentheses if (c == '('): count += 1 if (c == ')' and count > 1): # Include the character res += c if (c == ')'): count -= 1 # Return the resultant string return res # Driver Codeif __name__ == '__main__': S = "(()())(())()" print(removeOuterParentheses(S)) # This code is contributed by SURENDRA_GANGWAR
// C# program to implement// the above approach using System; class GFG{ // Function to remove the outermost// parentheses of every primitive// substring from the given stringstatic string removeOuterParentheses(string S){ // Stores the resultant // string string res = ""; // Stores the count of // opened parentheses int count = 0; // Traverse the string for(int c = 0; c < S.Length; c++) { // If opening parenthesis is // encountered and their // count exceeds 0 if (S == '(' && count++ > 0) // Include the character res += S; // If closing parenthesis is // encountered and their // count is less than count // of opening parentheses if (S == ')' && count-- > 1) // Include the character res += S; } // Return the resultant string return res;} // Driver Codepublic static void Main(){ string S = "(()())(())()"; Console.Write(removeOuterParentheses(S));}} // This code is contributed by sanjoy_62
<script> // Javascript program to implement the// above approach // Function to remove the outermost// parentheses of every primitive// substring from the given stringfunction removeOuterParentheses(S){ // Stores the resultant// stringlet res = ""; // Stores the count of// opened parentheseslet count = 0; // Traverse the stringfor (let c = 0; c < S.length; c++){ // If opening parenthesis is // encountered and their // count exceeds 0 if (S.charAt(c) == '(' && count++ > 0) // Include the character res += S.charAt(c); // If closing parenthesis is // encountered and their // count is less than count // of opening parentheses if (S.charAt(c) == ')' && count-- > 1) // Include the character res += S.charAt(c);} // Return the resultant stringreturn res;} // Driver Code let S = "(()())(())()";document.write(removeOuterParentheses(S)); // This code is contributed by jana_sayantan.</script>
()()()
Time Complexity: O(N) where n is number of elements in given string. As, we are using a loop to traverse N times so it will cost us O(N) time Auxiliary Space: O(N), as we are using extra space for stack.
ukasp
SURENDRA_GANGWAR
sanjoy_62
jana_sayantan
varshagumber28
rohitkumarsinghcna
frequency-counting
substring
Mathematical
Searching
Strings
Searching
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Find minimum number of coins that make a given value
Minimum number of jumps to reach end
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Linear Search
K'th Smallest/Largest Element in Unsorted Array | Set 1
Search an element in a sorted and rotated array
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n28 May, 2022"
},
{
"code": null,
"e": 220,
"s": 53,
"text": "Given a string S of valid parentheses “(“ and “)”, the task is to print the string obtained by removing the outermost parentheses of every primitive substring from S."
},
{
"code": null,
"e": 379,
"s": 220,
"text": "A valid parentheses substring S is primitive if it is non-empty, and cannot be split into two or more non-empty substrings which are also a valid parentheses."
},
{
"code": null,
"e": 389,
"s": 379,
"text": "Examples:"
},
{
"code": null,
"e": 663,
"s": 389,
"text": "Input: S = “(()())(())()” Output: ()()() Explanation: The input string is “(()())(())()” can be decomposed into primitive substrings “(()())” + “(())”+”()”. After removing outermost parentheses of each priiimitive substrings, the string obtained is “()()” + “()” = “()()()”"
},
{
"code": null,
"e": 718,
"s": 663,
"text": "Input: S = “((()())(())(()(())))” Output: ()()()()(())"
},
{
"code": null,
"e": 773,
"s": 718,
"text": "Approach: Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 1166,
"s": 773,
"text": "Initialize a variable count to store the number of opening parentheses, i.e. ‘(‘.Add every ‘(‘ to the result if count is greater than 0, i.e. add all ‘(‘ after the first ‘(‘ of a primitive substring is encountered.Add every ‘)’ to the result if count is greater than 0, i.e. add all ‘)’ before the last ‘)’ of a primitive substring is encountered.Finally, print the resultant string obtained."
},
{
"code": null,
"e": 1248,
"s": 1166,
"text": "Initialize a variable count to store the number of opening parentheses, i.e. ‘(‘."
},
{
"code": null,
"e": 1382,
"s": 1248,
"text": "Add every ‘(‘ to the result if count is greater than 0, i.e. add all ‘(‘ after the first ‘(‘ of a primitive substring is encountered."
},
{
"code": null,
"e": 1516,
"s": 1382,
"text": "Add every ‘)’ to the result if count is greater than 0, i.e. add all ‘)’ before the last ‘)’ of a primitive substring is encountered."
},
{
"code": null,
"e": 1562,
"s": 1516,
"text": "Finally, print the resultant string obtained."
},
{
"code": null,
"e": 1613,
"s": 1562,
"text": "Below is the implementation of the above approach-"
},
{
"code": null,
"e": 1617,
"s": 1613,
"text": "C++"
},
{
"code": null,
"e": 1622,
"s": 1617,
"text": "Java"
},
{
"code": null,
"e": 1630,
"s": 1622,
"text": "Python3"
},
{
"code": null,
"e": 1633,
"s": 1630,
"text": "C#"
},
{
"code": null,
"e": 1644,
"s": 1633,
"text": "Javascript"
},
{
"code": "// C++ program to implement the// above approach#include <bits/stdc++.h>using namespace std; // Function to remove the outermost// parentheses of every primitive// substring from the given stringstring removeOuterParentheses(string S){ // Stores the resultant string string res; // Stores the count of // opened parentheses int count = 0; // Traverse the string for (char c : S) { // If opening parenthesis is // encountered and their // count exceeds 0 if (c == '(' && count++ > 0) // Include the character res += c; // If closing parenthesis is // encountered and their // count is less than count // of opening parentheses if (c == ')' && count-- > 1) // Include the character res += c; } // Return the resultant string return res;} // Driver Codeint main(){ string S = \"(()())(())()\"; cout << removeOuterParentheses(S);}",
"e": 2620,
"s": 1644,
"text": null
},
{
"code": "// Java program to implement the// above approachimport java.io.*;class GFG{ // Function to remove the outermost// parentheses of every primitive// substring from the given stringstatic String removeOuterParentheses(String S){ // Stores the resultant // string String res = \"\"; // Stores the count of // opened parentheses int count = 0; // Traverse the string for (int c = 0; c < S.length(); c++) { // If opening parenthesis is // encountered and their // count exceeds 0 if (S.charAt(c) == '(' && count++ > 0) // Include the character res += S.charAt(c); // If closing parenthesis is // encountered and their // count is less than count // of opening parentheses if (S.charAt(c) == ')' && count-- > 1) // Include the character res += S.charAt(c); } // Return the resultant string return res;} // Driver Codepublic static void main(String[] args){ String S = \"(()())(())()\"; System.out.print(removeOuterParentheses(S));}} // This code is contributed by Chitranayal",
"e": 3679,
"s": 2620,
"text": null
},
{
"code": "# Python3 program to implement the# above approach # Function to remove the outermost# parentheses of every primitive# substring from the given stringdef removeOuterParentheses(S): # Stores the resultant string res = \"\" # Stores the count of # opened parentheses count = 0 # Traverse the string for c in S: # If opening parenthesis is # encountered and their # count exceeds 0 if (c == '(' and count > 0): # Include the character res += c # If closing parenthesis is # encountered and their # count is less than count # of opening parentheses if (c == '('): count += 1 if (c == ')' and count > 1): # Include the character res += c if (c == ')'): count -= 1 # Return the resultant string return res # Driver Codeif __name__ == '__main__': S = \"(()())(())()\" print(removeOuterParentheses(S)) # This code is contributed by SURENDRA_GANGWAR",
"e": 4737,
"s": 3679,
"text": null
},
{
"code": "// C# program to implement// the above approach using System; class GFG{ // Function to remove the outermost// parentheses of every primitive// substring from the given stringstatic string removeOuterParentheses(string S){ // Stores the resultant // string string res = \"\"; // Stores the count of // opened parentheses int count = 0; // Traverse the string for(int c = 0; c < S.Length; c++) { // If opening parenthesis is // encountered and their // count exceeds 0 if (S == '(' && count++ > 0) // Include the character res += S; // If closing parenthesis is // encountered and their // count is less than count // of opening parentheses if (S == ')' && count-- > 1) // Include the character res += S; } // Return the resultant string return res;} // Driver Codepublic static void Main(){ string S = \"(()())(())()\"; Console.Write(removeOuterParentheses(S));}} // This code is contributed by sanjoy_62",
"e": 5740,
"s": 4737,
"text": null
},
{
"code": "<script> // Javascript program to implement the// above approach // Function to remove the outermost// parentheses of every primitive// substring from the given stringfunction removeOuterParentheses(S){ // Stores the resultant// stringlet res = \"\"; // Stores the count of// opened parentheseslet count = 0; // Traverse the stringfor (let c = 0; c < S.length; c++){ // If opening parenthesis is // encountered and their // count exceeds 0 if (S.charAt(c) == '(' && count++ > 0) // Include the character res += S.charAt(c); // If closing parenthesis is // encountered and their // count is less than count // of opening parentheses if (S.charAt(c) == ')' && count-- > 1) // Include the character res += S.charAt(c);} // Return the resultant stringreturn res;} // Driver Code let S = \"(()())(())()\";document.write(removeOuterParentheses(S)); // This code is contributed by jana_sayantan.</script>",
"e": 6697,
"s": 5740,
"text": null
},
{
"code": null,
"e": 6704,
"s": 6697,
"text": "()()()"
},
{
"code": null,
"e": 6910,
"s": 6706,
"text": "Time Complexity: O(N) where n is number of elements in given string. As, we are using a loop to traverse N times so it will cost us O(N) time Auxiliary Space: O(N), as we are using extra space for stack."
},
{
"code": null,
"e": 6916,
"s": 6910,
"text": "ukasp"
},
{
"code": null,
"e": 6933,
"s": 6916,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 6943,
"s": 6933,
"text": "sanjoy_62"
},
{
"code": null,
"e": 6957,
"s": 6943,
"text": "jana_sayantan"
},
{
"code": null,
"e": 6972,
"s": 6957,
"text": "varshagumber28"
},
{
"code": null,
"e": 6991,
"s": 6972,
"text": "rohitkumarsinghcna"
},
{
"code": null,
"e": 7010,
"s": 6991,
"text": "frequency-counting"
},
{
"code": null,
"e": 7020,
"s": 7010,
"text": "substring"
},
{
"code": null,
"e": 7033,
"s": 7020,
"text": "Mathematical"
},
{
"code": null,
"e": 7043,
"s": 7033,
"text": "Searching"
},
{
"code": null,
"e": 7051,
"s": 7043,
"text": "Strings"
},
{
"code": null,
"e": 7061,
"s": 7051,
"text": "Searching"
},
{
"code": null,
"e": 7069,
"s": 7061,
"text": "Strings"
},
{
"code": null,
"e": 7082,
"s": 7069,
"text": "Mathematical"
},
{
"code": null,
"e": 7180,
"s": 7082,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7204,
"s": 7180,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 7225,
"s": 7204,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 7239,
"s": 7225,
"text": "Prime Numbers"
},
{
"code": null,
"e": 7292,
"s": 7239,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 7329,
"s": 7292,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 7343,
"s": 7329,
"text": "Binary Search"
},
{
"code": null,
"e": 7411,
"s": 7343,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 7425,
"s": 7411,
"text": "Linear Search"
},
{
"code": null,
"e": 7481,
"s": 7425,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
}
] |
Using “not equal” in MySQL?
|
If you want to work with not equal operator, then use the <> operator. The syntax is as follows −
SELECT *FROM yourTableName WHERE yourColumnName <> anyValue;
To understand the above syntax, let us first create a table. The query to create a table is as follows −
mysql> create table NotEqualDemo
-> (
-> ProductId int
-> );
Query OK, 0 rows affected (0.53 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into NotEqualDemo values(101);
Query OK, 1 row affected (0.13 sec)
mysql> insert into NotEqualDemo values(102);
Query OK, 1 row affected (0.23 sec)
mysql> insert into NotEqualDemo values(103);
Query OK, 1 row affected (0.11 sec)
mysql> insert into NotEqualDemo values(104);
Query OK, 1 row affected (0.13 sec)
mysql> insert into NotEqualDemo values(105);
Query OK, 1 row affected (0.12 sec)
Let us now display all records from the table using select command. The query is as follows −
mysql> select *from NotEqualDemo;
The following is the output −
+-----------+
| ProductId |
+-----------+
| 101 |
| 102 |
| 103 |
| 104 |
| 105 |
+-----------+
5 rows in set (0.00 sec)
Here we are using <> operator to filter the data which is not equal to 104. In this, all the data will be displayed except 104. The query is as follows −
mysql> select *from NotEqualDemo where ProductId <> 104 or ProductId is null;
The following is the output −
+-----------+
| ProductId |
+-----------+
| 101 |
| 102 |
| 103 |
| 105 |
+-----------+
4 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1285,
"s": 1187,
"text": "If you want to work with not equal operator, then use the <> operator. The syntax is as follows −"
},
{
"code": null,
"e": 1346,
"s": 1285,
"text": "SELECT *FROM yourTableName WHERE yourColumnName <> anyValue;"
},
{
"code": null,
"e": 1451,
"s": 1346,
"text": "To understand the above syntax, let us first create a table. The query to create a table is as follows −"
},
{
"code": null,
"e": 1549,
"s": 1451,
"text": "mysql> create table NotEqualDemo\n-> (\n-> ProductId int\n-> );\nQuery OK, 0 rows affected (0.53 sec)"
},
{
"code": null,
"e": 1630,
"s": 1549,
"text": "Insert some records in the table using insert command. The query is as follows −"
},
{
"code": null,
"e": 2039,
"s": 1630,
"text": "mysql> insert into NotEqualDemo values(101);\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into NotEqualDemo values(102);\nQuery OK, 1 row affected (0.23 sec)\n\nmysql> insert into NotEqualDemo values(103);\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into NotEqualDemo values(104);\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into NotEqualDemo values(105);\nQuery OK, 1 row affected (0.12 sec)"
},
{
"code": null,
"e": 2133,
"s": 2039,
"text": "Let us now display all records from the table using select command. The query is as follows −"
},
{
"code": null,
"e": 2167,
"s": 2133,
"text": "mysql> select *from NotEqualDemo;"
},
{
"code": null,
"e": 2197,
"s": 2167,
"text": "The following is the output −"
},
{
"code": null,
"e": 2348,
"s": 2197,
"text": "+-----------+\n| ProductId |\n+-----------+\n| 101 |\n| 102 |\n| 103 |\n| 104 |\n| 105 |\n+-----------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2502,
"s": 2348,
"text": "Here we are using <> operator to filter the data which is not equal to 104. In this, all the data will be displayed except 104. The query is as follows −"
},
{
"code": null,
"e": 2580,
"s": 2502,
"text": "mysql> select *from NotEqualDemo where ProductId <> 104 or ProductId is null;"
},
{
"code": null,
"e": 2610,
"s": 2580,
"text": "The following is the output −"
},
{
"code": null,
"e": 2747,
"s": 2610,
"text": "+-----------+\n| ProductId |\n+-----------+\n| 101 |\n| 102 |\n| 103 |\n| 105 |\n+-----------+\n4 rows in set (0.00 sec)"
}
] |
PLSQL | LOG Function
|
25 Oct, 2019
The PLSQL LOG function is used for returning the logarithm of n base m. The LOG function accepts two parameters which are used to calculate the logarithmic value. The LOG function returns a value of the numeric data type.
This function takes as an argument any numeric data type as well as any non-numeric data type that can be implicitly converted to a numeric data type. If in any case, the argument is BINARY_FLOAT or BINARY_DOUBLE, then the LOG function returns BINARY_DOUBLE, otherwise it returns number.
Syntax:
LOG( m, n )
Parameters Used:
m – It is used to specify the base number. It should be any positive numeric value except 0 and 1.
n – It is used to specify the number whose logarithmic value needs to be calculated with a specific base. It should be a positive numeric value.
Return Value:The LOG function in PLSQL returns a numeric value.
Supported Versions of Oracle/PLSQL:
Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i
Oracle 12c
Oracle 11g
Oracle 10g
Oracle 9i
Oracle 8i
Example-1: Using positive numeric values as arguments in the LOG function.
DECLARE
Test_Number1 number := 9;
Test_Number2 number := 3;
BEGIN
dbms_output.put_line(LOG(Test_Number1,
Test_Number2));
END;
Output:
0.5
Example-2: Using positive numeric values as arguments in the LOG function.
DECLARE
Test_Number1 number := 3;
Test_Number2 number := 9;
BEGIN
dbms_output.put_line(LOG(Test_Number1,
Test_Number2));
END;
Output:
2
Example-3: Using same positive numeric values in both the arguments in the LOG function.
DECLARE
Test_Number1 number := 3;
Test_Number2 number := 3;
BEGIN
dbms_output.put_line(LOG(Test_Number1,
Test_Number2));
END;
Output:
1
Example-4: Using zero in the base value argument in the LOG function.
DECLARE
Test_Number1 number := 0;
Test_Number2 number := 3;
BEGIN
dbms_output.put_line(LOG(Test_Number1,
Test_Number2));
END;
Output:
numeric or value error
The above example throws error because the LOG function doesn’t except 0 and 1 as base values in the argument.
Example-5: Using LOG function with select query.
SELECT LOG(2, 8) "Log base 2 of 8" FROM DUAL;
Output:
3
Advantages:The LOG function accepts any numeric datatype as well as any non-numeric datatype as an argument that can be implicitly converted to a numeric datatype.
SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Oct, 2019"
},
{
"code": null,
"e": 250,
"s": 28,
"text": "The PLSQL LOG function is used for returning the logarithm of n base m. The LOG function accepts two parameters which are used to calculate the logarithmic value. The LOG function returns a value of the numeric data type."
},
{
"code": null,
"e": 538,
"s": 250,
"text": "This function takes as an argument any numeric data type as well as any non-numeric data type that can be implicitly converted to a numeric data type. If in any case, the argument is BINARY_FLOAT or BINARY_DOUBLE, then the LOG function returns BINARY_DOUBLE, otherwise it returns number."
},
{
"code": null,
"e": 546,
"s": 538,
"text": "Syntax:"
},
{
"code": null,
"e": 558,
"s": 546,
"text": "LOG( m, n )"
},
{
"code": null,
"e": 575,
"s": 558,
"text": "Parameters Used:"
},
{
"code": null,
"e": 674,
"s": 575,
"text": "m – It is used to specify the base number. It should be any positive numeric value except 0 and 1."
},
{
"code": null,
"e": 819,
"s": 674,
"text": "n – It is used to specify the number whose logarithmic value needs to be calculated with a specific base. It should be a positive numeric value."
},
{
"code": null,
"e": 883,
"s": 819,
"text": "Return Value:The LOG function in PLSQL returns a numeric value."
},
{
"code": null,
"e": 919,
"s": 883,
"text": "Supported Versions of Oracle/PLSQL:"
},
{
"code": null,
"e": 968,
"s": 919,
"text": "Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i"
},
{
"code": null,
"e": 979,
"s": 968,
"text": "Oracle 12c"
},
{
"code": null,
"e": 990,
"s": 979,
"text": "Oracle 11g"
},
{
"code": null,
"e": 1001,
"s": 990,
"text": "Oracle 10g"
},
{
"code": null,
"e": 1011,
"s": 1001,
"text": "Oracle 9i"
},
{
"code": null,
"e": 1021,
"s": 1011,
"text": "Oracle 8i"
},
{
"code": null,
"e": 1096,
"s": 1021,
"text": "Example-1: Using positive numeric values as arguments in the LOG function."
},
{
"code": null,
"e": 1272,
"s": 1096,
"text": "DECLARE \n Test_Number1 number := 9;\n Test_Number2 number := 3;\n \nBEGIN \n dbms_output.put_line(LOG(Test_Number1, \n Test_Number2)); \n \nEND; "
},
{
"code": null,
"e": 1280,
"s": 1272,
"text": "Output:"
},
{
"code": null,
"e": 1285,
"s": 1280,
"text": "0.5 "
},
{
"code": null,
"e": 1360,
"s": 1285,
"text": "Example-2: Using positive numeric values as arguments in the LOG function."
},
{
"code": null,
"e": 1536,
"s": 1360,
"text": "DECLARE \n Test_Number1 number := 3;\n Test_Number2 number := 9;\n \nBEGIN \n dbms_output.put_line(LOG(Test_Number1, \n Test_Number2)); \n \nEND; "
},
{
"code": null,
"e": 1544,
"s": 1536,
"text": "Output:"
},
{
"code": null,
"e": 1547,
"s": 1544,
"text": "2 "
},
{
"code": null,
"e": 1636,
"s": 1547,
"text": "Example-3: Using same positive numeric values in both the arguments in the LOG function."
},
{
"code": null,
"e": 1812,
"s": 1636,
"text": "DECLARE \n Test_Number1 number := 3;\n Test_Number2 number := 3;\n \nBEGIN \n dbms_output.put_line(LOG(Test_Number1, \n Test_Number2)); \n \nEND; "
},
{
"code": null,
"e": 1820,
"s": 1812,
"text": "Output:"
},
{
"code": null,
"e": 1823,
"s": 1820,
"text": "1 "
},
{
"code": null,
"e": 1893,
"s": 1823,
"text": "Example-4: Using zero in the base value argument in the LOG function."
},
{
"code": null,
"e": 2069,
"s": 1893,
"text": "DECLARE \n Test_Number1 number := 0;\n Test_Number2 number := 3;\n \nBEGIN \n dbms_output.put_line(LOG(Test_Number1, \n Test_Number2)); \n \nEND; "
},
{
"code": null,
"e": 2077,
"s": 2069,
"text": "Output:"
},
{
"code": null,
"e": 2101,
"s": 2077,
"text": "numeric or value error "
},
{
"code": null,
"e": 2212,
"s": 2101,
"text": "The above example throws error because the LOG function doesn’t except 0 and 1 as base values in the argument."
},
{
"code": null,
"e": 2261,
"s": 2212,
"text": "Example-5: Using LOG function with select query."
},
{
"code": null,
"e": 2308,
"s": 2261,
"text": "SELECT LOG(2, 8) \"Log base 2 of 8\" FROM DUAL; "
},
{
"code": null,
"e": 2316,
"s": 2308,
"text": "Output:"
},
{
"code": null,
"e": 2319,
"s": 2316,
"text": "3 "
},
{
"code": null,
"e": 2483,
"s": 2319,
"text": "Advantages:The LOG function accepts any numeric datatype as well as any non-numeric datatype as an argument that can be implicitly converted to a numeric datatype."
},
{
"code": null,
"e": 2494,
"s": 2483,
"text": "SQL-PL/SQL"
},
{
"code": null,
"e": 2498,
"s": 2494,
"text": "SQL"
},
{
"code": null,
"e": 2502,
"s": 2498,
"text": "SQL"
}
] |
Wald Test
|
18 Jul, 2021
Prerequisite : Maximum Likelihood Estimate
NOTE : It is advised to read the prerequisite article before moving on to Wald Test.
Wald Test : It is a hypothesis test done on the parameters calculated by the Maximum Likelihood Estimate (MLE). It checks if the value of the true input parameters has the same likelihood as the parameters calculated by MLE. In simple words, the larger this wald estimate value, the less likely it is that the input parameters is true. Let us understand in-depth the working of wald test. Observe the formula given below:
where,
θ_hat -> a vector of all parameters estimated by the maximum likelihood.
θ0 -> a vector of all true input parameters considered under null hypothesis. (H0)
W -> Wald estimate.
Intuition
We consider the initial values of the parameters under the null hypothesis, H0. Now the question remains whether we should accept the null hypothesis and move forward with these parameter values or reject them. This is where the wald test comes into picture.
Wald test tells the difference measure between parameters under the null hypothesis and the ones estimated by the maximum likelihood estimate. If this difference is very large, the wald estimate value is also large. Hence, we reject the null hypothesis and consider the parameters estimated by the MLE.
If this difference measure is small, then the wald estimate value is also small, and we do not reject the null hypothesis. Consider the image given below for in-depth understanding. (Fig 1)
Fig 1 : Intuition
In the above image, we see the Likelihood of the sample y under parameters θ on the y axis. We see that the horizontal difference in θ0 and θ_hat is similar in case of the red and green pdf curves. However, the interpretation of the difference measure both is done differently. See the following two cases given below:
Case 1 : Green probability distribution function
In this case, we see that there is a huge difference in the likelihood value of θ_hat and θ0. So, here the variance of θ_hat is relatively small, hence the wald estimate tends to be quite high. This implies that parameters estimated under null hypothesis H0 are way different than the one calculated by MLE. Hence, we reject the null hypothesis.
Case 2 : Red probability distribution function
However, in this case the value of likelihood of θ_hat and θ0 is quite similar. So, the variance of θ_hat here is quite large, hence making the wald estimate to be quite low. Therefore, we can consider the true values of parameters for the sample data y. Hence, we do not need to reject the null hypothesis.
Wald test can be used to test the associativity between the independent variables dependent variable. A Wald test can be used in a great variety of different models including models for dichotomous variables and models for continuous variables. It has tons of applications in many areas of statistics. Any time a likelihood based approach is used for estimation (e.g., logistic regression, etc) the wald test is used. For any doubt/query, comment below.
ML-Statistics
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Support Vector Machine Algorithm
Introduction to Recurrent Neural Network
ML | Monte Carlo Tree Search (MCTS)
Markov Decision Process
DBSCAN Clustering in ML | Density based clustering
Normalization vs Standardization
Bagging vs Boosting in Machine Learning
Principal Component Analysis with Python
Types of Environments in AI
k-nearest neighbor algorithm in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jul, 2021"
},
{
"code": null,
"e": 71,
"s": 28,
"text": "Prerequisite : Maximum Likelihood Estimate"
},
{
"code": null,
"e": 156,
"s": 71,
"text": "NOTE : It is advised to read the prerequisite article before moving on to Wald Test."
},
{
"code": null,
"e": 578,
"s": 156,
"text": "Wald Test : It is a hypothesis test done on the parameters calculated by the Maximum Likelihood Estimate (MLE). It checks if the value of the true input parameters has the same likelihood as the parameters calculated by MLE. In simple words, the larger this wald estimate value, the less likely it is that the input parameters is true. Let us understand in-depth the working of wald test. Observe the formula given below:"
},
{
"code": null,
"e": 761,
"s": 578,
"text": "where,\nθ_hat -> a vector of all parameters estimated by the maximum likelihood.\nθ0 -> a vector of all true input parameters considered under null hypothesis. (H0)\nW -> Wald estimate."
},
{
"code": null,
"e": 771,
"s": 761,
"text": "Intuition"
},
{
"code": null,
"e": 1031,
"s": 771,
"text": "We consider the initial values of the parameters under the null hypothesis, H0. Now the question remains whether we should accept the null hypothesis and move forward with these parameter values or reject them. This is where the wald test comes into picture. "
},
{
"code": null,
"e": 1335,
"s": 1031,
"text": "Wald test tells the difference measure between parameters under the null hypothesis and the ones estimated by the maximum likelihood estimate. If this difference is very large, the wald estimate value is also large. Hence, we reject the null hypothesis and consider the parameters estimated by the MLE. "
},
{
"code": null,
"e": 1525,
"s": 1335,
"text": "If this difference measure is small, then the wald estimate value is also small, and we do not reject the null hypothesis. Consider the image given below for in-depth understanding. (Fig 1)"
},
{
"code": null,
"e": 1543,
"s": 1525,
"text": "Fig 1 : Intuition"
},
{
"code": null,
"e": 1862,
"s": 1543,
"text": "In the above image, we see the Likelihood of the sample y under parameters θ on the y axis. We see that the horizontal difference in θ0 and θ_hat is similar in case of the red and green pdf curves. However, the interpretation of the difference measure both is done differently. See the following two cases given below:"
},
{
"code": null,
"e": 1911,
"s": 1862,
"text": "Case 1 : Green probability distribution function"
},
{
"code": null,
"e": 2258,
"s": 1911,
"text": "In this case, we see that there is a huge difference in the likelihood value of θ_hat and θ0. So, here the variance of θ_hat is relatively small, hence the wald estimate tends to be quite high. This implies that parameters estimated under null hypothesis H0 are way different than the one calculated by MLE. Hence, we reject the null hypothesis. "
},
{
"code": null,
"e": 2305,
"s": 2258,
"text": "Case 2 : Red probability distribution function"
},
{
"code": null,
"e": 2614,
"s": 2305,
"text": "However, in this case the value of likelihood of θ_hat and θ0 is quite similar. So, the variance of θ_hat here is quite large, hence making the wald estimate to be quite low. Therefore, we can consider the true values of parameters for the sample data y. Hence, we do not need to reject the null hypothesis. "
},
{
"code": null,
"e": 3069,
"s": 2614,
"text": "Wald test can be used to test the associativity between the independent variables dependent variable. A Wald test can be used in a great variety of different models including models for dichotomous variables and models for continuous variables. It has tons of applications in many areas of statistics. Any time a likelihood based approach is used for estimation (e.g., logistic regression, etc) the wald test is used. For any doubt/query, comment below. "
},
{
"code": null,
"e": 3083,
"s": 3069,
"text": "ML-Statistics"
},
{
"code": null,
"e": 3100,
"s": 3083,
"text": "Machine Learning"
},
{
"code": null,
"e": 3117,
"s": 3100,
"text": "Machine Learning"
},
{
"code": null,
"e": 3215,
"s": 3117,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3248,
"s": 3215,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 3289,
"s": 3248,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 3325,
"s": 3289,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 3349,
"s": 3325,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 3400,
"s": 3349,
"text": "DBSCAN Clustering in ML | Density based clustering"
},
{
"code": null,
"e": 3433,
"s": 3400,
"text": "Normalization vs Standardization"
},
{
"code": null,
"e": 3473,
"s": 3433,
"text": "Bagging vs Boosting in Machine Learning"
},
{
"code": null,
"e": 3514,
"s": 3473,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 3542,
"s": 3514,
"text": "Types of Environments in AI"
}
] |
ushort keyword in C#
|
22 Jun, 2020
Keywords are the words in a language that are used for some internal process or represent some predefined actions. ushort is a keyword that is used to declare a variable which can store an unsigned integer value from the range 0 to 65,535. It is an alias of System.UInt16.
Syntax:
ushort variable_name = value;
ushort keyword occupies 2 bytes (16 bits) space in the memory.
Example:
Input: num: 5
Output: num: 5
Size of a ushort variable: 2
Input: num = 8765
Output: num: 8765
Type of num: System.UInt16
Size of a ushort variable: 2
Example 1:
// C# program for ushort keywordusing System;using System.Text; class GFG { static void Main(string[] args) { // variable declaration ushort num = 5; // to print value Console.WriteLine("num: " + num); // to print size Console.WriteLine("Size of a ushort variable: " + sizeof(ushort)); }}
Output:
num: 5
Size of a ushort variable: 2
Example 2:
// C# program for ushort keywordusing System;using System.Text; namespace Test { class GFG { static void Main(string[] args) { // variable declaration ushort num = 8765; // to print value Console.WriteLine("num: " + num); // to print type of variable Console.WriteLine("Type of num: " + num.GetType()); // to print size Console.WriteLine("Size of a ushort variable: " + sizeof(ushort)); // to print minimum & maximum value of ushort Console.WriteLine("Min value of ushort: " + ushort.MinValue); Console.WriteLine("Max value of ushort: " + ushort.MaxValue); }}}
Output:
num: 8765
Type of num: System.UInt16
Size of a ushort variable: 2
Min value of ushort: 0
Max value of ushort: 65535
CSharp-keyword
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Jun, 2020"
},
{
"code": null,
"e": 301,
"s": 28,
"text": "Keywords are the words in a language that are used for some internal process or represent some predefined actions. ushort is a keyword that is used to declare a variable which can store an unsigned integer value from the range 0 to 65,535. It is an alias of System.UInt16."
},
{
"code": null,
"e": 309,
"s": 301,
"text": "Syntax:"
},
{
"code": null,
"e": 339,
"s": 309,
"text": "ushort variable_name = value;"
},
{
"code": null,
"e": 402,
"s": 339,
"text": "ushort keyword occupies 2 bytes (16 bits) space in the memory."
},
{
"code": null,
"e": 411,
"s": 402,
"text": "Example:"
},
{
"code": null,
"e": 588,
"s": 411,
"text": "Input: num: 5\n\nOutput: num: 5\n Size of a ushort variable: 2\n\nInput: num = 8765\n\nOutput: num: 8765\n Type of num: System.UInt16\n Size of a ushort variable: 2"
},
{
"code": null,
"e": 599,
"s": 588,
"text": "Example 1:"
},
{
"code": "// C# program for ushort keywordusing System;using System.Text; class GFG { static void Main(string[] args) { // variable declaration ushort num = 5; // to print value Console.WriteLine(\"num: \" + num); // to print size Console.WriteLine(\"Size of a ushort variable: \" + sizeof(ushort)); }}",
"e": 946,
"s": 599,
"text": null
},
{
"code": null,
"e": 954,
"s": 946,
"text": "Output:"
},
{
"code": null,
"e": 991,
"s": 954,
"text": "num: 5\nSize of a ushort variable: 2\n"
},
{
"code": null,
"e": 1002,
"s": 991,
"text": "Example 2:"
},
{
"code": "// C# program for ushort keywordusing System;using System.Text; namespace Test { class GFG { static void Main(string[] args) { // variable declaration ushort num = 8765; // to print value Console.WriteLine(\"num: \" + num); // to print type of variable Console.WriteLine(\"Type of num: \" + num.GetType()); // to print size Console.WriteLine(\"Size of a ushort variable: \" + sizeof(ushort)); // to print minimum & maximum value of ushort Console.WriteLine(\"Min value of ushort: \" + ushort.MinValue); Console.WriteLine(\"Max value of ushort: \" + ushort.MaxValue); }}}",
"e": 1661,
"s": 1002,
"text": null
},
{
"code": null,
"e": 1669,
"s": 1661,
"text": "Output:"
},
{
"code": null,
"e": 1786,
"s": 1669,
"text": "num: 8765\nType of num: System.UInt16\nSize of a ushort variable: 2\nMin value of ushort: 0\nMax value of ushort: 65535\n"
},
{
"code": null,
"e": 1801,
"s": 1786,
"text": "CSharp-keyword"
},
{
"code": null,
"e": 1804,
"s": 1801,
"text": "C#"
}
] |
Merge two DataFrames with different amounts of columns in PySpark
|
21 Dec, 2021
In this article, we will discuss how to perform union on two dataframes with different amounts of columns in PySpark in Python.
Here we are having 3 columns named id, name, and address.
Python3
# importing moduleimport pyspark # import when and lit functionfrom pyspark.sql.functions import when, lit # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [["1", "sravan", "kakumanu"], ["2", "ojaswi", "hyd"], ["3", "rohith", "delhi"], ["4", "sridevi", "kakumanu"], ["5", "bobby", "guntur"]] # specify column namescolumns = ['ID', 'NAME', 'Address'] # creating a dataframe from the lists of datadataframe1 = spark.createDataFrame(data, columns) # displaydataframe1.show()
Output:
Here we are going to create dataframe with 2 columns
Python3
# importing moduleimport pyspark # import when and lit functionfrom pyspark.sql.functions import when, lit # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [["1", 23], ["2", 21], ["3", 32], ] # specify column namescolumns = ['ID', 'Age'] # creating a dataframe from the lists of datadataframe2 = spark.createDataFrame(data, columns) # displaydataframe2.show()
Output:
We can not perform union operations because the columns are different, so we have to add the missing columns. Here In first dataframe (dataframe1) , the columns [‘ID’, ‘NAME’, ‘Address’] and second dataframe (dataframe2 ) columns are [‘ID’,’Age’].
Now we have to add the Age column to the first dataframe and NAME and Address in the second dataframe, we can do this by using lit() function. This function is available in pyspark.sql.functions which is used to add a column with a value. Here we are going to add a value with None.
Syntax:
for column in [column for column in dataframe1.columns if column not in dataframe2.columns]:
dataframe2 = dataframe2.withColumn(column, lit(None))
where,
dataframe1 is the firstdata frame
dataframe2 is the second dataframe
Python3
# importing moduleimport pyspark # import lit functionfrom pyspark.sql.functions import lit # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [["1", "sravan", "kakumanu"], ["2", "ojaswi", "hyd"], ["3", "rohith", "delhi"], ["4", "sridevi", "kakumanu"], ["5", "bobby", "guntur"]] # specify column namescolumns = ['ID', 'NAME', 'Address'] # creating a dataframe from the lists of datadataframe1 = spark.createDataFrame(data, columns) # list of employee datadata = [["1", 23], ["2", 21], ["3", 32], ] # specify column namescolumns = ['ID', 'Age'] # creating a dataframe from the lists of datadataframe2 = spark.createDataFrame(data, columns) # add columns in dataframe1 that are missing from dataframe2for column in [column for column in dataframe2.columns if column not in dataframe1.columns]: dataframe1 = dataframe1.withColumn(column, lit(None)) # add columns in dataframe2 that are missing from dataframe1for column in [column for column in dataframe1.columns if column not in dataframe2.columns]: dataframe2 = dataframe2.withColumn(column, lit(None)) # now see the columns of dataframe1print(dataframe1.columns) # now see the columns of dataframe2print(dataframe2.columns)
Output:
['ID', 'NAME', 'Address', 'Age']
['ID', 'Age', 'NAME', 'Address']
Now we can perform union by using union() function. This function will join two dataframes.
Syntax: dataframe1.union(dataframe2)
Example:
Python3
# importing moduleimport pyspark # import lit functionfrom pyspark.sql.functions import lit # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [["1", "sravan", "kakumanu"], ["2", "ojaswi", "hyd"], ["3", "rohith", "delhi"], ["4", "sridevi", "kakumanu"], ["5", "bobby", "guntur"]] # specify column namescolumns = ['ID', 'NAME', 'Address'] # creating a dataframe from the lists of datadataframe1 = spark.createDataFrame(data, columns) # list of employee datadata = [["1", 23], ["2", 21], ["3", 32], ] # specify column namescolumns = ['ID', 'Age'] # creating a dataframe from the lists of datadataframe2 = spark.createDataFrame(data, columns) # add columns in dataframe1 that are missing from dataframe2for column in [column for column in dataframe2.columns if column not in dataframe1.columns]: dataframe1 = dataframe1.withColumn(column, lit(None)) # add columns in dataframe2 that are missing from dataframe1for column in [column for column in dataframe1.columns if column not in dataframe2.columns]: dataframe2 = dataframe2.withColumn(column, lit(None)) # perform uniondataframe1.union(dataframe2).show()
Output:
Syntax: dataframe1.unionAll(dataframe2)
Python3
# importing moduleimport pyspark # import lit functionfrom pyspark.sql.functions import lit # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [["1", "sravan", "kakumanu"], ["2", "ojaswi", "hyd"], ["3", "rohith", "delhi"], ["4", "sridevi", "kakumanu"], ["5", "bobby", "guntur"]] # specify column namescolumns = ['ID', 'NAME', 'Address'] # creating a dataframe from the lists of datadataframe1 = spark.createDataFrame(data, columns) # list of employee datadata = [["1", 23], ["2", 21], ["3", 32], ] # specify column namescolumns = ['ID', 'Age'] # creating a dataframe from the lists of datadataframe2 = spark.createDataFrame(data, columns) # add columns in dataframe1 that are missing# from dataframe2for column in [column for column in dataframe2.columns\ if column not in dataframe1.columns]: dataframe1 = dataframe1.withColumn(column, lit(None)) # add columns in dataframe2 that are missing# from dataframe1for column in [column for column in dataframe1.columns \ if column not in dataframe2.columns]: dataframe2 = dataframe2.withColumn(column, lit(None)) # perform unionAlldataframe1.unionAll(dataframe2).show()
Output:
We can also perform unionByName, This will join dataframes by name.
Syntax: dataframe1.unionByName(dataframe2)
Example:
Python3
# importing moduleimport pyspark # import lit functionfrom pyspark.sql.functions import lit # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [["1", "sravan", "kakumanu"], ["2", "ojaswi", "hyd"], ["3", "rohith", "delhi"], ["4", "sridevi", "kakumanu"], ["5", "bobby", "guntur"]] # specify column namescolumns = ['ID', 'NAME', 'Address'] # creating a dataframe from the lists of datadataframe1 = spark.createDataFrame(data, columns) # list of employee datadata = [["1", 23], ["2", 21], ["3", 32], ] # specify column namescolumns = ['ID', 'Age'] # creating a dataframe from the lists of datadataframe2 = spark.createDataFrame(data, columns) # add columns in dataframe1 that are missing from dataframe2for column in [column for column in dataframe2.columns \ if column not in dataframe1.columns]: dataframe1 = dataframe1.withColumn(column, lit(None)) # add columns in dataframe2 that are missing from dataframe1for column in [column for column in dataframe1.columns \ if column not in dataframe2.columns]: dataframe2 = dataframe2.withColumn(column, lit(None)) # perform unionByNamedataframe1.unionByName(dataframe2).show()
Output:
sagartomar9927
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Dec, 2021"
},
{
"code": null,
"e": 156,
"s": 28,
"text": "In this article, we will discuss how to perform union on two dataframes with different amounts of columns in PySpark in Python."
},
{
"code": null,
"e": 214,
"s": 156,
"text": "Here we are having 3 columns named id, name, and address."
},
{
"code": null,
"e": 222,
"s": 214,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # import when and lit functionfrom pyspark.sql.functions import when, lit # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[\"1\", \"sravan\", \"kakumanu\"], [\"2\", \"ojaswi\", \"hyd\"], [\"3\", \"rohith\", \"delhi\"], [\"4\", \"sridevi\", \"kakumanu\"], [\"5\", \"bobby\", \"guntur\"]] # specify column namescolumns = ['ID', 'NAME', 'Address'] # creating a dataframe from the lists of datadataframe1 = spark.createDataFrame(data, columns) # displaydataframe1.show()",
"e": 897,
"s": 222,
"text": null
},
{
"code": null,
"e": 905,
"s": 897,
"text": "Output:"
},
{
"code": null,
"e": 958,
"s": 905,
"text": "Here we are going to create dataframe with 2 columns"
},
{
"code": null,
"e": 966,
"s": 958,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # import when and lit functionfrom pyspark.sql.functions import when, lit # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[\"1\", 23], [\"2\", 21], [\"3\", 32], ] # specify column namescolumns = ['ID', 'Age'] # creating a dataframe from the lists of datadataframe2 = spark.createDataFrame(data, columns) # displaydataframe2.show()",
"e": 1522,
"s": 966,
"text": null
},
{
"code": null,
"e": 1530,
"s": 1522,
"text": "Output:"
},
{
"code": null,
"e": 1780,
"s": 1530,
"text": "We can not perform union operations because the columns are different, so we have to add the missing columns. Here In first dataframe (dataframe1) , the columns [‘ID’, ‘NAME’, ‘Address’] and second dataframe (dataframe2 ) columns are [‘ID’,’Age’]."
},
{
"code": null,
"e": 2063,
"s": 1780,
"text": "Now we have to add the Age column to the first dataframe and NAME and Address in the second dataframe, we can do this by using lit() function. This function is available in pyspark.sql.functions which is used to add a column with a value. Here we are going to add a value with None."
},
{
"code": null,
"e": 2071,
"s": 2063,
"text": "Syntax:"
},
{
"code": null,
"e": 2164,
"s": 2071,
"text": "for column in [column for column in dataframe1.columns if column not in dataframe2.columns]:"
},
{
"code": null,
"e": 2222,
"s": 2164,
"text": " dataframe2 = dataframe2.withColumn(column, lit(None))"
},
{
"code": null,
"e": 2230,
"s": 2222,
"text": "where, "
},
{
"code": null,
"e": 2264,
"s": 2230,
"text": "dataframe1 is the firstdata frame"
},
{
"code": null,
"e": 2299,
"s": 2264,
"text": "dataframe2 is the second dataframe"
},
{
"code": null,
"e": 2307,
"s": 2299,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # import lit functionfrom pyspark.sql.functions import lit # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[\"1\", \"sravan\", \"kakumanu\"], [\"2\", \"ojaswi\", \"hyd\"], [\"3\", \"rohith\", \"delhi\"], [\"4\", \"sridevi\", \"kakumanu\"], [\"5\", \"bobby\", \"guntur\"]] # specify column namescolumns = ['ID', 'NAME', 'Address'] # creating a dataframe from the lists of datadataframe1 = spark.createDataFrame(data, columns) # list of employee datadata = [[\"1\", 23], [\"2\", 21], [\"3\", 32], ] # specify column namescolumns = ['ID', 'Age'] # creating a dataframe from the lists of datadataframe2 = spark.createDataFrame(data, columns) # add columns in dataframe1 that are missing from dataframe2for column in [column for column in dataframe2.columns if column not in dataframe1.columns]: dataframe1 = dataframe1.withColumn(column, lit(None)) # add columns in dataframe2 that are missing from dataframe1for column in [column for column in dataframe1.columns if column not in dataframe2.columns]: dataframe2 = dataframe2.withColumn(column, lit(None)) # now see the columns of dataframe1print(dataframe1.columns) # now see the columns of dataframe2print(dataframe2.columns)",
"e": 3740,
"s": 2307,
"text": null
},
{
"code": null,
"e": 3748,
"s": 3740,
"text": "Output:"
},
{
"code": null,
"e": 3814,
"s": 3748,
"text": "['ID', 'NAME', 'Address', 'Age']\n['ID', 'Age', 'NAME', 'Address']"
},
{
"code": null,
"e": 3906,
"s": 3814,
"text": "Now we can perform union by using union() function. This function will join two dataframes."
},
{
"code": null,
"e": 3943,
"s": 3906,
"text": "Syntax: dataframe1.union(dataframe2)"
},
{
"code": null,
"e": 3952,
"s": 3943,
"text": "Example:"
},
{
"code": null,
"e": 3960,
"s": 3952,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # import lit functionfrom pyspark.sql.functions import lit # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[\"1\", \"sravan\", \"kakumanu\"], [\"2\", \"ojaswi\", \"hyd\"], [\"3\", \"rohith\", \"delhi\"], [\"4\", \"sridevi\", \"kakumanu\"], [\"5\", \"bobby\", \"guntur\"]] # specify column namescolumns = ['ID', 'NAME', 'Address'] # creating a dataframe from the lists of datadataframe1 = spark.createDataFrame(data, columns) # list of employee datadata = [[\"1\", 23], [\"2\", 21], [\"3\", 32], ] # specify column namescolumns = ['ID', 'Age'] # creating a dataframe from the lists of datadataframe2 = spark.createDataFrame(data, columns) # add columns in dataframe1 that are missing from dataframe2for column in [column for column in dataframe2.columns if column not in dataframe1.columns]: dataframe1 = dataframe1.withColumn(column, lit(None)) # add columns in dataframe2 that are missing from dataframe1for column in [column for column in dataframe1.columns if column not in dataframe2.columns]: dataframe2 = dataframe2.withColumn(column, lit(None)) # perform uniondataframe1.union(dataframe2).show()",
"e": 5322,
"s": 3960,
"text": null
},
{
"code": null,
"e": 5330,
"s": 5322,
"text": "Output:"
},
{
"code": null,
"e": 5370,
"s": 5330,
"text": "Syntax: dataframe1.unionAll(dataframe2)"
},
{
"code": null,
"e": 5378,
"s": 5370,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # import lit functionfrom pyspark.sql.functions import lit # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[\"1\", \"sravan\", \"kakumanu\"], [\"2\", \"ojaswi\", \"hyd\"], [\"3\", \"rohith\", \"delhi\"], [\"4\", \"sridevi\", \"kakumanu\"], [\"5\", \"bobby\", \"guntur\"]] # specify column namescolumns = ['ID', 'NAME', 'Address'] # creating a dataframe from the lists of datadataframe1 = spark.createDataFrame(data, columns) # list of employee datadata = [[\"1\", 23], [\"2\", 21], [\"3\", 32], ] # specify column namescolumns = ['ID', 'Age'] # creating a dataframe from the lists of datadataframe2 = spark.createDataFrame(data, columns) # add columns in dataframe1 that are missing# from dataframe2for column in [column for column in dataframe2.columns\\ if column not in dataframe1.columns]: dataframe1 = dataframe1.withColumn(column, lit(None)) # add columns in dataframe2 that are missing# from dataframe1for column in [column for column in dataframe1.columns \\ if column not in dataframe2.columns]: dataframe2 = dataframe2.withColumn(column, lit(None)) # perform unionAlldataframe1.unionAll(dataframe2).show()",
"e": 6751,
"s": 5378,
"text": null
},
{
"code": null,
"e": 6759,
"s": 6751,
"text": "Output:"
},
{
"code": null,
"e": 6827,
"s": 6759,
"text": "We can also perform unionByName, This will join dataframes by name."
},
{
"code": null,
"e": 6870,
"s": 6827,
"text": "Syntax: dataframe1.unionByName(dataframe2)"
},
{
"code": null,
"e": 6879,
"s": 6870,
"text": "Example:"
},
{
"code": null,
"e": 6887,
"s": 6879,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # import lit functionfrom pyspark.sql.functions import lit # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[\"1\", \"sravan\", \"kakumanu\"], [\"2\", \"ojaswi\", \"hyd\"], [\"3\", \"rohith\", \"delhi\"], [\"4\", \"sridevi\", \"kakumanu\"], [\"5\", \"bobby\", \"guntur\"]] # specify column namescolumns = ['ID', 'NAME', 'Address'] # creating a dataframe from the lists of datadataframe1 = spark.createDataFrame(data, columns) # list of employee datadata = [[\"1\", 23], [\"2\", 21], [\"3\", 32], ] # specify column namescolumns = ['ID', 'Age'] # creating a dataframe from the lists of datadataframe2 = spark.createDataFrame(data, columns) # add columns in dataframe1 that are missing from dataframe2for column in [column for column in dataframe2.columns \\ if column not in dataframe1.columns]: dataframe1 = dataframe1.withColumn(column, lit(None)) # add columns in dataframe2 that are missing from dataframe1for column in [column for column in dataframe1.columns \\ if column not in dataframe2.columns]: dataframe2 = dataframe2.withColumn(column, lit(None)) # perform unionByNamedataframe1.unionByName(dataframe2).show()",
"e": 8265,
"s": 6887,
"text": null
},
{
"code": null,
"e": 8273,
"s": 8265,
"text": "Output:"
},
{
"code": null,
"e": 8288,
"s": 8273,
"text": "sagartomar9927"
},
{
"code": null,
"e": 8295,
"s": 8288,
"text": "Picked"
},
{
"code": null,
"e": 8310,
"s": 8295,
"text": "Python-Pyspark"
},
{
"code": null,
"e": 8317,
"s": 8310,
"text": "Python"
},
{
"code": null,
"e": 8415,
"s": 8317,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8433,
"s": 8415,
"text": "Python Dictionary"
},
{
"code": null,
"e": 8475,
"s": 8433,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 8497,
"s": 8475,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 8532,
"s": 8497,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 8558,
"s": 8532,
"text": "Python String | replace()"
},
{
"code": null,
"e": 8590,
"s": 8558,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 8619,
"s": 8590,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 8646,
"s": 8619,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 8667,
"s": 8646,
"text": "Python OOPs Concepts"
}
] |
How to change the width of an iframe to 100% using JavaScript ?
|
30 Jul, 2020
Given an HTML document containing an <iframe> element and the task is to change the width of the <iframe> element to 100% with the help of JavaScript. There are two methods to change the width of the iframe which are discussed below:
Method 1: This method uses id attribute of iframe with width property to change the width of <iframe> element. JavaScript’s code is written within the <script> tag.
HTML
<!DOCTYPE html><html> <head> <title> How to change the width of an iframe to 100% with JavaScript? </title> </head> <body> <center> <h1 style="color:green;"> GeeksforGeeks </h1> <h3> How to change the width of a <br> to 100% with JavaScript? </h3> <iframe id="iframe" height="100%" width="40%" src="https://www.youtube.com/embed/HzeK7g8cD0Y" frameborder="0" allowfullscreen> </iframe> <br><br> <button onclick="changewidth()"> Click to change </button> <script> // JavaScript code to change the // width to 100% of <iframe> function changewidth() { var x = document.getElementById('iframe'); x.style.width = "100%"; } </script> </center></body> </html>
Output:
Before clicking the button:
After clicking the button:
Method 2: This method uses the id attribute of the iframe with window.innerWidth property to change the width of <iframe> element. JavaScript code is written within the <script> tag.
HTML
<!DOCTYPE html><html> <head> <title> How to change the width of an iframe to 100% with JavaScript? </title> </head> <body> <center> <h1 style="color:green;"> GeeksforGeeks </h1> <h3> How to change the width of a <br> to 100% with JavaScript? </h3> <iframe id="iframe" height="100%" width="40%" src="https://www.youtube.com/embed/HzeK7g8cD0Y" frameborder="0" allowfullscreen> </iframe> <br><br> <button onclick="changewidth()"> Click to change </button> <script> // JavaScript code to change the // width to 100% of <iframe> function changewidth() { var x = document.getElementById('iframe'); x.style.width = window.innerWidth; } </script> </center></body> </html>
Output:
Before clicking the button:
After clicking the button:
CSS-Misc
HTML-Misc
JavaScript-Misc
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jul, 2020"
},
{
"code": null,
"e": 262,
"s": 28,
"text": "Given an HTML document containing an <iframe> element and the task is to change the width of the <iframe> element to 100% with the help of JavaScript. There are two methods to change the width of the iframe which are discussed below:"
},
{
"code": null,
"e": 427,
"s": 262,
"text": "Method 1: This method uses id attribute of iframe with width property to change the width of <iframe> element. JavaScript’s code is written within the <script> tag."
},
{
"code": null,
"e": 432,
"s": 427,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to change the width of an iframe to 100% with JavaScript? </title> </head> <body> <center> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h3> How to change the width of a <br> to 100% with JavaScript? </h3> <iframe id=\"iframe\" height=\"100%\" width=\"40%\" src=\"https://www.youtube.com/embed/HzeK7g8cD0Y\" frameborder=\"0\" allowfullscreen> </iframe> <br><br> <button onclick=\"changewidth()\"> Click to change </button> <script> // JavaScript code to change the // width to 100% of <iframe> function changewidth() { var x = document.getElementById('iframe'); x.style.width = \"100%\"; } </script> </center></body> </html>",
"e": 1378,
"s": 432,
"text": null
},
{
"code": null,
"e": 1386,
"s": 1378,
"text": "Output:"
},
{
"code": null,
"e": 1414,
"s": 1386,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 1441,
"s": 1414,
"text": "After clicking the button:"
},
{
"code": null,
"e": 1624,
"s": 1441,
"text": "Method 2: This method uses the id attribute of the iframe with window.innerWidth property to change the width of <iframe> element. JavaScript code is written within the <script> tag."
},
{
"code": null,
"e": 1629,
"s": 1624,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to change the width of an iframe to 100% with JavaScript? </title> </head> <body> <center> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h3> How to change the width of a <br> to 100% with JavaScript? </h3> <iframe id=\"iframe\" height=\"100%\" width=\"40%\" src=\"https://www.youtube.com/embed/HzeK7g8cD0Y\" frameborder=\"0\" allowfullscreen> </iframe> <br><br> <button onclick=\"changewidth()\"> Click to change </button> <script> // JavaScript code to change the // width to 100% of <iframe> function changewidth() { var x = document.getElementById('iframe'); x.style.width = window.innerWidth; } </script> </center></body> </html>",
"e": 2584,
"s": 1629,
"text": null
},
{
"code": null,
"e": 2592,
"s": 2584,
"text": "Output:"
},
{
"code": null,
"e": 2620,
"s": 2592,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 2647,
"s": 2620,
"text": "After clicking the button:"
},
{
"code": null,
"e": 2656,
"s": 2647,
"text": "CSS-Misc"
},
{
"code": null,
"e": 2666,
"s": 2656,
"text": "HTML-Misc"
},
{
"code": null,
"e": 2682,
"s": 2666,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 2686,
"s": 2682,
"text": "CSS"
},
{
"code": null,
"e": 2691,
"s": 2686,
"text": "HTML"
},
{
"code": null,
"e": 2702,
"s": 2691,
"text": "JavaScript"
},
{
"code": null,
"e": 2719,
"s": 2702,
"text": "Web Technologies"
},
{
"code": null,
"e": 2746,
"s": 2719,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2751,
"s": 2746,
"text": "HTML"
}
] |
Johnson’s algorithm for All-pairs shortest paths
|
23 Jun, 2022
The problem is to find the shortest paths between every pair of vertices in a given weighted directed Graph and weights may be negative. We have discussed Floyd Warshall Algorithm for this problem. The time complexity of the Floyd Warshall Algorithm is Θ(V3).
Using Johnson’s algorithm, we can find all pair shortest paths in O(V2log V + VE) time. Johnson’s algorithm uses both Dijkstra and Bellman-Ford as subroutines. If we apply Dijkstra’s Single Source shortest path algorithm for every vertex, considering every vertex as the source, we can find all pair shortest paths in O(V*VLogV) time.
So using Dijkstra’s single-source shortest path seems to be a better option than Floyd Warshall’s Algorithm(https://www.geeksforgeeks.org/floyd-warshall-algorithm-dp-16/?ref=lbp) , but the problem with Dijkstra’s algorithm is, that it doesn’t work for negative weight edge. The idea of Johnson’s algorithm is to re-weight all edges and make them all positive, then apply Dijkstra’s algorithm for every vertex.
How to transform a given graph into a graph with all non-negative weight edges?
One may think of a simple approach of finding the minimum weight edge and adding this weight to all edges. Unfortunately, this doesn’t work as there may be a different number of edges in different paths (See this for an example). If there are multiple paths from a vertex u to v, then all paths must be increased by the same amount, so that the shortest path remains the shortest in the transformed graph. The idea of Johnson’s algorithm is to assign a weight to every vertex. Let the weight assigned to vertex u be h[u].
We reweight edges using vertex weights. For example, for an edge (u, v) of weight w(u, v), the new weight becomes w(u, v) + h[u] – h[v]. The great thing about this reweighting is, that all set of paths between any two vertices is increased by the same amount and all negative weights become non-negative. Consider any path between two vertices s and t, the weight of every path is increased by h[s] – h[t], and all h[] values of vertices on the path from s to t cancel each other.
How do we calculate h[] values?
Bellman-Ford algorithm is used for this purpose. Following is the complete algorithm. A new vertex is added to the graph and connected to all existing vertices. The shortest distance values from the new vertex to all existing vertices are h[] values.
Algorithm:
Let the given graph be G. Add a new vertex s to the graph, add edges from the new vertex to all vertices of G. Let the modified graph be G’. Run the Bellman-Ford algorithm on G’ with s as the source. Let the distances calculated by Bellman-Ford be h[0], h[1], .. h[V-1]. If we find a negative weight cycle, then return. Note that the negative weight cycle cannot be created by new vertex s as there is no edge to s. All edges are from s. Reweight the edges of the original graph. For each edge (u, v), assign the new weight as “original weight + h[u] – h[v]”. Remove the added vertex s and run Dijkstra’s algorithm for every vertex.
Let the given graph be G. Add a new vertex s to the graph, add edges from the new vertex to all vertices of G. Let the modified graph be G’.
Run the Bellman-Ford algorithm on G’ with s as the source. Let the distances calculated by Bellman-Ford be h[0], h[1], .. h[V-1]. If we find a negative weight cycle, then return. Note that the negative weight cycle cannot be created by new vertex s as there is no edge to s. All edges are from s.
Reweight the edges of the original graph. For each edge (u, v), assign the new weight as “original weight + h[u] – h[v]”.
Remove the added vertex s and run Dijkstra’s algorithm for every vertex.
How does the transformation ensure nonnegative weight edges?
The following property is always true about h[] values as they are the shortest distances.
h[v] <= h[u] + w(u, v)
The property simply means that the shortest distance from s to v must be smaller than or equal to the shortest distance from s to u plus the weight of the edge (u, v). The new weights are w(u, v) + h[u] – h[v]. The value of the new weights must be greater than or equal to zero because of the inequality “h[v] <= h[u] + w(u, v)”.
Example: Let us consider the following graph.
We add a source s and add edges from s to all vertices of the original graph. In the following diagram s is 4.
We calculate the shortest distances from 4 to all other vertices using Bellman-Ford algorithm. The shortest distances from 4 to 0, 1, 2 and 3 are 0, -5, -1 and 0 respectively, i.e., h[] = {0, -5, -1, 0}. Once we get these distances, we remove the source vertex 4 and reweight the edges using following formula. w(u, v) = w(u, v) + h[u] – h[v].
Since all weights are positive now, we can run Dijkstra’s shortest path algorithm for every vertex as the source.
Time Complexity: The main steps in the algorithm are Bellman-Ford Algorithm called once and Dijkstra called V times. Time complexity of Bellman Ford is O(VE) and time complexity of Dijkstra is O(VLogV). So overall time complexity is O(V2log V + VE).
The time complexity of Johnson’s algorithm becomes the same as Floyd Warshall’s Algorithm (https://www.geeksforgeeks.org/floyd-warshall-algorithm-dp-16/?ref=lbp)
when the graph is complete (For a complete graph E = O(V2). But for sparse graphs, the algorithm performs much better than Floyd Warshall’s Algorithm( https://www.geeksforgeeks.org/floyd-warshall-algorithm-dp-16/?ref=lbp ).
raj2002
hardikkoriintern
Shortest Path
Graph
Graph
Shortest Path
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Dijkstra's shortest path algorithm | Greedy Algo-7
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Find if there is a path between two vertices in a directed graph
Detect Cycle in a Directed Graph
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
Bellman–Ford Algorithm | DP-23
Find if there is a path between two vertices in an undirected graph
Minimum number of swaps required to sort an array
Minimum steps to reach target by a Knight | Set 1
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 314,
"s": 52,
"text": "The problem is to find the shortest paths between every pair of vertices in a given weighted directed Graph and weights may be negative. We have discussed Floyd Warshall Algorithm for this problem. The time complexity of the Floyd Warshall Algorithm is Θ(V3). "
},
{
"code": null,
"e": 650,
"s": 314,
"text": "Using Johnson’s algorithm, we can find all pair shortest paths in O(V2log V + VE) time. Johnson’s algorithm uses both Dijkstra and Bellman-Ford as subroutines. If we apply Dijkstra’s Single Source shortest path algorithm for every vertex, considering every vertex as the source, we can find all pair shortest paths in O(V*VLogV) time. "
},
{
"code": null,
"e": 1061,
"s": 650,
"text": "So using Dijkstra’s single-source shortest path seems to be a better option than Floyd Warshall’s Algorithm(https://www.geeksforgeeks.org/floyd-warshall-algorithm-dp-16/?ref=lbp) , but the problem with Dijkstra’s algorithm is, that it doesn’t work for negative weight edge. The idea of Johnson’s algorithm is to re-weight all edges and make them all positive, then apply Dijkstra’s algorithm for every vertex. "
},
{
"code": null,
"e": 1142,
"s": 1061,
"text": "How to transform a given graph into a graph with all non-negative weight edges? "
},
{
"code": null,
"e": 1665,
"s": 1142,
"text": "One may think of a simple approach of finding the minimum weight edge and adding this weight to all edges. Unfortunately, this doesn’t work as there may be a different number of edges in different paths (See this for an example). If there are multiple paths from a vertex u to v, then all paths must be increased by the same amount, so that the shortest path remains the shortest in the transformed graph. The idea of Johnson’s algorithm is to assign a weight to every vertex. Let the weight assigned to vertex u be h[u]. "
},
{
"code": null,
"e": 2147,
"s": 1665,
"text": "We reweight edges using vertex weights. For example, for an edge (u, v) of weight w(u, v), the new weight becomes w(u, v) + h[u] – h[v]. The great thing about this reweighting is, that all set of paths between any two vertices is increased by the same amount and all negative weights become non-negative. Consider any path between two vertices s and t, the weight of every path is increased by h[s] – h[t], and all h[] values of vertices on the path from s to t cancel each other. "
},
{
"code": null,
"e": 2180,
"s": 2147,
"text": "How do we calculate h[] values? "
},
{
"code": null,
"e": 2432,
"s": 2180,
"text": "Bellman-Ford algorithm is used for this purpose. Following is the complete algorithm. A new vertex is added to the graph and connected to all existing vertices. The shortest distance values from the new vertex to all existing vertices are h[] values. "
},
{
"code": null,
"e": 2444,
"s": 2432,
"text": "Algorithm: "
},
{
"code": null,
"e": 3078,
"s": 2444,
"text": "Let the given graph be G. Add a new vertex s to the graph, add edges from the new vertex to all vertices of G. Let the modified graph be G’. Run the Bellman-Ford algorithm on G’ with s as the source. Let the distances calculated by Bellman-Ford be h[0], h[1], .. h[V-1]. If we find a negative weight cycle, then return. Note that the negative weight cycle cannot be created by new vertex s as there is no edge to s. All edges are from s. Reweight the edges of the original graph. For each edge (u, v), assign the new weight as “original weight + h[u] – h[v]”. Remove the added vertex s and run Dijkstra’s algorithm for every vertex. "
},
{
"code": null,
"e": 3220,
"s": 3078,
"text": "Let the given graph be G. Add a new vertex s to the graph, add edges from the new vertex to all vertices of G. Let the modified graph be G’. "
},
{
"code": null,
"e": 3518,
"s": 3220,
"text": "Run the Bellman-Ford algorithm on G’ with s as the source. Let the distances calculated by Bellman-Ford be h[0], h[1], .. h[V-1]. If we find a negative weight cycle, then return. Note that the negative weight cycle cannot be created by new vertex s as there is no edge to s. All edges are from s. "
},
{
"code": null,
"e": 3641,
"s": 3518,
"text": "Reweight the edges of the original graph. For each edge (u, v), assign the new weight as “original weight + h[u] – h[v]”. "
},
{
"code": null,
"e": 3715,
"s": 3641,
"text": "Remove the added vertex s and run Dijkstra’s algorithm for every vertex. "
},
{
"code": null,
"e": 3777,
"s": 3715,
"text": "How does the transformation ensure nonnegative weight edges? "
},
{
"code": null,
"e": 3868,
"s": 3777,
"text": "The following property is always true about h[] values as they are the shortest distances."
},
{
"code": null,
"e": 3895,
"s": 3868,
"text": " h[v] <= h[u] + w(u, v) "
},
{
"code": null,
"e": 4226,
"s": 3895,
"text": "The property simply means that the shortest distance from s to v must be smaller than or equal to the shortest distance from s to u plus the weight of the edge (u, v). The new weights are w(u, v) + h[u] – h[v]. The value of the new weights must be greater than or equal to zero because of the inequality “h[v] <= h[u] + w(u, v)”. "
},
{
"code": null,
"e": 4273,
"s": 4226,
"text": "Example: Let us consider the following graph. "
},
{
"code": null,
"e": 4386,
"s": 4273,
"text": " We add a source s and add edges from s to all vertices of the original graph. In the following diagram s is 4. "
},
{
"code": null,
"e": 4734,
"s": 4390,
"text": "We calculate the shortest distances from 4 to all other vertices using Bellman-Ford algorithm. The shortest distances from 4 to 0, 1, 2 and 3 are 0, -5, -1 and 0 respectively, i.e., h[] = {0, -5, -1, 0}. Once we get these distances, we remove the source vertex 4 and reweight the edges using following formula. w(u, v) = w(u, v) + h[u] – h[v]."
},
{
"code": null,
"e": 4852,
"s": 4737,
"text": "Since all weights are positive now, we can run Dijkstra’s shortest path algorithm for every vertex as the source. "
},
{
"code": null,
"e": 5103,
"s": 4852,
"text": "Time Complexity: The main steps in the algorithm are Bellman-Ford Algorithm called once and Dijkstra called V times. Time complexity of Bellman Ford is O(VE) and time complexity of Dijkstra is O(VLogV). So overall time complexity is O(V2log V + VE). "
},
{
"code": null,
"e": 5265,
"s": 5103,
"text": "The time complexity of Johnson’s algorithm becomes the same as Floyd Warshall’s Algorithm (https://www.geeksforgeeks.org/floyd-warshall-algorithm-dp-16/?ref=lbp)"
},
{
"code": null,
"e": 5490,
"s": 5265,
"text": "when the graph is complete (For a complete graph E = O(V2). But for sparse graphs, the algorithm performs much better than Floyd Warshall’s Algorithm( https://www.geeksforgeeks.org/floyd-warshall-algorithm-dp-16/?ref=lbp ). "
},
{
"code": null,
"e": 5498,
"s": 5490,
"text": "raj2002"
},
{
"code": null,
"e": 5515,
"s": 5498,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 5529,
"s": 5515,
"text": "Shortest Path"
},
{
"code": null,
"e": 5535,
"s": 5529,
"text": "Graph"
},
{
"code": null,
"e": 5541,
"s": 5535,
"text": "Graph"
},
{
"code": null,
"e": 5555,
"s": 5541,
"text": "Shortest Path"
},
{
"code": null,
"e": 5653,
"s": 5555,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5704,
"s": 5653,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 5762,
"s": 5704,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 5827,
"s": 5762,
"text": "Find if there is a path between two vertices in a directed graph"
},
{
"code": null,
"e": 5860,
"s": 5827,
"text": "Detect Cycle in a Directed Graph"
},
{
"code": null,
"e": 5892,
"s": 5860,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 5956,
"s": 5892,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 5987,
"s": 5956,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 6055,
"s": 5987,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 6105,
"s": 6055,
"text": "Minimum number of swaps required to sort an array"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.